-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathATLMConversationViewController.m
More file actions
executable file
·707 lines (608 loc) · 29.7 KB
/
Copy pathATLMConversationViewController.m
File metadata and controls
executable file
·707 lines (608 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//
// ATLMConversationViewController.m
// Atlas Messenger
//
// Created by Kevin Coleman on 9/10/14.
// Copyright (c) 2014 Layer, Inc. All rights reserved.
//
// 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 "ATLMConversationViewController.h"
#import "ATLMConversationDetailViewController.h"
#import "ATLMMediaViewController.h"
#import "ATLMUtilities.h"
#import "ATLMParticipantTableViewController.h"
#import "ATLMSplitViewController.h"
#import "LYRIdentity+ATLParticipant.h"
#import "MEConversationViewSwizzle.h"
#import "MEOutgoingMessageCollectionViewCell.h"
#import "MEIncomingMessageCollectionViewCell.h"
// Makemoji Addition
#import "METextInputView.h"
static NSDateFormatter *ATLMShortTimeFormatter()
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
}
return dateFormatter;
}
static NSDateFormatter *ATLMDayOfWeekDateFormatter()
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"EEEE"; // Tuesday
}
return dateFormatter;
}
static NSDateFormatter *ATLMRelativeDateFormatter()
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.doesRelativeDateFormatting = YES;
}
return dateFormatter;
}
static NSDateFormatter *ATLMThisYearDateFormatter()
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"E, MMM dd,"; // Sat, Nov 29,
}
return dateFormatter;
}
static NSDateFormatter *ATLMDefaultDateFormatter()
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MMM dd, yyyy,"; // Nov 29, 2013,
}
return dateFormatter;
}
typedef NS_ENUM(NSInteger, ATLMDateProximity) {
ATLMDateProximityToday,
ATLMDateProximityYesterday,
ATLMDateProximityWeek,
ATLMDateProximityYear,
ATLMDateProximityOther,
};
static ATLMDateProximity ATLMProximityToDate(NSDate *date)
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
NSCalendarUnit calendarUnits = NSEraCalendarUnit | NSYearCalendarUnit | NSWeekOfMonthCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
#pragma GCC diagnostic pop
NSDateComponents *dateComponents = [calendar components:calendarUnits fromDate:date];
NSDateComponents *todayComponents = [calendar components:calendarUnits fromDate:now];
if (dateComponents.day == todayComponents.day &&
dateComponents.month == todayComponents.month &&
dateComponents.year == todayComponents.year &&
dateComponents.era == todayComponents.era) {
return ATLMDateProximityToday;
}
NSDateComponents *componentsToYesterday = [NSDateComponents new];
componentsToYesterday.day = -1;
NSDate *yesterday = [calendar dateByAddingComponents:componentsToYesterday toDate:now options:0];
NSDateComponents *yesterdayComponents = [calendar components:calendarUnits fromDate:yesterday];
if (dateComponents.day == yesterdayComponents.day &&
dateComponents.month == yesterdayComponents.month &&
dateComponents.year == yesterdayComponents.year &&
dateComponents.era == yesterdayComponents.era) {
return ATLMDateProximityYesterday;
}
if (dateComponents.weekOfMonth == todayComponents.weekOfMonth &&
dateComponents.month == todayComponents.month &&
dateComponents.year == todayComponents.year &&
dateComponents.era == todayComponents.era) {
return ATLMDateProximityWeek;
}
if (dateComponents.year == todayComponents.year &&
dateComponents.era == todayComponents.era) {
return ATLMDateProximityYear;
}
return ATLMDateProximityOther;
}
@interface ATLMConversationViewController () <ATLMConversationDetailViewControllerDelegate, ATLParticipantTableViewControllerDelegate>
//Makemoji additions
@property (nonatomic) METextInputView * meTextInputView;
@property (nonatomic) NSMutableArray * messageCells;
@end
@implementation ATLMConversationViewController
NSString *const ATLMConversationViewControllerAccessibilityLabel = @"Conversation View Controller";
NSString *const ATLMDetailsButtonAccessibilityLabel = @"Details Button";
NSString *const ATLMDetailsButtonLabel = @"Details";
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.accessibilityLabel = ATLMConversationViewControllerAccessibilityLabel;
self.dataSource = self;
self.delegate = self;
if (self.conversation) {
[self addDetailsButton];
}
[self configureUserInterfaceAttributes];
[self registerNotificationObservers];
// Makemoji Addition: Use this array to keep track of message position since heightForMessage does not return an index path
self.messageCells = [NSMutableArray array];
// nil the existing Input Accessory view to remove the message toolbar
ATLConversationView * conversationView = (ATLConversationView *)self.view;
conversationView.inputAccessoryView = nil;
self.shouldDisplayAvatarItemForOneOtherParticipant = YES;
self.shouldDisplayAvatarItemForAuthenticatedUser = YES;
// initialize the Makemoji text input and toolbar
self.meTextInputView = [[METextInputView alloc] initWithFrame:CGRectZero];
self.meTextInputView.delegate = self;
[self.view addSubview:self.meTextInputView];
// initially hide the toolbar for recipient picker
self.meTextInputView.hidden = YES;
self.collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
// custom collection view cell for displaying HTML messages
[self registerClass:[MEOutgoingMessageCollectionViewCell class] forMessageCellWithReuseIdentifier:@"MEOutgoingMessageCollectionViewCell"];
[self registerClass:[MEIncomingMessageCollectionViewCell class] forMessageCellWithReuseIdentifier:@"MEIncomingMessageCollectionViewCell"];
self.edgesForExtendedLayout = UIRectEdgeNone;
// initial offsets
self.collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, (self.view.frame.size.height-self.meTextInputView.frame.origin.y), 0);
self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, (self.view.frame.size.height-self.meTextInputView.frame.origin.y), 0);
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self configureTitle];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.conversation != nil) { self.meTextInputView.hidden = NO; [self.meTextInputView showKeyboard]; }
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (![self isMovingFromParentViewController]) {
[self.view resignFirstResponder];
[self.meTextInputView hideKeyboard];
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (NSString *)conversationViewController:(ATLConversationViewController *)viewController reuseIdentifierForMessage:(LYRMessage *)message {
LYRMessagePart *part = message.parts[0];
NSString * messageText = [[NSString alloc] initWithData:part.data encoding:NSUTF8StringEncoding];
if ([part.MIMEType isEqualToString:@"text/plain"] && [METextInputView detectMakemojiMessage:messageText] == YES) {
if ([message.sender.userID isEqualToString:self.layerClient.authenticatedUser.userID]) {
return @"MEOutgoingMessageCollectionViewCell";
} else {
return @"MEIncomingMessageCollectionViewCell";
}
}
return nil;
}
- (CGFloat)conversationViewController:(ATLConversationViewController *)viewController heightForMessage:(LYRMessage *)message withCellWidth:(CGFloat)cellWidth {
LYRMessagePart *part = message.parts[0];
NSString * messageText = [[NSString alloc] initWithData:part.data encoding:NSUTF8StringEncoding];
if ([part.MIMEType isEqualToString:@"text/plain"] && [METextInputView detectMakemojiMessage:messageText] == YES) {
NSString * messageHTML = [METextInputView convertSubstituedToHTML:messageText];
NSString * messsageIdentifier = [message.identifier absoluteString];
NSUInteger index;
if ([self.messageCells containsObject:messsageIdentifier]) {
index = [self.messageCells indexOfObject:[message.identifier absoluteString]];
} else {
[self.messageCells addObject:messsageIdentifier];
index = [self.messageCells indexOfObject:[message.identifier absoluteString]];
}
CGFloat messageHeight = [self.meTextInputView cellHeightForHTML:messageHTML
atIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
maxCellWidth:ATLMaxCellWidth()
cellStyle:MECellStyleSimple];
CGFloat totalHeight = messageHeight + ATLMessageBubbleLabelVerticalPadding*2;
if (totalHeight < ATLMessageBubbleDefaultHeight) totalHeight = ATLMessageBubbleDefaultHeight;
return totalHeight;
}
return 0;
}
// the chat input frame changed size (keyboard show, expanding input)
-(void)meTextInputView:(METextInputView *)inputView didChangeFrame:(CGRect)frame {
CGFloat collapsedHeight = self.view.frame.size.height-frame.size.height;
CGFloat heightOffset = (self.view.frame.size.height-self.meTextInputView.frame.origin.y);
CGFloat topOffset = 0;
if (self.addressBarController != nil && self.addressBarController.view.subviews.count > 0) {
UIView * addressBarView = (UIView *)[self.addressBarController.view.subviews objectAtIndex:0];
topOffset = addressBarView.frame.size.height;
}
if (heightOffset != self.collectionView.contentInset.bottom) {
self.collectionView.scrollIndicatorInsets = UIEdgeInsetsMake(topOffset, 0, heightOffset, 0);
self.collectionView.contentInset = UIEdgeInsetsMake(topOffset, 0, heightOffset, 0);
if (frame.origin.y != collapsedHeight) {
[self scrollToBottomAnimated:YES];
}
}
}
-(void)meTextInputView:(METextInputView *)inputView didTapCameraButton:(UIButton*)cameraButton {
[self.meTextInputView hideKeyboard];
[self.messageInputToolbar.inputToolBarDelegate messageInputToolbar:self.messageInputToolbar didTapLeftAccessoryButton:self.messageInputToolbar.leftAccessoryButton];
}
// send button was pressed
-(void)meTextInputView:(METextInputView *)inputView didTapSend:(NSDictionary *)message {
NSData *messageData = [[message objectForKey:@"substitute"] dataUsingEncoding:NSUTF8StringEncoding];
LYRMessagePart *messagePart = [LYRMessagePart messagePartWithMIMEType:@"text/plain" data:messageData];
NSError *error = nil;
LYRMessage *layerMessage = [self.layerClient newMessageWithParts:@[ messagePart ] options:nil error:&error];
BOOL success = [self.conversation sendMessage:layerMessage error:&error];
}
#pragma mark - Accessors
- (void)setConversation:(LYRConversation *)conversation
{
[super setConversation:conversation];
[self configureTitle];
if (conversation != nil) {
self.meTextInputView.hidden = NO;
[self.meTextInputView showKeyboard];
}
}
#pragma mark - ATLConversationViewControllerDelegate
/**
Atlas - Informs the delegate of a successful message send. Atlas Messenger adds a `Details` button to the navigation bar if this is the first message sent within a new conversation.
*/
- (void)conversationViewController:(ATLConversationViewController *)viewController didSendMessage:(LYRMessage *)message
{
[self addDetailsButton];
}
/**
Atlas - Informs the delegate that a message failed to send. Atlas messeneger display an alert view to inform the user of the failure.
*/
- (void)conversationViewController:(ATLConversationViewController *)viewController didFailSendingMessage:(LYRMessage *)message error:(NSError *)error;
{
NSLog(@"Message Send Failed with Error: %@", error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Messaging Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
/**
Atlas - Informs the delegate that a message was selected. Atlas messenger presents an `ATLImageViewController` if the message contains an image.
*/
- (void)conversationViewController:(ATLConversationViewController *)viewController didSelectMessage:(LYRMessage *)message
{
LYRMessagePart *messagePart = ATLMessagePartForMIMEType(message, ATLMIMETypeImageJPEG);
if (messagePart) {
[self presentMediaViewControllerWithMessage:message];
return;
}
messagePart = ATLMessagePartForMIMEType(message, ATLMIMETypeImagePNG);
if (messagePart) {
[self presentMediaViewControllerWithMessage:message];
return;
}
messagePart = ATLMessagePartForMIMEType(message, ATLMIMETypeImageGIF);
if (messagePart) {
[self presentMediaViewControllerWithMessage:message];
return;
}
messagePart = ATLMessagePartForMIMEType(message, ATLMIMETypeVideoMP4);
if (messagePart) {
[self presentMediaViewControllerWithMessage:message];
return;
}
}
- (void)presentMediaViewControllerWithMessage:(LYRMessage *)message
{
ATLMMediaViewController *imageViewController = [[ATLMMediaViewController alloc] initWithMessage:message];
UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:imageViewController];
[self.navigationController presentViewController:controller animated:YES completion:nil];
}
#pragma mark - ATLConversationViewControllerDataSource
/**
Atlas - Returns an object conforming to the `ATLParticipant` protocol whose `userID` property matches the supplied identity.
*/
- (id<ATLParticipant>)conversationViewController:(ATLConversationViewController *)conversationViewController participantForIdentity:(nonnull LYRIdentity *)identity
{
return identity;
}
/**
Atlas - Returns an `NSAttributedString` object for a given date. The format of this string can be configured to whatever format an application wishes to display.
*/
- (NSAttributedString *)conversationViewController:(ATLConversationViewController *)conversationViewController attributedStringForDisplayOfDate:(NSDate *)date
{
NSDateFormatter *dateFormatter;
ATLMDateProximity dateProximity = ATLMProximityToDate(date);
switch (dateProximity) {
case ATLMDateProximityToday:
case ATLMDateProximityYesterday:
dateFormatter = ATLMRelativeDateFormatter();
break;
case ATLMDateProximityWeek:
dateFormatter = ATLMDayOfWeekDateFormatter();
break;
case ATLMDateProximityYear:
dateFormatter = ATLMThisYearDateFormatter();
break;
case ATLMDateProximityOther:
dateFormatter = ATLMDefaultDateFormatter();
break;
}
NSString *dateString = [dateFormatter stringFromDate:date];
NSString *timeString = [ATLMShortTimeFormatter() stringFromDate:date];
NSMutableAttributedString *dateAttributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@", dateString, timeString]];
[dateAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, dateAttributedString.length)];
[dateAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, dateAttributedString.length)];
[dateAttributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:11] range:NSMakeRange(0, dateString.length)];
return dateAttributedString;
}
/**
Atlas - Returns an `NSAttributedString` object for given recipient state. The state string will only be displayed below the latest message that was sent by the currently authenticated user.
*/
- (NSAttributedString *)conversationViewController:(ATLConversationViewController *)conversationViewController attributedStringForDisplayOfRecipientStatus:(NSDictionary *)recipientStatus
{
NSMutableDictionary *mutableRecipientStatus = [recipientStatus mutableCopy];
if ([mutableRecipientStatus valueForKey:self.applicationController.layerClient.authenticatedUser.userID]) {
[mutableRecipientStatus removeObjectForKey:self.applicationController.layerClient.authenticatedUser.userID];
}
NSString *statusString = [NSString new];
if (mutableRecipientStatus.count > 1) {
__block NSUInteger readCount = 0;
__block BOOL delivered = NO;
__block BOOL sent = NO;
__block BOOL pending = NO;
[mutableRecipientStatus enumerateKeysAndObjectsUsingBlock:^(NSString *userID, NSNumber *statusNumber, BOOL *stop) {
LYRRecipientStatus status = statusNumber.integerValue;
switch (status) {
case LYRRecipientStatusInvalid:
break;
case LYRRecipientStatusPending:
pending = YES;
break;
case LYRRecipientStatusSent:
sent = YES;
break;
case LYRRecipientStatusDelivered:
delivered = YES;
break;
case LYRRecipientStatusRead:
readCount += 1;
break;
}
}];
if (readCount) {
NSString *participantString = readCount > 1 ? @"Participants" : @"Participant";
statusString = [NSString stringWithFormat:@"Read by %lu %@", (unsigned long)readCount, participantString];
} else if (pending) {
statusString = @"Pending";
}else if (delivered) {
statusString = @"Delivered";
} else if (sent) {
statusString = @"Sent";
}
} else {
__block NSString *blockStatusString = [NSString new];
[mutableRecipientStatus enumerateKeysAndObjectsUsingBlock:^(NSString *userID, NSNumber *statusNumber, BOOL *stop) {
if ([userID isEqualToString:self.applicationController.layerClient.authenticatedUser.userID]) return;
LYRRecipientStatus status = statusNumber.integerValue;
switch (status) {
case LYRRecipientStatusInvalid:
blockStatusString = @"Not Sent";
break;
case LYRRecipientStatusPending:
blockStatusString = @"Pending";
break;
case LYRRecipientStatusSent:
blockStatusString = @"Sent";
break;
case LYRRecipientStatusDelivered:
blockStatusString = @"Delivered";
break;
case LYRRecipientStatusRead:
blockStatusString = @"Read";
break;
}
}];
statusString = blockStatusString;
}
return [[NSAttributedString alloc] initWithString:statusString attributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:11]}];
}
#pragma mark - ATLAddressBarControllerDelegate
/**
Atlas - Informs the delegate that the user tapped the `addContacts` icon in the `ATLAddressBarViewController`. Atlas Messenger presents an `ATLParticipantPickerController`.
*/
- (void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController didTapAddContactsButton:(UIButton *)addContactsButton
{
NSSet *selectedParticipantIDs = [addressBarViewController.selectedParticipants valueForKey:@"userID"];
if (!selectedParticipantIDs) {
selectedParticipantIDs = [NSSet new];
}
LYRQuery *query = [LYRQuery queryWithQueryableClass:[LYRIdentity class]];
query.predicate = [LYRPredicate predicateWithProperty:@"userID" predicateOperator:LYRPredicateOperatorIsNotIn value:selectedParticipantIDs];
NSError *error;
NSOrderedSet *identities = [self.layerClient executeQuery:query error:&error];
if (error) {
ATLMAlertWithError(error);
}
ATLMParticipantTableViewController *controller = [ATLMParticipantTableViewController participantTableViewControllerWithParticipants:identities.set sortType:ATLParticipantPickerSortTypeFirstName];
controller.blockedParticipantIdentifiers = [self.layerClient.policies valueForKey:@"sentByUserID"];
controller.delegate = self;
controller.allowsMultipleSelection = NO;
UINavigationController *navigationController =[[UINavigationController alloc] initWithRootViewController:controller];
[self.navigationController presentViewController:navigationController animated:YES completion:nil];
[self.meTextInputView hideKeyboard];
}
/**
Atlas - Informs the delegate that the user is searching for participants. Atlas Messengers queries for participants whose `fullName` property contains the given search string.
*/
- (void)addressBarViewController:(ATLAddressBarViewController *)addressBarViewController searchForParticipantsMatchingText:(NSString *)searchText completion:(void (^)(NSArray *participants))completion
{
LYRQuery *query = [LYRQuery queryWithQueryableClass:[LYRIdentity class]];
query.predicate = [LYRPredicate predicateWithProperty:@"displayName" predicateOperator:LYRPredicateOperatorLike value:[searchText stringByAppendingString:@"%"]];
[self.layerClient executeQuery:query completion:^(NSOrderedSet<id<ATLParticipant>> * _Nullable resultSet, NSError * _Nullable error) {
if (resultSet) {
completion(resultSet.array);
} else {
completion([NSArray array]);
}
}];
}
/**
Atlas - Informs the delegate that the user tapped on the `ATLAddressBarViewController` while it was disabled. Atlas Messenger presents an `ATLConversationDetailViewController` in response.
*/
- (void)addressBarViewControllerDidSelectWhileDisabled:(ATLAddressBarViewController *)addressBarViewController
{
[self detailsButtonTapped];
}
#pragma mark - ATLParticipantTableViewControllerDelegate
/**
Atlas - Informs the delegate that the user selected an participant. Atlas Messenger in turn, informs the `ATLAddressBarViewController` of the selection.
*/
- (void)participantTableViewController:(ATLParticipantTableViewController *)participantTableViewController didSelectParticipant:(id<ATLParticipant>)participant
{
[self.addressBarController selectParticipant:participant];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
/**
Atlas - Informs the delegate that the user is searching for participants. Atlas Messengers queries for participants whose `fullName` property contains the give search string.
*/
- (void)participantTableViewController:(ATLParticipantTableViewController *)participantTableViewController didSearchWithString:(NSString *)searchText completion:(void (^)(NSSet *))completion
{
LYRQuery *query = [LYRQuery queryWithQueryableClass:[LYRIdentity class]];
query.predicate = [LYRPredicate predicateWithProperty:@"displayName" predicateOperator:LYRPredicateOperatorLike value:searchText];
[self.layerClient executeQuery:query completion:^(NSOrderedSet<id<ATLParticipant>> * _Nullable resultSet, NSError * _Nullable error) {
if (resultSet) {
completion(resultSet.set);
} else {
completion([NSSet set]);
}
}];
}
#pragma mark - LSConversationDetailViewControllerDelegate
/**
Atlas - Informs the delegate that the user has tapped the `Share My Current Location` button. Atlas Messenger sends a message into the current conversation with the current location.
*/
- (void)conversationDetailViewControllerDidSelectShareLocation:(ATLMConversationDetailViewController *)conversationDetailViewController
{
[self sendLocationMessage];
[self.navigationController popViewControllerAnimated:YES];
}
/**
Atlas - Informs the delegate that the conversation has changed. Atlas Messenger updates its conversation and the current view controller's title in response.
*/
- (void)conversationDetailViewController:(ATLMConversationDetailViewController *)conversationDetailViewController didChangeConversation:(LYRConversation *)conversation
{
self.conversation = conversation;
[self configureTitle];
[self.meTextInputView showKeyboard];
}
#pragma mark - Details Button Actions
- (void)addDetailsButton
{
if (self.navigationItem.rightBarButtonItem) return;
UIBarButtonItem *detailsButtonItem = [[UIBarButtonItem alloc] initWithTitle:ATLMDetailsButtonLabel
style:UIBarButtonItemStylePlain
target:self
action:@selector(detailsButtonTapped)];
detailsButtonItem.accessibilityLabel = ATLMDetailsButtonAccessibilityLabel;
self.navigationItem.rightBarButtonItem = detailsButtonItem;
}
- (void)detailsButtonTapped
{
ATLMConversationDetailViewController *detailViewController = [ATLMConversationDetailViewController conversationDetailViewControllerWithConversation:self.conversation];
detailViewController.detailDelegate = self;
detailViewController.applicationController = self.applicationController;
[self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark - Notification Handlers
- (void)conversationMetadataDidChange:(NSNotification *)notification
{
if (!self.conversation) return;
if (!notification.object) return;
if (![notification.object isEqual:self.conversation]) return;
[self configureTitle];
}
#pragma mark - Helpers
- (void)configureTitle
{
if ([self.conversation.metadata valueForKey:ATLMConversationMetadataNameKey]) {
NSString *conversationTitle = [self.conversation.metadata valueForKey:ATLMConversationMetadataNameKey];
if (conversationTitle.length) {
self.title = conversationTitle;
} else {
self.title = [self defaultTitle];
} } else {
self.title = [self defaultTitle];
}
}
- (NSString *)defaultTitle
{
if (!self.conversation) {
return @"New Message";
}
NSMutableSet *otherParticipants = [self.conversation.participants mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID != %@", self.layerClient.authenticatedUser.userID];
[otherParticipants filterUsingPredicate:predicate];
if (otherParticipants.count == 0) {
return @"Personal";
} else if (otherParticipants.count == 1) {
LYRIdentity *otherIdentity = [otherParticipants anyObject];
id<ATLParticipant> participant = [self conversationViewController:self participantForIdentity:otherIdentity];
return participant ? participant.firstName : @"Message";
} else if (otherParticipants.count > 1) {
NSUInteger participantCount = 0;
id<ATLParticipant> knownParticipant;
for (LYRIdentity *identity in otherParticipants) {
id<ATLParticipant> participant = [self conversationViewController:self participantForIdentity:identity];
if (participant) {
participantCount += 1;
knownParticipant = participant;
}
}
if (participantCount == 1) {
return knownParticipant.firstName;
} else if (participantCount > 1) {
return @"Group";
}
}
return @"Message";
}
#pragma mark - Link Tap Handler
- (void)userDidTapLink:(NSNotification *)notification
{
[[UIApplication sharedApplication] openURL:notification.object];
}
- (void)configureUserInterfaceAttributes
{
[[ATLIncomingMessageCollectionViewCell appearance] setBubbleViewColor:ATLLightGrayColor()];
[[ATLIncomingMessageCollectionViewCell appearance] setMessageTextColor:[UIColor blackColor]];
[[ATLIncomingMessageCollectionViewCell appearance] setMessageLinkTextColor:ATLBlueColor()];
[[ATLOutgoingMessageCollectionViewCell appearance] setBubbleViewColor:ATLBlueColor()];
[[ATLOutgoingMessageCollectionViewCell appearance] setMessageTextColor:[UIColor whiteColor]];
[[ATLOutgoingMessageCollectionViewCell appearance] setMessageLinkTextColor:[UIColor whiteColor]];
}
- (void)registerNotificationObservers
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTapLink:) name:ATLUserDidTapLinkNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conversationMetadataDidChange:) name:ATLMConversationMetadataDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
#pragma mark - Device Orientation
- (void)deviceOrientationDidChange:(NSNotification *)notification
{
[self.collectionView.collectionViewLayout invalidateLayout];
}
@end