RoomsTableViewController.m 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  1. /**
  2. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  3. * SPDX-License-Identifier: GPL-3.0-or-later
  4. */
  5. #import "RoomsTableViewController.h"
  6. @import NextcloudKit;
  7. #import <Realm/Realm.h>
  8. #import "NextcloudTalk-Swift.h"
  9. #import "JDStatusBarNotification.h"
  10. #import "CCCertificate.h"
  11. #import "NCAPIController.h"
  12. #import "NCAppBranding.h"
  13. #import "NCDatabaseManager.h"
  14. #import "NCConnectionController.h"
  15. #import "NCNavigationController.h"
  16. #import "NCNotificationController.h"
  17. #import "NCRoomsManager.h"
  18. #import "NCSettingsController.h"
  19. #import "NCUserInterfaceController.h"
  20. #import "NotificationCenterNotifications.h"
  21. #import "PlaceholderView.h"
  22. #import "RoomInfoTableViewController.h"
  23. #import "RoomSearchTableViewController.h"
  24. #import "UIBarButtonItem+Badge.h"
  25. typedef void (^FetchRoomsCompletionBlock)(BOOL success);
  26. typedef enum RoomsFilter {
  27. kRoomsFilterAll = 0,
  28. kRoomsFilterUnread,
  29. kRoomsFilterMentioned
  30. } RoomsFilter;
  31. typedef enum RoomsSections {
  32. kRoomsSectionPendingFederationInvitation = 0,
  33. kRoomsSectionRoomList
  34. } RoomsSections;
  35. @interface RoomsTableViewController () <CCCertificateDelegate, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating, UserStatusViewDelegate>
  36. {
  37. RLMNotificationToken *_rlmNotificationToken;
  38. NSMutableArray *_rooms;
  39. NSMutableArray *_allRooms;
  40. UIRefreshControl *_refreshControl;
  41. BOOL _allowEmptyGroupRooms;
  42. UISearchController *_searchController;
  43. NSString *_searchString;
  44. RoomSearchTableViewController *_resultTableViewController;
  45. NCUnifiedSearchController *_unifiedSearchController;
  46. PlaceholderView *_roomsBackgroundView;
  47. UIBarButtonItem *_newConversationButton;
  48. UIBarButtonItem *_settingsButton;
  49. UIButton *_profileButton;
  50. NCUserStatus *_activeUserStatus;
  51. NSTimer *_refreshRoomsTimer;
  52. NSIndexPath *_nextRoomWithMentionIndexPath;
  53. NSIndexPath *_lastRoomWithMentionIndexPath;
  54. UIButton *_unreadMentionsBottomButton;
  55. NCNavigationController *_contextChatNavigationController;
  56. }
  57. @property (nonatomic, copy, nullable) void (^contextMenuActionBlock)(void);
  58. @end
  59. @implementation RoomsTableViewController
  60. - (void)viewDidLoad
  61. {
  62. [super viewDidLoad];
  63. __weak typeof(self) weakSelf = self;
  64. _rlmNotificationToken = [[NCRoom allObjects] addNotificationBlock:^(RLMResults * _Nullable results, RLMCollectionChange * _Nullable change, NSError * _Nullable error) {
  65. [weakSelf refreshRoomList];
  66. }];
  67. [self.tableView registerNib:[UINib nibWithNibName:RoomTableViewCell.nibName bundle:nil] forCellReuseIdentifier:RoomTableViewCell.identifier];
  68. [self.tableView registerNib:[UINib nibWithNibName:RoomInvitationViewCell.NibName bundle:nil] forCellReuseIdentifier:RoomInvitationViewCell.ReuseIdentifier];
  69. // Align header's title to ContactsTableViewCell's label
  70. self.tableView.separatorInset = UIEdgeInsetsMake(0, 52, 0, 0);
  71. self.tableView.separatorInsetReference = UITableViewSeparatorInsetFromAutomaticInsets;
  72. self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
  73. _resultTableViewController = [[RoomSearchTableViewController alloc] initWithStyle:UITableViewStyleInsetGrouped];
  74. _searchController = [[UISearchController alloc] initWithSearchResultsController:_resultTableViewController];
  75. _searchController.searchResultsUpdater = self;
  76. [_searchController.searchBar sizeToFit];
  77. if (@available(iOS 16.0, *)) {
  78. _searchController.scopeBarActivation = UISearchControllerScopeBarActivationOnSearchActivation;
  79. } else {
  80. _searchController.automaticallyShowsScopeBar = YES;
  81. }
  82. _searchController.searchBar.scopeButtonTitles = [self getFilters];
  83. [self setupNavigationBar];
  84. // We want ourselves to be the delegate for the result table so didSelectRowAtIndexPath is called for both tables.
  85. _resultTableViewController.tableView.delegate = self;
  86. _searchController.delegate = self;
  87. _searchController.searchBar.delegate = self;
  88. self.definesPresentationContext = YES;
  89. // Rooms placeholder view
  90. _roomsBackgroundView = [[PlaceholderView alloc] init];
  91. [_roomsBackgroundView setImage:[UIImage imageNamed:@"conversations-placeholder"]];
  92. [_roomsBackgroundView.placeholderTextView setText:NSLocalizedString(@"You are not part of any conversation. Press + to start a new one.", nil)];
  93. [_roomsBackgroundView.placeholderView setHidden:YES];
  94. [_roomsBackgroundView.loadingView startAnimating];
  95. self.tableView.backgroundView = _roomsBackgroundView;
  96. // Unread mentions bottom indicator
  97. _unreadMentionsBottomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 126, 28)];
  98. _unreadMentionsBottomButton.backgroundColor = [NCAppBranding themeColor];
  99. [_unreadMentionsBottomButton setTitleColor:[NCAppBranding themeTextColor] forState:UIControlStateNormal];
  100. _unreadMentionsBottomButton.titleLabel.font = [UIFont systemFontOfSize:14];
  101. _unreadMentionsBottomButton.layer.cornerRadius = 14;
  102. _unreadMentionsBottomButton.clipsToBounds = YES;
  103. _unreadMentionsBottomButton.hidden = NO;
  104. _unreadMentionsBottomButton.translatesAutoresizingMaskIntoConstraints = NO;
  105. _unreadMentionsBottomButton.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 12.0f, 0.0f, 12.0f);
  106. _unreadMentionsBottomButton.titleLabel.minimumScaleFactor = 0.9f;
  107. _unreadMentionsBottomButton.titleLabel.numberOfLines = 1;
  108. _unreadMentionsBottomButton.titleLabel.adjustsFontSizeToFitWidth = YES;
  109. NSString *unreadMentionsString = NSLocalizedString(@"Unread mentions", nil);
  110. NSString *buttonText = [NSString stringWithFormat:@"↓ %@", unreadMentionsString];
  111. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14]};
  112. CGRect textSize = [buttonText boundingRectWithSize:CGSizeMake(300, 28) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:NULL];
  113. CGFloat buttonWidth = textSize.size.width + 20;
  114. [_unreadMentionsBottomButton addTarget:self action:@selector(unreadMentionsBottomButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
  115. [_unreadMentionsBottomButton setTitle:buttonText forState:UIControlStateNormal];
  116. [self.view addSubview:_unreadMentionsBottomButton];
  117. // Set selection color for selected cells
  118. [self.tableView setTintColor:UIColor.systemGray4Color];
  119. // Remove the backButtonTitle, otherwise when we transition to a conversation, "Back" is briefly visible
  120. self.navigationItem.backButtonTitle = @"";
  121. NSDictionary *views = @{@"unreadMentionsButton": _unreadMentionsBottomButton};
  122. NSDictionary *metrics = @{@"buttonWidth": @(buttonWidth)};
  123. UILayoutGuide *margins = self.view.layoutMarginsGuide;
  124. [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(>=0)-[unreadMentionsButton(28)]-30-|" options:0 metrics:nil views:views]];
  125. [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(>=0)-[unreadMentionsButton(buttonWidth)]-(>=0)-|" options:0 metrics:metrics views:views]];
  126. [NSLayoutConstraint activateConstraints:@[[_unreadMentionsBottomButton.centerXAnchor constraintEqualToAnchor:margins.centerXAnchor]]];
  127. [self.view addConstraint:[_unreadMentionsBottomButton.bottomAnchor constraintEqualToAnchor:self.tableView.safeAreaLayoutGuide.bottomAnchor constant:-20]];
  128. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appStateHasChanged:) name:NCAppStateHasChangedNotification object:nil];
  129. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectionStateHasChanged:) name:NCConnectionStateHasChangedNotification object:nil];
  130. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(roomsDidUpdate:) name:NCRoomsManagerDidUpdateRoomsNotification object:nil];
  131. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationWillBePresented:) name:NCNotificationControllerWillPresentNotification object:nil];
  132. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serverCapabilitiesUpdated:) name:NCServerCapabilitiesUpdatedNotification object:nil];
  133. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userProfileImageUpdated:) name:NCUserProfileImageUpdatedNotification object:nil];
  134. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
  136. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(roomCreated:) name:NCRoomCreatedNotification object:nil];
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeAccountDidChange:) name:NCSettingsControllerDidChangeActiveAccountNotification object:nil];
  138. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pendingInvitationsDidUpdate:) name:NCDatabaseManagerPendingFederationInvitationsDidChange object:nil];
  139. }
  140. - (void)setupNavigationBar
  141. {
  142. [self setNavigationLogoButton];
  143. [self createNewConversationButton];
  144. [self createRefreshControl];
  145. self.navigationController.navigationBar.barTintColor = [NCAppBranding themeColor];
  146. self.navigationController.navigationBar.tintColor = [NCAppBranding themeTextColor];
  147. self.tabBarController.tabBar.tintColor = [NCAppBranding themeColor];
  148. UIColor *themeColor = [NCAppBranding themeColor];
  149. UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
  150. [appearance configureWithOpaqueBackground];
  151. appearance.backgroundColor = themeColor;
  152. self.navigationItem.standardAppearance = appearance;
  153. self.navigationItem.compactAppearance = appearance;
  154. self.navigationItem.scrollEdgeAppearance = appearance;
  155. self.navigationItem.searchController = _searchController;
  156. self.navigationItem.searchController.searchBar.searchTextField.backgroundColor = [NCUtils searchbarBGColorForColor:themeColor];
  157. if (@available(iOS 16.0, *)) {
  158. self.navigationItem.preferredSearchBarPlacement = UINavigationItemSearchBarPlacementStacked;
  159. }
  160. _searchController.searchBar.tintColor = [NCAppBranding themeTextColor];
  161. [_searchController.searchBar setScopeBarButtonTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NCAppBranding themeTextColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
  162. [_searchController.searchBar setScopeBarButtonTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NCAppBranding themeTextColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
  163. _searchController.searchBar.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
  164. UITextField *searchTextField = [_searchController.searchBar valueForKey:@"searchField"];
  165. UIButton *clearButton = [searchTextField valueForKey:@"_clearButton"];
  166. searchTextField.tintColor = [NCAppBranding themeTextColor];
  167. searchTextField.textColor = [NCAppBranding themeTextColor];
  168. dispatch_async(dispatch_get_main_queue(), ^{
  169. // Search bar placeholder
  170. searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Search", nil)
  171. attributes:@{NSForegroundColorAttributeName:[[NCAppBranding themeTextColor] colorWithAlphaComponent:0.5]}];
  172. // Search bar search icon
  173. UIImageView *searchImageView = (UIImageView *)searchTextField.leftView;
  174. searchImageView.image = [searchImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
  175. [searchImageView setTintColor:[[NCAppBranding themeTextColor] colorWithAlphaComponent:0.5]];
  176. // Search bar search clear button
  177. UIImage *clearButtonImage = [clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
  178. [clearButton setImage:clearButtonImage forState:UIControlStateNormal];
  179. [clearButton setImage:clearButtonImage forState:UIControlStateHighlighted];
  180. [clearButton setTintColor:[NCAppBranding themeTextColor]];
  181. });
  182. [self setNeedsStatusBarAppearanceUpdate];
  183. }
  184. - (void)createNewConversationButton
  185. {
  186. if ([[NCSettingsController sharedInstance] canCreateGroupAndPublicRooms] ||
  187. [[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityListableRooms]) {
  188. _newConversationButton = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"plus.circle.fill"] style:UIBarButtonItemStylePlain target:self action:@selector(presentNewRoomViewController)];
  189. _newConversationButton.accessibilityLabel = NSLocalizedString(@"Create or join a conversation", nil);
  190. [self.navigationItem setRightBarButtonItem:_newConversationButton];
  191. }
  192. }
  193. - (void)presentNewRoomViewController
  194. {
  195. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  196. NewRoomTableViewController *newRoowVC = [[NewRoomTableViewController alloc] initWithAccount:activeAccount];
  197. NCNavigationController *navigationController = [[NCNavigationController alloc] initWithRootViewController:newRoowVC];
  198. [self presentViewController:navigationController animated:YES completion:nil];
  199. }
  200. - (void)dealloc
  201. {
  202. [_rlmNotificationToken invalidate];
  203. [[NSNotificationCenter defaultCenter] removeObserver:self];
  204. }
  205. - (void)viewDidAppear:(BOOL)animated
  206. {
  207. [super viewDidAppear:animated];
  208. [self adaptInterfaceForAppState:[NCConnectionController sharedInstance].appState];
  209. [self adaptInterfaceForConnectionState:[NCConnectionController sharedInstance].connectionState];
  210. if ([[NCSettingsController sharedInstance] isContactSyncEnabled] && [[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityPhonebookSearch]) {
  211. [[NCContactsManager sharedInstance] searchInServerForAddressBookContacts:NO];
  212. }
  213. }
  214. - (void)viewWillAppear:(BOOL)animated
  215. {
  216. [super viewWillAppear:animated];
  217. [self refreshRoomList];
  218. self.clearsSelectionOnViewWillAppear = self.splitViewController.isCollapsed;
  219. if (self.splitViewController.isCollapsed) {
  220. [self setSelectedRoomToken:nil];
  221. }
  222. }
  223. - (void)viewWillDisappear:(BOOL)animated
  224. {
  225. [super viewWillDisappear:animated];
  226. [self stopRefreshRoomsTimer];
  227. }
  228. - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
  229. {
  230. [self setProfileButton];
  231. }
  232. - (void)didReceiveMemoryWarning
  233. {
  234. [super didReceiveMemoryWarning];
  235. // Dispose of any resources that can be recreated.
  236. }
  237. #pragma mark - Notifications
  238. - (void)appStateHasChanged:(NSNotification *)notification
  239. {
  240. AppState appState = [[notification.userInfo objectForKey:@"appState"] intValue];
  241. [self adaptInterfaceForAppState:appState];
  242. }
  243. - (void)connectionStateHasChanged:(NSNotification *)notification
  244. {
  245. ConnectionState connectionState = [[notification.userInfo objectForKey:@"connectionState"] intValue];
  246. [self adaptInterfaceForConnectionState:connectionState];
  247. }
  248. - (void)roomsDidUpdate:(NSNotification *)notification
  249. {
  250. NSError *error = [notification.userInfo objectForKey:@"error"];
  251. if (error) {
  252. NSLog(@"Error while trying to get rooms: %@", error);
  253. if ([error code] == NSURLErrorServerCertificateUntrusted) {
  254. NSLog(@"Untrusted certificate");
  255. dispatch_async(dispatch_get_main_queue(), ^{
  256. [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:self delegate:self];
  257. });
  258. }
  259. }
  260. [_refreshControl endRefreshing];
  261. }
  262. - (void)pendingInvitationsDidUpdate:(NSNotification *)notification
  263. {
  264. // Update the rooms: In case we accepted an invitation, we want to show the new room directly
  265. [self refreshRooms];
  266. }
  267. - (void)notificationWillBePresented:(NSNotification *)notification
  268. {
  269. [[NCRoomsManager sharedInstance] updateRoomsAndChatsUpdatingUserStatus:NO onlyLastModified:NO withCompletionBlock:nil];
  270. [self setUnreadMessageForInactiveAccountsIndicator];
  271. }
  272. - (void)serverCapabilitiesUpdated:(NSNotification *)notification
  273. {
  274. [self setupNavigationBar];
  275. }
  276. - (void)userProfileImageUpdated:(NSNotification *)notification
  277. {
  278. [self setProfileButton];
  279. }
  280. - (void)appWillEnterForeground:(NSNotification *)notification
  281. {
  282. if ([NCConnectionController sharedInstance].appState == kAppStateReady) {
  283. [[NCRoomsManager sharedInstance] updateRoomsAndChatsUpdatingUserStatus:YES onlyLastModified:NO withCompletionBlock:nil];
  284. [self startRefreshRoomsTimer];
  285. dispatch_async(dispatch_get_main_queue(), ^{
  286. // Dispatch to main, otherwise the traitCollection is not updated yet and profile buttons shows wrong style
  287. [self setProfileButton];
  288. [self setUnreadMessageForInactiveAccountsIndicator];
  289. });
  290. }
  291. }
  292. - (void)appWillResignActive:(NSNotification *)notification
  293. {
  294. [self stopRefreshRoomsTimer];
  295. }
  296. - (void)roomCreated:(NSNotification *)notification
  297. {
  298. dispatch_async(dispatch_get_main_queue(), ^{
  299. [self refreshRooms];
  300. NSString *roomToken = [notification.userInfo objectForKey:@"token"];
  301. [self setSelectedRoomToken:roomToken];
  302. });
  303. }
  304. - (void)activeAccountDidChange:(NSNotification *)notification
  305. {
  306. dispatch_async(dispatch_get_main_queue(), ^{
  307. [self refreshRoomList];
  308. // Setup the navigation bar here, otherwise it would only be updated
  309. // when the capabilities were updated, which fails when the server is not reachable.
  310. [self setupNavigationBar];
  311. });
  312. }
  313. #pragma mark - Refresh Timer
  314. - (void)startRefreshRoomsTimer
  315. {
  316. [self stopRefreshRoomsTimer];
  317. _refreshRoomsTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(refreshRooms) userInfo:nil repeats:YES];
  318. }
  319. - (void)stopRefreshRoomsTimer
  320. {
  321. [_refreshRoomsTimer invalidate];
  322. _refreshRoomsTimer = nil;
  323. }
  324. - (void)refreshRooms
  325. {
  326. [[NCRoomsManager sharedInstance] updateRoomsAndChatsUpdatingUserStatus:YES onlyLastModified:NO withCompletionBlock:nil];
  327. [[NCRoomsManager sharedInstance] checkUpdateNeededForPendingFederationInvitations];
  328. if ([NCConnectionController sharedInstance].connectionState == kConnectionStateConnected) {
  329. [[NCRoomsManager sharedInstance] resendOfflineMessagesWithCompletionBlock:nil];
  330. }
  331. [self getUserStatusWithCompletionBlock:nil];
  332. dispatch_async(dispatch_get_main_queue(), ^{
  333. // Dispatch to main, otherwise the traitCollection is not updated yet and profile buttons shows wrong style
  334. [self setUnreadMessageForInactiveAccountsIndicator];
  335. });
  336. }
  337. #pragma mark - Refresh Control
  338. - (void)createRefreshControl
  339. {
  340. _refreshControl = [UIRefreshControl new];
  341. _refreshControl.tintColor = [NCAppBranding themeTextColor];
  342. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  343. self.tableView.refreshControl = _refreshControl;
  344. }
  345. - (void)deleteRefreshControl
  346. {
  347. [_refreshControl endRefreshing];
  348. self.refreshControl = nil;
  349. }
  350. - (void)refreshControlTarget
  351. {
  352. [[NCRoomsManager sharedInstance] updateRoomsAndChatsUpdatingUserStatus:YES onlyLastModified:NO withCompletionBlock:nil];
  353. // When we manually forced a room update, we update the invitation list as well
  354. [[NCRoomsManager sharedInstance] updatePendingFederationInvitations];
  355. [self getUserStatusWithCompletionBlock:nil];
  356. // Actuate `Peek` feedback (weak boom)
  357. AudioServicesPlaySystemSound(1519);
  358. }
  359. #pragma mark - User Status SwiftUI View Delegate
  360. - (void)userStatusViewDidDisappear
  361. {
  362. [self getUserStatusWithCompletionBlock:nil];
  363. }
  364. #pragma mark - Title menu
  365. - (void)setNavigationLogoButton
  366. {
  367. UIImage *logoImage = [UIImage imageNamed:[NCAppBranding navigationLogoImageName]];
  368. self.navigationItem.titleView = [[UIImageView alloc] initWithImage:logoImage];
  369. self.navigationItem.titleView.accessibilityLabel = talkAppName;
  370. self.navigationItem.titleView.accessibilityHint = NSLocalizedString(@"Double tap to change accounts or add a new one", nil);
  371. }
  372. - (UIMenu *)getActiveAccountMenuOptions
  373. {
  374. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  375. ServerCapabilities *serverCapabilities = [[NCDatabaseManager sharedInstance] serverCapabilitiesForAccountId:activeAccount.accountId];
  376. UIDeferredMenuElement *userStatusDeferred = [UIDeferredMenuElement elementWithUncachedProvider:^(void (^ _Nonnull completion)(NSArray<UIMenuElement *> * _Nonnull)) {
  377. if (!activeAccount || !serverCapabilities.userStatus) {
  378. completion(@[]);
  379. return;
  380. }
  381. [self getUserStatusWithCompletionBlock:^(NSDictionary *userStatusDict, NSError *error) {
  382. if (error) {
  383. completion(@[]);
  384. return;
  385. }
  386. NCUserStatus *userStatus = [NCUserStatus userStatusWithDictionary:userStatusDict];
  387. UIImage *userStatusImage = [userStatus getSFUserStatusIcon];
  388. UIViewController *vc = [UserStatusSwiftUIViewFactory createWithUserStatus:userStatus delegate:self];
  389. UIAction *onlineOption = [UIAction actionWithTitle:[userStatus readableUserStatusOrMessage] image:userStatusImage identifier:nil handler:^(UIAction *action) {
  390. [self presentViewController:vc animated:YES completion:nil];
  391. }];
  392. completion(@[onlineOption]);
  393. }];
  394. }];
  395. return [UIMenu menuWithTitle:@""
  396. image:nil
  397. identifier:nil
  398. options:UIMenuOptionsDisplayInline
  399. children:@[userStatusDeferred]];
  400. }
  401. - (UIDeferredMenuElement *)getInactiveAccountMenuOptions
  402. {
  403. // We use a deferred action here to always have an up-to-date list of inactive accounts and their notifications
  404. UIDeferredMenuElement *inactiveAccountMenuDeferred = [UIDeferredMenuElement elementWithUncachedProvider:^(void (^ _Nonnull completion)(NSArray<UIMenuElement *> * _Nonnull)) {
  405. NSMutableArray *inactiveAccounts = [[NSMutableArray alloc] init];
  406. for (TalkAccount *account in [[NCDatabaseManager sharedInstance] inactiveAccounts]) {
  407. NSString *accountName = account.userDisplayName;
  408. UIImage *accountImage = [[NCAPIController sharedInstance] userProfileImageForAccount:account withStyle:self.traitCollection.userInterfaceStyle];
  409. if (accountImage) {
  410. accountImage = [NCUtils roundedImageFromImage:accountImage];
  411. // Draw a red circle to the image in case we have unread notifications for that account
  412. if (account.unreadNotification) {
  413. UIGraphicsBeginImageContextWithOptions(CGSizeMake(82, 82), NO, 3);
  414. CGContextRef context = UIGraphicsGetCurrentContext();
  415. [accountImage drawInRect:CGRectMake(0, 4, 78, 78)];
  416. CGContextSaveGState(context);
  417. CGContextSetFillColorWithColor(context, [UIColor systemRedColor].CGColor);
  418. CGContextFillEllipseInRect(context, CGRectMake(52, 0, 30, 30));
  419. accountImage = UIGraphicsGetImageFromCurrentImageContext();
  420. UIGraphicsEndImageContext();
  421. }
  422. }
  423. UIAction *switchAccountAction = [UIAction actionWithTitle:accountName image:accountImage identifier:nil handler:^(UIAction *action) {
  424. [[NCSettingsController sharedInstance] setActiveAccountWithAccountId:account.accountId];
  425. }];
  426. if (account.unreadBadgeNumber > 0) {
  427. switchAccountAction.subtitle = [NSString localizedStringWithFormat:NSLocalizedString(@"%ld notifications", nil), (long)account.unreadBadgeNumber];
  428. }
  429. [inactiveAccounts addObject:switchAccountAction];
  430. }
  431. UIMenu *inactiveAccountsMenu = [UIMenu menuWithTitle:@""
  432. image:nil
  433. identifier:nil
  434. options:UIMenuOptionsDisplayInline
  435. children:inactiveAccounts];
  436. completion(@[inactiveAccountsMenu]);
  437. }];
  438. return inactiveAccountMenuDeferred;
  439. }
  440. - (void)updateAccountPickerMenu
  441. {
  442. NSMutableArray *accountPickerMenu = [[NSMutableArray alloc] init];
  443. // When no elements are returned by the deferred menu, the entries / inline-menu will be hidden
  444. [accountPickerMenu addObject:[self getActiveAccountMenuOptions]];
  445. [accountPickerMenu addObject:[self getInactiveAccountMenuOptions]];
  446. NSMutableArray *optionItems = [[NSMutableArray alloc] init];
  447. if (multiAccountEnabled) {
  448. UIAction *addAccountOption = [UIAction actionWithTitle:NSLocalizedString(@"Add account", nil) image:[[UIImage systemImageNamed:@"person.crop.circle.badge.plus"] imageWithTintColor:[UIColor secondaryLabelColor] renderingMode:UIImageRenderingModeAlwaysOriginal] identifier:nil handler:^(UIAction *action) {
  449. [[NCUserInterfaceController sharedInstance] presentLoginViewController];
  450. }];
  451. [optionItems addObject:addAccountOption];
  452. }
  453. UIAction *openSettingsOption = [UIAction actionWithTitle:NSLocalizedString(@"Settings", nil) image:[[UIImage systemImageNamed:@"gear"] imageWithTintColor:[UIColor secondaryLabelColor] renderingMode:UIImageRenderingModeAlwaysOriginal] identifier:nil handler:^(UIAction *action) {
  454. [[NCDatabaseManager sharedInstance] removeUnreadNotificationForInactiveAccounts];
  455. [self setUnreadMessageForInactiveAccountsIndicator];
  456. [[NCUserInterfaceController sharedInstance] presentSettingsViewController];
  457. }];
  458. [optionItems addObject:openSettingsOption];
  459. UIMenu *optionMenu = [UIMenu menuWithTitle:@""
  460. image:nil
  461. identifier:nil
  462. options:UIMenuOptionsDisplayInline
  463. children:optionItems];
  464. [accountPickerMenu addObject:optionMenu];
  465. _profileButton.menu = [UIMenu menuWithTitle:@"" children:accountPickerMenu];
  466. _profileButton.showsMenuAsPrimaryAction = YES;
  467. }
  468. #pragma mark - Search controller
  469. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  470. {
  471. NSString *searchString = _searchController.searchBar.text;
  472. // Do not search for the same term twice (e.g. when the searchbar retrieves back the focus)
  473. if ([_searchString isEqualToString:searchString]) {return;}
  474. _searchString = searchString;
  475. // Cancel previous call to search listable rooms and messages
  476. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchListableRoomsAndMessages) object:nil];
  477. // Search for listable rooms and messages
  478. if (searchString.length > 0) {
  479. // Set searchingMessages flag if we are going to search for messages
  480. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityUnifiedSearch]) {
  481. [self setLoadMoreButtonHidden:YES];
  482. _resultTableViewController.searchingMessages = YES;
  483. }
  484. // Throttle listable rooms and messages search
  485. [self performSelector:@selector(searchListableRoomsAndMessages) withObject:nil afterDelay:1];
  486. } else {
  487. // Clear search results
  488. [self setLoadMoreButtonHidden:YES];
  489. _resultTableViewController.searchingMessages = NO;
  490. [_resultTableViewController clearSearchedResults];
  491. }
  492. // Filter rooms
  493. [self filterRooms];
  494. }
  495. - (void)willDismissSearchController:(UISearchController *)searchController
  496. {
  497. _searchController.searchBar.text = @"";
  498. _searchController.searchBar.selectedScopeButtonIndex = kRoomsFilterAll;
  499. [self filterRooms];
  500. }
  501. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  502. {
  503. [self filterRooms];
  504. }
  505. - (void)filterRooms
  506. {
  507. RoomsFilter filter = (RoomsFilter) _searchController.searchBar.selectedScopeButtonIndex;
  508. NSArray *filteredRooms = [self filterRoomsWithFilter:filter];
  509. NSString *searchString = _searchController.searchBar.text;
  510. if (searchString.length == 0) {
  511. _rooms = [[NSMutableArray alloc] initWithArray:filteredRooms];
  512. [self calculateLastRoomWithMention];
  513. [self.tableView reloadData];
  514. } else {
  515. _resultTableViewController.rooms = [self filterRooms:filteredRooms withString:searchString];
  516. [self calculateLastRoomWithMention];
  517. }
  518. }
  519. - (void)searchListableRoomsAndMessages
  520. {
  521. NSString *searchString = _searchController.searchBar.text;
  522. TalkAccount *account = [[NCDatabaseManager sharedInstance] activeAccount];
  523. // Search for contacts
  524. _resultTableViewController.users = @[];
  525. [[NCAPIController sharedInstance] getContactsForAccount:account forRoom:nil groupRoom:NO withSearchParam:searchString andCompletionBlock:^(NSArray *indexes, NSMutableDictionary *contacts, NSMutableArray *contactList, NSError *error) {
  526. if (!error) {
  527. NSArray *users = [self usersWithoutOneToOneConversations:contactList];
  528. if ([[NCSettingsController sharedInstance] isContactSyncEnabled] && [[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityPhonebookSearch]) {
  529. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  530. NSArray *addressBookContacts = [NCContact contactsForAccountId:activeAccount.accountId contains:nil];
  531. users = [NCUser combineUsersArray:addressBookContacts withUsersArray:users];
  532. }
  533. self->_resultTableViewController.users = users;
  534. }
  535. }];
  536. // Search for listable rooms
  537. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityListableRooms]) {
  538. _resultTableViewController.listableRooms = @[];
  539. [[NCAPIController sharedInstance] getListableRoomsForAccount:account withSerachTerm:searchString completionBlock:^(NSArray<NCRoom *> * _Nullable rooms, NSError * _Nullable error) {
  540. if (!error) {
  541. self->_resultTableViewController.listableRooms = rooms;
  542. }
  543. }];
  544. }
  545. // Search for messages
  546. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityUnifiedSearch]) {
  547. _unifiedSearchController = [[NCUnifiedSearchController alloc] initWithAccount:account searchTerm:searchString];
  548. _resultTableViewController.messages = @[];
  549. [self searchForMessagesWithCurrentSearchTerm];
  550. }
  551. }
  552. - (NSArray *)usersWithoutOneToOneConversations:(NSArray *)users
  553. {
  554. NSPredicate *oneToOnePredicate = [NSPredicate predicateWithFormat:@"type == %ld", kNCRoomTypeOneToOne];
  555. NSArray *oneToOneRooms = [_rooms filteredArrayUsingPredicate:oneToOnePredicate];
  556. NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"NOT (userId IN %@)", [oneToOneRooms valueForKey:@"name"]];
  557. return [users filteredArrayUsingPredicate:namePredicate];
  558. }
  559. - (void)searchForMessagesWithCurrentSearchTerm
  560. {
  561. [_unifiedSearchController searchMessagesWithCompletionHandler:^(NSArray<NKSearchEntry *> *entries) {
  562. dispatch_async(dispatch_get_main_queue(), ^{
  563. self->_resultTableViewController.searchingMessages = NO;
  564. self->_resultTableViewController.messages = entries;
  565. [self setLoadMoreButtonHidden:!self->_unifiedSearchController.showMore];
  566. });
  567. }];
  568. }
  569. - (NSArray *)filterRoomsWithFilter:(RoomsFilter)filter
  570. {
  571. switch (filter) {
  572. case kRoomsFilterUnread:
  573. return [_allRooms filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"unreadMessages > 0"]];
  574. case kRoomsFilterMentioned:
  575. return [_allRooms filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"hasUnreadMention == YES"]];
  576. default:
  577. return _allRooms;
  578. }
  579. }
  580. - (NSArray *)filterRooms:(NSArray *)rooms withString:(NSString *)searchString
  581. {
  582. return [rooms filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"displayName CONTAINS[c] %@", searchString]];
  583. }
  584. - (void)setLoadMoreButtonHidden:(BOOL)hidden
  585. {
  586. if (!hidden) {
  587. UIButton *loadMoreButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
  588. loadMoreButton.titleLabel.font = [UIFont systemFontOfSize:15];
  589. [loadMoreButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
  590. [loadMoreButton setTitle:NSLocalizedString(@"Load more results", @"") forState:UIControlStateNormal];
  591. [loadMoreButton addTarget:self action:@selector(loadMoreMessagesWithCurrentSearchTerm) forControlEvents:UIControlEventTouchUpInside];
  592. _resultTableViewController.tableView.tableFooterView = loadMoreButton;
  593. } else {
  594. _resultTableViewController.tableView.tableFooterView = nil;
  595. }
  596. }
  597. - (void)loadMoreMessagesWithCurrentSearchTerm
  598. {
  599. if (_unifiedSearchController && [_unifiedSearchController.searchTerm isEqualToString:_searchController.searchBar.text]) {
  600. [_resultTableViewController showSearchingFooterView];
  601. [self searchForMessagesWithCurrentSearchTerm];
  602. }
  603. }
  604. #pragma mark - Rooms filter
  605. - (NSArray *)availableFilters
  606. {
  607. NSMutableArray *filters = [[NSMutableArray alloc] init];
  608. [filters addObject:[NSNumber numberWithInt:kRoomsFilterAll]];
  609. [filters addObject:[NSNumber numberWithInt:kRoomsFilterUnread]];
  610. [filters addObject:[NSNumber numberWithInt:kRoomsFilterMentioned]];
  611. return [NSArray arrayWithArray:filters];
  612. }
  613. - (NSString *)filterName:(RoomsFilter)filter
  614. {
  615. switch (filter) {
  616. case kRoomsFilterAll:
  617. return NSLocalizedString(@"All", @"'All' meaning 'All conversations'");
  618. case kRoomsFilterUnread:
  619. return NSLocalizedString(@"Unread", @"'Unread' meaning 'Unread conversations'");
  620. case kRoomsFilterMentioned:
  621. return NSLocalizedString(@"Mentioned", @"'Mentioned' meaning 'Mentioned conversations'");
  622. default:
  623. return @"";
  624. }
  625. }
  626. - (NSArray *)getFilters
  627. {
  628. NSMutableArray *filters = [[NSMutableArray alloc] init];
  629. for (NSNumber *filter in [self availableFilters]) {
  630. [filters addObject:[self filterName:filter.intValue]];
  631. }
  632. return [NSArray arrayWithArray:filters];
  633. }
  634. #pragma mark - User Interface
  635. - (void)refreshRoomList
  636. {
  637. TalkAccount *account = [[NCDatabaseManager sharedInstance] activeAccount];
  638. NSArray *accountRooms = [[NCRoomsManager sharedInstance] roomsForAccountId:account.accountId withRealm:nil];
  639. _allRooms = [[NSMutableArray alloc] initWithArray:accountRooms];
  640. _rooms = [[NSMutableArray alloc] initWithArray:accountRooms];
  641. // Show/Hide placeholder view
  642. [_roomsBackgroundView.loadingView stopAnimating];
  643. [_roomsBackgroundView.loadingView setHidden:YES];
  644. [_roomsBackgroundView.placeholderView setHidden:(_rooms.count > 0)];
  645. // Filter rooms
  646. [self filterRooms];
  647. // Reload room list
  648. [self.tableView reloadData];
  649. // Update unread mentions indicator
  650. [self updateMentionsIndicator];
  651. [self highlightSelectedRoom];
  652. }
  653. - (void)adaptInterfaceForAppState:(AppState)appState
  654. {
  655. switch (appState) {
  656. case kAppStateNotServerProvided:
  657. case kAppStateMissingUserProfile:
  658. case kAppStateMissingServerCapabilities:
  659. case kAppStateMissingSignalingConfiguration:
  660. {
  661. // Clear active user status when changing users
  662. _activeUserStatus = nil;
  663. [self setProfileButton];
  664. }
  665. break;
  666. case kAppStateReady:
  667. {
  668. [self setProfileButton];
  669. BOOL isAppActive = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
  670. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:isAppActive onlyLastModified:NO];
  671. [self getUserStatusWithCompletionBlock:nil];
  672. [self startRefreshRoomsTimer];
  673. [self setupNavigationBar];
  674. }
  675. break;
  676. default:
  677. break;
  678. }
  679. }
  680. - (void)adaptInterfaceForConnectionState:(ConnectionState)connectionState
  681. {
  682. switch (connectionState) {
  683. case kConnectionStateConnected:
  684. {
  685. [self setOnlineAppearance];
  686. }
  687. break;
  688. case kConnectionStateDisconnected:
  689. {
  690. [self setOfflineAppearance];
  691. }
  692. break;
  693. default:
  694. break;
  695. }
  696. }
  697. - (void)setOfflineAppearance
  698. {
  699. _newConversationButton.enabled = NO;
  700. if (!customNavigationLogo) {
  701. self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  702. }
  703. }
  704. - (void)setOnlineAppearance
  705. {
  706. _newConversationButton.enabled = YES;
  707. [self setNavigationLogoButton];
  708. }
  709. #pragma mark - UIScrollViewDelegate Methods
  710. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  711. {
  712. if ([scrollView isEqual:self.tableView]) {
  713. [self updateMentionsIndicator];
  714. }
  715. }
  716. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
  717. {
  718. if ([scrollView isEqual:self.tableView]) {
  719. [self updateMentionsIndicator];
  720. }
  721. }
  722. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
  723. {
  724. if ([scrollView isEqual:self.tableView]) {
  725. [self updateMentionsIndicator];
  726. }
  727. }
  728. - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
  729. {
  730. if ([scrollView isEqual:self.tableView]) {
  731. [self updateMentionsIndicator];
  732. }
  733. }
  734. #pragma mark - Mentions
  735. - (void)updateMentionsIndicator
  736. {
  737. NSArray *visibleRows = [self.tableView indexPathsForVisibleRows];
  738. NSIndexPath *lastVisibleRowIndexPath = visibleRows.lastObject;
  739. _unreadMentionsBottomButton.hidden = YES;
  740. // Calculate index of first room with a mention outside visible cells
  741. _nextRoomWithMentionIndexPath = nil;
  742. if (!_lastRoomWithMentionIndexPath) {
  743. return;
  744. }
  745. for (int i = (int)lastVisibleRowIndexPath.row; i <= (int)_lastRoomWithMentionIndexPath.row && i < [_rooms count]; i++) {
  746. NCRoom *room = [_rooms objectAtIndex:i];
  747. if (room.hasUnreadMention) {
  748. _nextRoomWithMentionIndexPath = [NSIndexPath indexPathForRow:i inSection:1];
  749. break;
  750. }
  751. }
  752. // Update unread mentions indicator visibility
  753. _unreadMentionsBottomButton.hidden = [visibleRows containsObject:_lastRoomWithMentionIndexPath] || lastVisibleRowIndexPath.row > _lastRoomWithMentionIndexPath.row;
  754. // Make sure the style is adjusted to current accounts theme
  755. _unreadMentionsBottomButton.backgroundColor = [NCAppBranding themeColor];
  756. [_unreadMentionsBottomButton setTitleColor:[NCAppBranding themeTextColor] forState:UIControlStateNormal];
  757. }
  758. - (void)unreadMentionsBottomButtonPressed:(id)sender
  759. {
  760. if (_nextRoomWithMentionIndexPath) {
  761. [self.tableView scrollToRowAtIndexPath:_nextRoomWithMentionIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
  762. }
  763. }
  764. - (void)calculateLastRoomWithMention
  765. {
  766. _lastRoomWithMentionIndexPath = nil;
  767. for (int i = 0; i < _rooms.count; i++) {
  768. NCRoom *room = [_rooms objectAtIndex:i];
  769. if (room.hasUnreadMention) {
  770. _lastRoomWithMentionIndexPath = [NSIndexPath indexPathForRow:i inSection:1];
  771. }
  772. }
  773. }
  774. #pragma mark - User profile
  775. - (void)setProfileButton
  776. {
  777. _profileButton = [UIButton buttonWithType:UIButtonTypeCustom];
  778. _profileButton.frame = CGRectMake(0, 0, 38, 38);
  779. _profileButton.accessibilityLabel = NSLocalizedString(@"User profile and settings", nil);
  780. _settingsButton = [[UIBarButtonItem alloc] initWithCustomView:_profileButton];
  781. [self.navigationItem setLeftBarButtonItem:_settingsButton];
  782. [self updateProfileButtonImage];
  783. [self updateAccountPickerMenu];
  784. [self setUnreadMessageForInactiveAccountsIndicator];
  785. }
  786. - (void)updateProfileButtonImage
  787. {
  788. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  789. UIImage *profileImage = [[NCAPIController sharedInstance] userProfileImageForAccount:activeAccount withStyle:self.traitCollection.userInterfaceStyle];
  790. if (profileImage) {
  791. // Crop the profile image into a circle
  792. profileImage = [profileImage cropToCircleWithSize:CGSizeMake(30, 30)];
  793. // Increase the profile image size to leave space for the status
  794. profileImage = [profileImage withCircularBackgroundWithBackgroundColor:[UIColor clearColor] diameter:38.0 padding:4.0];
  795. // Online status icon
  796. UIImage *statusImage = nil;
  797. if ([_activeUserStatus hasVisibleStatusIcon]) {
  798. statusImage = [[_activeUserStatus getSFUserStatusIcon] withCircularBackgroundWithBackgroundColor:self.navigationController.navigationBar.barTintColor
  799. diameter:14.0 padding:1.0];
  800. }
  801. // Status message icon
  802. if (_activeUserStatus.icon.length > 0) {
  803. UILabel *iconLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 14, 14)];
  804. iconLabel.text = _activeUserStatus.icon;
  805. iconLabel.adjustsFontSizeToFitWidth = YES;
  806. statusImage = [UIImage imageFrom:iconLabel];
  807. }
  808. // Set status image
  809. if (statusImage) {
  810. profileImage = [profileImage overlayWith:statusImage at:CGRectMake(24, 24, 14, 14)];
  811. }
  812. [_profileButton setImage:profileImage forState:UIControlStateNormal];
  813. // Used to distinguish between a "completely loaded" button (with a profile image) and the default gear one
  814. _profileButton.accessibilityIdentifier = @"LoadedProfileButton";
  815. } else {
  816. [_profileButton setImage:[UIImage systemImageNamed:@"gear"] forState:UIControlStateNormal];
  817. _profileButton.contentMode = UIViewContentModeCenter;
  818. }
  819. }
  820. - (void)getUserStatusWithCompletionBlock:(GetUserStatusCompletionBlock)block
  821. {
  822. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  823. [[NCAPIController sharedInstance] getUserStatusForAccount:activeAccount withCompletionBlock:^(NSDictionary *userStatusDict, NSError *error) {
  824. if (!error) {
  825. self->_activeUserStatus = [NCUserStatus userStatusWithDictionary:userStatusDict];
  826. [self updateProfileButtonImage];
  827. if (block) {
  828. block(userStatusDict, nil);
  829. }
  830. } else if (block) {
  831. block(nil, error);
  832. }
  833. }];
  834. }
  835. - (void)setUnreadMessageForInactiveAccountsIndicator
  836. {
  837. NSInteger numberOfInactiveAccountsWithUnreadNotifications = [[NCDatabaseManager sharedInstance] numberOfInactiveAccountsWithUnreadNotifications];
  838. if (numberOfInactiveAccountsWithUnreadNotifications > 0) {
  839. _settingsButton.badgeValue = [NSString stringWithFormat:@"%ld", numberOfInactiveAccountsWithUnreadNotifications];
  840. }
  841. }
  842. #pragma mark - CCCertificateDelegate
  843. - (void)trustedCerticateAccepted
  844. {
  845. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:NO onlyLastModified:NO];
  846. }
  847. #pragma mark - Room actions
  848. - (UIAction *)actionForNotificationLevel:(NCRoomNotificationLevel)level forRoom:(NCRoom *)room
  849. {
  850. UIAction *notificationAction = [UIAction actionWithTitle:[NCRoom stringForNotificationLevel:level] image:nil identifier:nil handler:^(UIAction *action) {
  851. if (level == room.notificationLevel) {
  852. return;
  853. }
  854. [[NCAPIController sharedInstance] setNotificationLevel:level forRoom:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  855. if (error) {
  856. NSLog(@"Error renaming the room: %@", error.description);
  857. }
  858. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  859. }];
  860. }];
  861. if (room.notificationLevel == level) {
  862. notificationAction.state = UIMenuElementStateOn;
  863. }
  864. return notificationAction;
  865. }
  866. - (void)shareLinkFromRoom:(NCRoom *)room
  867. {
  868. NSIndexPath *indexPath = [self indexPathForRoom:room];
  869. if (indexPath) {
  870. [[NCUserInterfaceController sharedInstance] presentShareLinkDialogForRoom:room inViewContoller:self forIndexPath:indexPath];
  871. }
  872. }
  873. - (void)markRoomAsRead:(NCRoom *)room
  874. {
  875. [[NCAPIController sharedInstance] setChatReadMarker:room.lastMessage.messageId inRoom:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  876. if (error) {
  877. NSLog(@"Error marking room as read: %@", error.description);
  878. }
  879. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  880. }];
  881. }
  882. - (void)markRoomAsUnread:(NCRoom *)room
  883. {
  884. [[NCAPIController sharedInstance] markChatAsUnreadInRoom:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  885. if (error) {
  886. NSLog(@"Error marking chat as unread: %@", error.description);
  887. }
  888. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  889. }];
  890. }
  891. - (void)addRoomToFavorites:(NCRoom *)room
  892. {
  893. [[NCAPIController sharedInstance] addRoomToFavorites:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  894. if (error) {
  895. NSLog(@"Error adding room to favorites: %@", error.description);
  896. }
  897. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  898. }];
  899. }
  900. - (void)removeRoomFromFavorites:(NCRoom *)room
  901. {
  902. [[NCAPIController sharedInstance] removeRoomFromFavorites:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  903. if (error) {
  904. NSLog(@"Error removing room from favorites: %@", error.description);
  905. }
  906. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  907. }];
  908. }
  909. - (void)presentRoomInfoForRoom:(NCRoom *)room
  910. {
  911. RoomInfoTableViewController *roomInfoVC = [[RoomInfoTableViewController alloc] initForRoom:room];
  912. NCNavigationController *navigationController = [[NCNavigationController alloc] initWithRootViewController:roomInfoVC];
  913. [self presentViewController:navigationController animated:YES completion:nil];
  914. }
  915. - (void)leaveRoom:(NCRoom *)room
  916. {
  917. UIAlertController *confirmDialog =
  918. [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Leave conversation", nil)
  919. message:NSLocalizedString(@"Once a conversation is left, to rejoin a closed conversation, an invite is needed. An open conversation can be rejoined at any time.", nil)
  920. preferredStyle:UIAlertControllerStyleAlert];
  921. UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Leave", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  922. [[NCUserInterfaceController sharedInstance] presentConversationsList];
  923. NSIndexPath *indexPath = [self indexPathForRoom:room];
  924. if (indexPath) {
  925. [self->_rooms removeObjectAtIndex:indexPath.row];
  926. [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  927. }
  928. [[NCAPIController sharedInstance] removeSelfFromRoom:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSInteger errorCode, NSError *error) {
  929. if (errorCode == 400) {
  930. [self showLeaveRoomLastModeratorErrorForRoom:room];
  931. } else if (error) {
  932. NSLog(@"Error leaving room: %@", error.description);
  933. }
  934. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  935. }];
  936. }];
  937. [confirmDialog addAction:confirmAction];
  938. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:nil];
  939. [confirmDialog addAction:cancelAction];
  940. [self presentViewController:confirmDialog animated:YES completion:nil];
  941. }
  942. - (void)deleteRoom:(NCRoom *)room
  943. {
  944. UIAlertController *confirmDialog =
  945. [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Delete conversation", nil)
  946. message:room.deletionMessage
  947. preferredStyle:UIAlertControllerStyleAlert];
  948. UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  949. [[NCUserInterfaceController sharedInstance] presentConversationsList];
  950. NSIndexPath *indexPath = [self indexPathForRoom:room];
  951. if (indexPath) {
  952. [self->_rooms removeObjectAtIndex:indexPath.row];
  953. [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  954. }
  955. [[NCAPIController sharedInstance] deleteRoom:room.token forAccount:[[NCDatabaseManager sharedInstance] activeAccount] withCompletionBlock:^(NSError *error) {
  956. if (error) {
  957. NSLog(@"Error deleting room: %@", error.description);
  958. }
  959. [[NCRoomsManager sharedInstance] updateRoomsUpdatingUserStatus:YES onlyLastModified:NO];
  960. }];
  961. }];
  962. [confirmDialog addAction:confirmAction];
  963. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:nil];
  964. [confirmDialog addAction:cancelAction];
  965. [self presentViewController:confirmDialog animated:YES completion:nil];
  966. }
  967. - (void)presentChatForRoomAtIndexPath:(NSIndexPath *)indexPath
  968. {
  969. NCRoom *room = [self roomForIndexPath:indexPath];
  970. [[NCRoomsManager sharedInstance] startChatInRoom:room];
  971. }
  972. #pragma mark - Utils
  973. - (NCRoom *)roomForIndexPath:(NSIndexPath *)indexPath
  974. {
  975. if (_searchController.active && !_resultTableViewController.view.isHidden) {
  976. return [_resultTableViewController roomForIndexPath:indexPath];
  977. } else if (indexPath.row < _rooms.count) {
  978. return [_rooms objectAtIndex:indexPath.row];
  979. }
  980. return nil;
  981. }
  982. - (NSIndexPath *)indexPathForRoom:(NCRoom *)room
  983. {
  984. NSUInteger idx = [_rooms indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
  985. NCRoom *currentRoom = (NCRoom *)obj;
  986. return [currentRoom.internalId isEqualToString:room.internalId];
  987. }];
  988. if (idx != NSNotFound) {
  989. return [NSIndexPath indexPathForRow:idx inSection:1];
  990. }
  991. return nil;
  992. }
  993. - (void)showLeaveRoomLastModeratorErrorForRoom:(NCRoom *)room
  994. {
  995. UIAlertController *leaveRoomFailedDialog =
  996. [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Could not leave conversation", nil)
  997. message:[NSString stringWithFormat:NSLocalizedString(@"You need to promote a new moderator before you can leave %@.", nil), room.displayName]
  998. preferredStyle:UIAlertControllerStyleAlert];
  999. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:nil];
  1000. [leaveRoomFailedDialog addAction:okAction];
  1001. [self presentViewController:leaveRoomFailedDialog animated:YES completion:nil];
  1002. }
  1003. #pragma mark - Search results
  1004. - (void)presentSelectedMessageInChat:(NKSearchEntry *)message
  1005. {
  1006. NSString *roomToken = [message.attributes objectForKey:@"conversation"];
  1007. NSString *messageIdString = [message.attributes objectForKey:@"messageId"];
  1008. if (roomToken && messageIdString) {
  1009. TalkAccount *activeAccount = [[NCDatabaseManager sharedInstance] activeAccount];
  1010. NSInteger messageId = [messageIdString intValue];
  1011. NCRoom *room = [[NCDatabaseManager sharedInstance] roomWithToken:roomToken forAccountId:activeAccount.accountId];
  1012. if (room) {
  1013. [self presentContextChatInRoom:room forMessageId:messageId];
  1014. } else {
  1015. [[NCAPIController sharedInstance] getRoomForAccount:activeAccount withToken:roomToken completionBlock:^(NSDictionary *roomDict, NSError *error) {
  1016. if (!error) {
  1017. NCRoom *room = [NCRoom roomWithDictionary:roomDict andAccountId:activeAccount.accountId];
  1018. [self presentContextChatInRoom:room forMessageId:messageId];
  1019. } else {
  1020. NSString *errorMessage = NSLocalizedString(@"Unable to get conversation of the message", nil);
  1021. [[JDStatusBarNotificationPresenter sharedPresenter] presentWithText:errorMessage dismissAfterDelay:5.0 includedStyle:JDStatusBarNotificationIncludedStyleDark];
  1022. }
  1023. }];
  1024. }
  1025. }
  1026. }
  1027. - (void)presentContextChatInRoom:(NCRoom *)room forMessageId:(NSInteger)messageId
  1028. {
  1029. ContextChatViewController *contextChatViewController = [[ContextChatViewController alloc] initFor:room withMessage:@[] withHighlightId:0];
  1030. contextChatViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeContextChat)];
  1031. NCChatController *chatController = [[NCChatController alloc] initForRoom:room];
  1032. [chatController getMessageContextForMessageId:messageId withLimit:50 withCompletionBlock:^(NSArray<NCChatMessage *> * _Nullable messages) {
  1033. if (messages.count > 0) {
  1034. [contextChatViewController appendMessagesWithMessages:messages];
  1035. [contextChatViewController reloadDataAndHighlightMessageWithMessageId:messageId];
  1036. } else {
  1037. NSString *errorMessage = NSLocalizedString(@"Unable to get context of the message", nil);
  1038. [[JDStatusBarNotificationPresenter sharedPresenter] presentWithText:errorMessage dismissAfterDelay:5.0 includedStyle:JDStatusBarNotificationIncludedStyleDark];
  1039. }
  1040. }];
  1041. _contextChatNavigationController = [[NCNavigationController alloc] initWithRootViewController:contextChatViewController];
  1042. [self presentViewController:_contextChatNavigationController animated:YES completion:nil];
  1043. }
  1044. - (void)closeContextChat
  1045. {
  1046. [_contextChatNavigationController dismissViewControllerAnimated:YES completion:nil];
  1047. }
  1048. - (void)createRoomForSelectedUser:(NCUser *)user
  1049. {
  1050. [[NCAPIController sharedInstance]
  1051. createRoomForAccount:[[NCDatabaseManager sharedInstance] activeAccount] withInvite:user.userId
  1052. ofType:kNCRoomTypeOneToOne
  1053. andName:nil
  1054. completionBlock:^(NCRoom *room, NSError *error) {
  1055. if (!error) {
  1056. [self.navigationController dismissViewControllerAnimated:YES completion:^{
  1057. [[NSNotificationCenter defaultCenter] postNotificationName:NCSelectedUserForChatNotification
  1058. object:self
  1059. userInfo:@{@"token":room.token}];
  1060. }];
  1061. }
  1062. [self->_searchController setActive:NO];
  1063. }];
  1064. }
  1065. #pragma mark - Table view data source
  1066. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  1067. {
  1068. return 2;
  1069. }
  1070. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  1071. {
  1072. if (section == kRoomsSectionPendingFederationInvitation) {
  1073. TalkAccount *account = [[NCDatabaseManager sharedInstance] activeAccount];
  1074. if (account.pendingFederationInvitations > 0) {
  1075. return 1;
  1076. }
  1077. return 0;
  1078. }
  1079. return _rooms.count;
  1080. }
  1081. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  1082. {
  1083. if (tableView == self.tableView && indexPath.section == kRoomsSectionPendingFederationInvitation) {
  1084. return RoomInvitationViewCell.CellHeight;
  1085. }
  1086. return RoomTableViewCell.cellHeight;
  1087. }
  1088. - (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath
  1089. {
  1090. if (tableView == self.tableView && indexPath.section == kRoomsSectionPendingFederationInvitation) {
  1091. // No swipe action for pending invitations
  1092. return nil;
  1093. }
  1094. NCRoom *room = [self roomForIndexPath:indexPath];
  1095. // Do not show swipe actions for open conversations or messages
  1096. if ((tableView == _resultTableViewController.tableView && room.listable) || !room) {
  1097. return nil;
  1098. }
  1099. UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil
  1100. handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
  1101. [self deleteRoom:room];
  1102. completionHandler(false);
  1103. }];
  1104. deleteAction.image = [UIImage systemImageNamed:@"trash"];
  1105. if (room.isLeavable && room.type != kNCRoomTypeNoteToSelf) {
  1106. deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil
  1107. handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
  1108. [self leaveRoom:room];
  1109. completionHandler(false);
  1110. }];
  1111. deleteAction.image = [UIImage systemImageNamed:@"arrow.right.square"];
  1112. }
  1113. return [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
  1114. }
  1115. - (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  1116. {
  1117. if (tableView == self.tableView && indexPath.section == kRoomsSectionPendingFederationInvitation) {
  1118. // No swipe action for pending invitations
  1119. return nil;
  1120. }
  1121. NCRoom *room = [self roomForIndexPath:indexPath];
  1122. // Do not show swipe actions for open conversations or messages
  1123. if ((tableView == _resultTableViewController.tableView && room.listable) || !room) {
  1124. return nil;
  1125. }
  1126. // Add/Remove room to/from favorites
  1127. UIContextualAction *favoriteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:nil
  1128. handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
  1129. if (room.isFavorite) {
  1130. [self removeRoomFromFavorites:room];
  1131. } else {
  1132. [self addRoomToFavorites:room];
  1133. }
  1134. completionHandler(true);
  1135. }];
  1136. NSString *favImageName = (room.isFavorite) ? @"star" : @"star.fill";
  1137. favoriteAction.image = [UIImage systemImageNamed:favImageName];
  1138. favoriteAction.backgroundColor = [UIColor colorWithRed:0.97 green:0.80 blue:0.27 alpha:1.0]; // Favorite yellow
  1139. // Mark room as read/unread
  1140. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityChatReadMarker] &&
  1141. (!room.isFederated || [[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityChatReadLast])) {
  1142. UIContextualAction *markReadAction = [UIContextualAction
  1143. contextualActionWithStyle:UIContextualActionStyleNormal title:nil
  1144. handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
  1145. if (room.unreadMessages > 0) {
  1146. [self markRoomAsRead:room];
  1147. } else {
  1148. [self markRoomAsUnread:room];
  1149. }
  1150. completionHandler(true);
  1151. }];
  1152. NSString *markImageName = (room.unreadMessages > 0) ? @"eye" : @"eye.slash";
  1153. markReadAction.image = [UIImage systemImageNamed:markImageName];
  1154. markReadAction.backgroundColor = [UIColor systemBlueColor];
  1155. return [UISwipeActionsConfiguration configurationWithActions:@[markReadAction, favoriteAction]];
  1156. }
  1157. return [UISwipeActionsConfiguration configurationWithActions:@[favoriteAction]];
  1158. }
  1159. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  1160. {
  1161. if (indexPath.section == kRoomsSectionPendingFederationInvitation) {
  1162. RoomInvitationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RoomInvitationViewCell.ReuseIdentifier];
  1163. if (!cell) {
  1164. cell = [[RoomInvitationViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RoomInvitationViewCell.ReuseIdentifier];
  1165. }
  1166. // Pending federation invitations
  1167. TalkAccount *account = [[NCDatabaseManager sharedInstance] activeAccount];
  1168. NSString *pendingInvitationsString = [NSString localizedStringWithFormat:NSLocalizedString(@"You have %ld pending invitations", nil), (long)account.pendingFederationInvitations];
  1169. UIFont *resultFont = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
  1170. NSTextAttachment *pendingInvitationsAttachment = [[NSTextAttachment alloc] init];
  1171. pendingInvitationsAttachment.image = [UIImage imageNamed:@"pending-federation-invitations"];
  1172. pendingInvitationsAttachment.bounds = CGRectMake(0, roundf(resultFont.capHeight - 20) / 2, 20, 20);
  1173. NSMutableAttributedString *resultString = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:pendingInvitationsAttachment]];
  1174. [resultString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
  1175. [resultString appendAttributedString:[[NSAttributedString alloc] initWithString:pendingInvitationsString]];
  1176. NSRange range = NSMakeRange(0, [resultString length]);
  1177. [resultString addAttribute:NSFontAttributeName value:[UIFont preferredFontForTextStyle:UIFontTextStyleHeadline] range:range];
  1178. cell.detailsLabel.attributedText = resultString;
  1179. cell.separatorInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, CGFLOAT_MAX);
  1180. return cell;
  1181. }
  1182. RoomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RoomTableViewCell.identifier];
  1183. if (!cell) {
  1184. cell = [[RoomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RoomTableViewCell.identifier];
  1185. }
  1186. NCRoom *room = [_rooms objectAtIndex:indexPath.row];
  1187. // Set room name
  1188. cell.titleLabel.text = room.displayName;
  1189. // Set last activity
  1190. if (room.lastMessageId || room.lastMessageProxiedJSONString) {
  1191. cell.titleOnly = NO;
  1192. cell.subtitleLabel.attributedText = room.lastMessageString;
  1193. } else {
  1194. cell.titleOnly = YES;
  1195. }
  1196. NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:room.lastActivity];
  1197. cell.dateLabel.text = [NCUtils readableTimeOrDateFromDate:date];
  1198. // Set unread messages
  1199. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityDirectMentionFlag]) {
  1200. BOOL mentioned = room.unreadMentionDirect || room.type == kNCRoomTypeOneToOne || room.type == kNCRoomTypeFormerOneToOne;
  1201. BOOL groupMentioned = room.unreadMention && !room.unreadMentionDirect;
  1202. [cell setUnreadWithMessages:room.unreadMessages mentioned:mentioned groupMentioned:groupMentioned];
  1203. } else {
  1204. BOOL mentioned = room.unreadMention || room.type == kNCRoomTypeOneToOne || room.type == kNCRoomTypeFormerOneToOne;
  1205. [cell setUnreadWithMessages:room.unreadMessages mentioned:mentioned groupMentioned:NO];
  1206. }
  1207. [cell.roomImage setAvatarFor:room];
  1208. // Set favorite or call image
  1209. if (room.hasCall) {
  1210. [cell.favoriteImage setTintColor:[UIColor systemRedColor]];
  1211. [cell.favoriteImage setImage:[UIImage systemImageNamed:@"video.fill"]];
  1212. } else if (room.isFavorite) {
  1213. [cell.favoriteImage setTintColor:[UIColor systemYellowColor]];
  1214. [cell.favoriteImage setImage:[UIImage systemImageNamed:@"star.fill"]];
  1215. }
  1216. cell.roomToken = room.token;
  1217. return cell;
  1218. }
  1219. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)rcell forRowAtIndexPath:(NSIndexPath *)indexPath
  1220. {
  1221. if (indexPath.section == kRoomsSectionPendingFederationInvitation || tableView != self.tableView) {
  1222. return;
  1223. }
  1224. RoomTableViewCell *cell = (RoomTableViewCell *)rcell;
  1225. NCRoom *room = [_rooms objectAtIndex:indexPath.row];
  1226. //Show User Status
  1227. if (room.type == kNCRoomTypeOneToOne && [room.status length] != 0) {
  1228. if (![room.status isEqualToString:@"dnd"] && [room.statusIcon length] != 0) {
  1229. [cell setUserStatusIcon:room.statusIcon];
  1230. } else {
  1231. [cell setUserStatus:room.status];
  1232. }
  1233. } else if (room.isPublic) {
  1234. UIImageSymbolConfiguration *conf = [UIImageSymbolConfiguration configurationWithPointSize:12];
  1235. UIImage *publicRoomImage = [UIImage systemImageNamed:@"link"];
  1236. publicRoomImage = [publicRoomImage imageWithTintColor:[UIColor labelColor] renderingMode:UIImageRenderingModeAlwaysOriginal];
  1237. publicRoomImage = [publicRoomImage imageByApplyingSymbolConfiguration:conf];
  1238. [cell setUserStatusIconWithImage:publicRoomImage];
  1239. } else if (room.isFederated) {
  1240. UIImageSymbolConfiguration *conf = [UIImageSymbolConfiguration configurationWithPointSize:14];
  1241. UIImage *publicRoomImage = [UIImage systemImageNamed:@"globe"];
  1242. publicRoomImage = [publicRoomImage imageWithTintColor:[UIColor labelColor] renderingMode:UIImageRenderingModeAlwaysOriginal];
  1243. publicRoomImage = [publicRoomImage imageByApplyingSymbolConfiguration:conf];
  1244. [cell setUserStatusIconWithImage:publicRoomImage];
  1245. }
  1246. }
  1247. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  1248. {
  1249. [self setSelectedRoomToken:nil];
  1250. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  1251. BOOL isAppInForeground = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
  1252. if (!isAppInForeground) {
  1253. // In case we are not in the active state, we don't want to invoke any navigation event as this might
  1254. // lead to crashes, when the wrong NavBar is referenced
  1255. return;
  1256. }
  1257. if (tableView == self.tableView && indexPath.section == kRoomsSectionPendingFederationInvitation) {
  1258. FederationInvitationTableViewController *federationInvitationVC = [[FederationInvitationTableViewController alloc] init];
  1259. NCNavigationController *navigationController = [[NCNavigationController alloc] initWithRootViewController:federationInvitationVC];
  1260. [self presentViewController:navigationController animated:YES completion:nil];
  1261. return;
  1262. }
  1263. if (tableView == _resultTableViewController.tableView) {
  1264. // Messages
  1265. NKSearchEntry *message = [_resultTableViewController messageForIndexPath:indexPath];
  1266. if (message) {
  1267. [self presentSelectedMessageInChat:message];
  1268. return;
  1269. }
  1270. // Users
  1271. NCUser *user = [_resultTableViewController userForIndexPath:indexPath];
  1272. if (user) {
  1273. [self createRoomForSelectedUser:user];
  1274. return;
  1275. }
  1276. }
  1277. // Present room chat
  1278. [self presentChatForRoomAtIndexPath:indexPath];
  1279. }
  1280. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point
  1281. {
  1282. if (![tableView isEqual:self.tableView]) {
  1283. return nil;
  1284. }
  1285. __weak typeof(self) weakSelf = self;
  1286. NCRoom *room = [self roomForIndexPath:indexPath];
  1287. NSMutableArray *actions = [[NSMutableArray alloc] init];
  1288. NSString *favImageName = (room.isFavorite) ? @"star.slash" : @"star";
  1289. UIImage *favImage = [[UIImage systemImageNamed:favImageName] imageWithTintColor:UIColor.systemYellowColor renderingMode:UIImageRenderingModeAlwaysOriginal];
  1290. NSString *favActionName = (room.isFavorite) ? NSLocalizedString(@"Remove from favorites", nil) : NSLocalizedString(@"Add to favorites", nil);
  1291. UIAction *favAction = [UIAction actionWithTitle:favActionName image:favImage identifier:nil handler:^(UIAction *action) {
  1292. weakSelf.contextMenuActionBlock = ^{
  1293. if (room.isFavorite) {
  1294. [weakSelf removeRoomFromFavorites:room];
  1295. } else {
  1296. [weakSelf addRoomToFavorites:room];
  1297. }
  1298. };
  1299. }];
  1300. [actions addObject:favAction];
  1301. // Mark room as read/unread
  1302. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityChatReadMarker] &&
  1303. (!room.isFederated || [[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityChatReadLast])) {
  1304. if (room.unreadMessages > 0) {
  1305. // Mark room as read
  1306. UIAction *markReadAction = [UIAction actionWithTitle:NSLocalizedString(@"Mark as read", nil) image:[UIImage systemImageNamed:@"eye"] identifier:nil handler:^(UIAction *action) {
  1307. weakSelf.contextMenuActionBlock = ^{
  1308. [weakSelf markRoomAsRead:room];
  1309. };
  1310. }];
  1311. [actions addObject:markReadAction];
  1312. } else if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityChatUnread]) {
  1313. // Mark room as unread
  1314. UIAction *markUnreadAction = [UIAction actionWithTitle:NSLocalizedString(@"Mark as unread", nil) image:[UIImage systemImageNamed:@"eye.slash"] identifier:nil handler:^(UIAction *action) {
  1315. weakSelf.contextMenuActionBlock = ^{
  1316. [weakSelf markRoomAsUnread:room];
  1317. };
  1318. }];
  1319. [actions addObject:markUnreadAction];
  1320. }
  1321. }
  1322. // Notification levels
  1323. if ([[NCDatabaseManager sharedInstance] serverHasTalkCapability:kCapabilityNotificationLevels] &&
  1324. room.type != kNCRoomTypeChangelog && room.type != kNCRoomTypeNoteToSelf) {
  1325. NSMutableArray *notificationActions = [[NSMutableArray alloc] init];
  1326. [notificationActions addObject:[self actionForNotificationLevel:kNCRoomNotificationLevelAlways forRoom:room]];
  1327. [notificationActions addObject:[self actionForNotificationLevel:kNCRoomNotificationLevelMention forRoom:room]];
  1328. [notificationActions addObject:[self actionForNotificationLevel:kNCRoomNotificationLevelNever forRoom:room]];
  1329. NSString *notificationTitle = [NSString stringWithFormat:NSLocalizedString(@"Notifications: %@", nil), room.notificationLevelString];
  1330. UIMenu *notificationMenu = [UIMenu menuWithTitle:notificationTitle
  1331. image:[UIImage systemImageNamed:@"bell"]
  1332. identifier:nil
  1333. options:0
  1334. children:notificationActions];
  1335. [actions addObject:notificationMenu];
  1336. }
  1337. // Share link
  1338. if (room.type != kNCRoomTypeChangelog && room.type != kNCRoomTypeNoteToSelf) {
  1339. UIAction *notificationActions = [UIAction actionWithTitle:NSLocalizedString(@"Share link", nil) image:[UIImage systemImageNamed:@"square.and.arrow.up"] identifier:nil handler:^(UIAction *action) {
  1340. [weakSelf shareLinkFromRoom:room];
  1341. }];
  1342. [actions addObject:notificationActions];
  1343. }
  1344. // Room info
  1345. UIAction *roomInfoAction = [UIAction actionWithTitle:NSLocalizedString(@"Conversation settings", nil) image:[UIImage systemImageNamed:@"gearshape"] identifier:nil handler:^(UIAction *action) {
  1346. [weakSelf presentRoomInfoForRoom:room];
  1347. }];
  1348. [actions addObject:roomInfoAction];
  1349. UIAction *deleteAction;
  1350. if (room.isLeavable && room.type != kNCRoomTypeNoteToSelf) {
  1351. deleteAction = [UIAction actionWithTitle:NSLocalizedString(@"Leave conversation", nil) image:[UIImage systemImageNamed:@"arrow.right.square"] identifier:nil handler:^(UIAction *action) {
  1352. [weakSelf leaveRoom:room];
  1353. }];
  1354. } else {
  1355. deleteAction = [UIAction actionWithTitle:NSLocalizedString(@"Delete conversation", nil) image:[UIImage systemImageNamed:@"trash"] identifier:nil handler:^(UIAction *action) {
  1356. [weakSelf deleteRoom:room];
  1357. }];
  1358. }
  1359. deleteAction.attributes = UIMenuElementAttributesDestructive;
  1360. UIMenu *deleteMenu = [UIMenu menuWithTitle:@""
  1361. image:nil
  1362. identifier:nil
  1363. options:UIMenuOptionsDisplayInline
  1364. children:@[deleteAction]];
  1365. [actions addObject:deleteMenu];
  1366. UIMenu *menu = [UIMenu menuWithTitle:@"" children:actions];
  1367. UIContextMenuConfiguration *configuration = [UIContextMenuConfiguration configurationWithIdentifier:indexPath previewProvider:^UIViewController * _Nullable{
  1368. return nil;
  1369. } actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
  1370. return menu;
  1371. }];
  1372. return configuration;
  1373. }
  1374. - (UITargetedPreview *)tableView:(UITableView *)tableView previewForHighlightingContextMenuWithConfiguration:(UIContextMenuConfiguration *)configuration
  1375. {
  1376. if (![tableView isEqual:self.tableView]) {
  1377. return nil;
  1378. }
  1379. NSIndexPath *indexPath = (NSIndexPath *)configuration.identifier;
  1380. // Use a snapshot here to not interfere with room refresh
  1381. UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1382. UIView *previewView = [cell.contentView snapshotViewAfterScreenUpdates:NO];
  1383. // On large iPhones (with regular landscape size, like iPhone X) we need to take the safe area into account when calculating the center
  1384. CGFloat cellCenterX = cell.center.x + self.view.safeAreaInsets.left / 2 - self.view.safeAreaInsets.right / 2;
  1385. CGPoint cellCenter = CGPointMake(cellCenterX, cell.center.y);
  1386. // Create a preview target which allows us to have a transparent background
  1387. UIPreviewTarget *previewTarget = [[UIPreviewTarget alloc] initWithContainer:self.view center:cellCenter];
  1388. UIPreviewParameters *previewParameter = [[UIPreviewParameters alloc] init];
  1389. // Remove the background and the drop shadow from our custom preview view
  1390. previewParameter.backgroundColor = UIColor.systemBackgroundColor;
  1391. previewParameter.shadowPath = [[UIBezierPath alloc] init];
  1392. return [[UITargetedPreview alloc] initWithView:previewView parameters:previewParameter target:previewTarget];
  1393. }
  1394. - (void)tableView:(UITableView *)tableView willEndContextMenuInteractionWithConfiguration:(UIContextMenuConfiguration *)configuration animator:(id<UIContextMenuInteractionAnimating>)animator
  1395. {
  1396. if (![tableView isEqual:self.tableView]) {
  1397. return;
  1398. }
  1399. [animator addCompletion:^{
  1400. // Wait until the context menu is completely hidden before we execute any method
  1401. if (self->_contextMenuActionBlock) {
  1402. self->_contextMenuActionBlock();
  1403. self->_contextMenuActionBlock = nil;
  1404. }
  1405. }];
  1406. }
  1407. - (void)setSelectedRoomToken:(NSString *)selectedRoomToken
  1408. {
  1409. _selectedRoomToken = selectedRoomToken;
  1410. [self highlightSelectedRoom];
  1411. }
  1412. - (void)removeRoomSelection {
  1413. [self setSelectedRoomToken:nil];
  1414. }
  1415. - (void)highlightSelectedRoom
  1416. {
  1417. if(_selectedRoomToken != nil) {
  1418. NSUInteger idx = [_rooms indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
  1419. NCRoom* room = (NCRoom*)obj;
  1420. return [room.token isEqualToString:_selectedRoomToken];
  1421. }];
  1422. if (idx != NSNotFound) {
  1423. NSIndexPath* indexPath = [NSIndexPath indexPathForRow:idx inSection:1];
  1424. [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
  1425. }
  1426. } else {
  1427. NSIndexPath *selectedRow = [self.tableView indexPathForSelectedRow];
  1428. if (selectedRow != nil) {
  1429. [self.tableView deselectRowAtIndexPath:selectedRow animated:YES];
  1430. // Needed to make sure the highlight is really removed
  1431. [self.tableView reloadRowsAtIndexPaths:@[selectedRow] withRowAnimation:UITableViewRowAnimationNone];
  1432. }
  1433. }
  1434. }
  1435. @end