/* Copyright 2017 Vector Creations Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #import "WidgetManager.h" #pragma mark - Contants NSString *const kWidgetEventTypeString = @"im.vector.modular.widgets"; NSString *const kWidgetTypeJitsi = @"jitsi"; NSString *const kMXKWidgetManagerDidUpdateWidgetNotification = @"kMXKWidgetManagerDidUpdateWidgetNotification"; NSString *const WidgetManagerErrorDomain = @"WidgetManagerErrorDomain"; @interface WidgetManager () { // MXSession kind of hash -> Listener for matrix events for widgets. // There is one per matrix session NSMutableDictionary *widgetEventListener; } @end @implementation WidgetManager + (instancetype)sharedManager { static WidgetManager *sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedManager = [[WidgetManager alloc] init]; }); return sharedManager; } - (instancetype)init { self = [super init]; if (self) { widgetEventListener = [NSMutableDictionary dictionary]; } return self; } - (NSArray *)widgetsInRoom:(MXRoom *)room { return [self widgetsOfTypes:nil inRoom:room]; } - (NSArray *)widgetsOfTypes:(NSArray *)widgetTypes inRoom:(MXRoom *)room { // Widget id -> widget NSMutableDictionary *widgets = [NSMutableDictionary dictionary]; // Get all im.vector.modular.widgets state events in the room NSMutableArray *widgetEvents = [NSMutableArray arrayWithArray:[room.state stateEventsWithType:kWidgetEventTypeString]]; // There can be several im.vector.modular.widgets state events for a same widget but // only the last one must be considered. // Order widgetEvents with the last event first [widgetEvents sortUsingComparator:^NSComparisonResult(MXEvent *event1, MXEvent *event2) { NSComparisonResult result = NSOrderedAscending; if (event2.originServerTs > event1.originServerTs) { result = NSOrderedDescending; } else if (event2.originServerTs == event1.originServerTs) { result = NSOrderedSame; } return result; }]; // Create each widget from its lastest im.vector.modular.widgets state event for (MXEvent *widgetEvent in widgetEvents) { // Filter widget types if required if (widgetTypes) { NSString *widgetType; MXJSONModelSetString(widgetType, widgetEvent.content[@"type"]); if (widgetType && NSNotFound == [widgetTypes indexOfObject:widgetType]) { continue; } } // widgetEvent.stateKey = widget id if (!widgets[widgetEvent.stateKey]) { Widget *widget = [[Widget alloc] initWithWidgetEvent:widgetEvent inMatrixSession:room.mxSession]; if (widget) { widgets[widget.widgetId] = widget; } } } // Return active widgets only NSMutableArray *activeWidgets = [NSMutableArray array]; for (Widget *widget in widgets.allValues) { if (widget.isActive) { [activeWidgets addObject:widget]; } } return activeWidgets; } - (MXHTTPOperation *)closeWidget:(NSString *)widgetId inRoom:(MXRoom *)room success:(void (^)())success failure:(void (^)(NSError *))failure { NSError *permissionError = [self checkWidgetPermissionInRoom:room]; if (permissionError) { if (failure) { failure(permissionError); } return nil; } // Send a state event with an empty content to disable the widget return [room sendStateEventOfType:kWidgetEventTypeString content:@{} stateKey:widgetId success:^(NSString *eventId) { if (success) { success(); } } failure:failure]; } /** Check user's power for widgets management in a room. @param room the room to check. @return an NSError if the user cannot act on widgets in this room. Else, nil. */ - (NSError *)checkWidgetPermissionInRoom:(MXRoom *)room { NSError *error; // Check user's power in the room MXRoomPowerLevels *powerLevels = room.state.powerLevels; NSInteger oneSelfPowerLevel = [powerLevels powerLevelOfUserWithUserID:room.mxSession.myUser.userId]; // The user must be able to send state events to manage widgets if (oneSelfPowerLevel < powerLevels.stateDefault) { error = [NSError errorWithDomain:WidgetManagerErrorDomain code:WidgetManagerErrorCodeNotEnoughPower userInfo:@{ NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"widget_no_power_to_manage", @"Vector", nil) }]; } return error; } - (void)addMatrixSession:(MXSession *)mxSession { __weak __typeof__(self) weakSelf = self; id listener = [mxSession listenToEventsOfTypes:@[kWidgetEventTypeString] onEvent:^(MXEvent *event, MXTimelineDirection direction, id customObject) { typeof(self) self = weakSelf; if (self && direction == MXTimelineDirectionForwards) { Widget *widget = [[Widget alloc] initWithWidgetEvent:event inMatrixSession:mxSession]; if (widget) { [[NSNotificationCenter defaultCenter] postNotificationName:kMXKWidgetManagerDidUpdateWidgetNotification object:widget]; } } }]; NSString *hash = [NSString stringWithFormat:@"%p", mxSession]; widgetEventListener[hash] = listener; } - (void)removeMatrixSession:(MXSession *)mxSession { // mxSession.myUser.userId and mxSession.matrixRestClient.credentials.userId may be nil here // So, use a kind of hash value instead NSString *hash = [NSString stringWithFormat:@"%p", mxSession]; id listener = widgetEventListener[hash]; [mxSession removeListener:listener]; [widgetEventListener removeObjectForKey:hash]; } @end