chatsecureios / ChatSecure / Classes / View Controllers / OTRMessagesViewController.m @ c6c7b30a
History | View | Annotate | Download (100 KB)
1 |
// |
---|---|
2 |
// OTRMessagesViewController.m |
3 |
// Off the Record |
4 |
// |
5 |
// Created by David Chiles on 5/12/14. |
6 |
// Copyright (c) 2014 Chris Ballinger. All rights reserved. |
7 |
// |
8 |
|
9 |
#import "OTRMessagesViewController.h" |
10 |
|
11 |
#import "OTRDatabaseView.h" |
12 |
#import "OTRDatabaseManager.h" |
13 |
#import "OTRLog.h" |
14 |
|
15 |
#import "OTRBuddy.h" |
16 |
#import "OTRAccount.h" |
17 |
#import "OTRMessage+JSQMessageData.h" |
18 |
@import JSQMessagesViewController; |
19 |
@import MobileCoreServices; |
20 |
#import "OTRProtocolManager.h" |
21 |
#import "OTRXMPPTorAccount.h" |
22 |
#import "OTRXMPPManager.h" |
23 |
#import "OTRLockButton.h" |
24 |
#import "OTRButtonView.h" |
25 |
@import OTRAssets; |
26 |
#import "OTRTitleSubtitleView.h" |
27 |
@import OTRKit; |
28 |
@import FormatterKit; |
29 |
#import "OTRImages.h" |
30 |
#import "UIActivityViewController+ChatSecure.h" |
31 |
#import "OTRUtilities.h" |
32 |
#import "OTRProtocolManager.h" |
33 |
#import "OTRColors.h" |
34 |
#import "JSQMessagesCollectionViewCell+ChatSecure.h" |
35 |
@import BButton; |
36 |
#import "OTRAttachmentPicker.h" |
37 |
#import "OTRImageItem.h" |
38 |
#import "OTRVideoItem.h" |
39 |
#import "OTRAudioItem.h" |
40 |
@import JTSImageViewController; |
41 |
#import "OTRAudioControlsView.h" |
42 |
#import "OTRPlayPauseProgressView.h" |
43 |
#import "OTRAudioPlaybackController.h" |
44 |
#import "OTRMediaFileManager.h" |
45 |
#import "OTRMediaServer.h" |
46 |
#import "UIImage+ChatSecure.h" |
47 |
#import "OTRBaseLoginViewController.h" |
48 |
|
49 |
#import <ChatSecureCore/ChatSecureCore-Swift.h> |
50 |
#import "OTRYapMessageSendAction.h" |
51 |
#import "UIViewController+ChatSecure.h" |
52 |
#import "OTRBuddyCache.h" |
53 |
#import "OTRTextItem.h" |
54 |
#import "OTRHTMLItem.h" |
55 |
#import "OTRFileItem.h" |
56 |
@import YapDatabase; |
57 |
@import PureLayout; |
58 |
@import KVOController; |
59 |
|
60 |
@import AVFoundation; |
61 |
@import MediaPlayer; |
62 |
|
63 |
static NSTimeInterval const kOTRMessageSentDateShowTimeInterval = 5 * 60; |
64 |
static NSUInteger const kOTRMessagePageSize = 50; |
65 |
|
66 |
typedef NS_ENUM(int, OTRDropDownType) { |
67 |
OTRDropDownTypeNone = 0, |
68 |
OTRDropDownTypeEncryption = 1, |
69 |
OTRDropDownTypePush = 2 |
70 |
}; |
71 |
|
72 |
@interface OTRMessagesViewController () <UITextViewDelegate, OTRAttachmentPickerDelegate, OTRYapViewHandlerDelegateProtocol, OTRMessagesCollectionViewFlowLayoutSizeProtocol, OTRMessagesCollectionViewFlowLayoutSupplementaryViewProtocol, OTRRoomOccupantsViewControllerDelegate> { |
73 |
JSQMessagesAvatarImage *_warningAvatarImage; |
74 |
JSQMessagesAvatarImage *_accountAvatarImage; |
75 |
JSQMessagesAvatarImage *_buddyAvatarImage; |
76 |
} |
77 |
|
78 |
@property (nonatomic, strong) OTRYapViewHandler *viewHandler; |
79 |
|
80 |
@property (nonatomic, strong) JSQMessagesBubbleImage *outgoingBubbleImage; |
81 |
@property (nonatomic, strong) JSQMessagesBubbleImage *incomingBubbleImage; |
82 |
|
83 |
@property (nonatomic, weak) id didFinishGeneratingPrivateKeyNotificationObject; |
84 |
@property (nonatomic, weak) id messageStateDidChangeNotificationObject; |
85 |
@property (nonatomic, weak) id pendingApprovalDidChangeNotificationObject; |
86 |
@property (nonatomic, weak) id deviceListUpdateNotificationObject; |
87 |
|
88 |
|
89 |
@property (nonatomic ,strong) UIBarButtonItem *lockBarButtonItem; |
90 |
@property (nonatomic, strong) OTRLockButton *lockButton; |
91 |
@property (nonatomic, strong) OTRButtonView *buttonDropdownView; |
92 |
|
93 |
@property (nonatomic, strong) OTRAttachmentPicker *attachmentPicker; |
94 |
@property (nonatomic, strong) OTRAudioPlaybackController *audioPlaybackController; |
95 |
|
96 |
@property (nonatomic, strong) NSTimer *lastSeenRefreshTimer; |
97 |
@property (nonatomic, strong) UIView *jidForwardingHeaderView; |
98 |
|
99 |
@property (nonatomic) BOOL loadingMessages; |
100 |
@property (nonatomic) BOOL messageRangeExtended; |
101 |
@property (nonatomic, strong) NSIndexPath *currentIndexPath; |
102 |
@property (nonatomic, strong) id currentMessage; |
103 |
@property (nonatomic, strong) NSCache *messageSizeCache; |
104 |
|
105 |
@property (nonatomic) BOOL automaticURLFetchingDisabled; |
106 |
@property (nonatomic, strong) OTRMessagesUnknownSenderCell *prototypeCellUnknownSender; |
107 |
|
108 |
@end |
109 |
|
110 |
@implementation OTRMessagesViewController |
111 |
|
112 |
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil |
113 |
{ |
114 |
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { |
115 |
self.senderId = @""; |
116 |
self.senderDisplayName = @""; |
117 |
_state = [[MessagesViewControllerState alloc] init]; |
118 |
self.messageSizeCache = [NSCache new]; |
119 |
self.messageSizeCache.countLimit = kOTRMessagePageSize; |
120 |
self.messageRangeExtended = NO; |
121 |
} |
122 |
return self; |
123 |
} |
124 |
|
125 |
#pragma - mark Lifecylce Methods |
126 |
|
127 |
- (void) dealloc { |
128 |
[self.lastSeenRefreshTimer invalidate]; |
129 |
[[NSNotificationCenter defaultCenter] removeObserver:self]; |
130 |
} |
131 |
|
132 |
- (void)viewDidLoad |
133 |
{ |
134 |
[super viewDidLoad]; |
135 |
|
136 |
self.automaticallyScrollsToMostRecentMessage = YES; |
137 |
|
138 |
////// bubbles ////// |
139 |
JSQMessagesBubbleImageFactory *bubbleImageFactory = [[JSQMessagesBubbleImageFactory alloc] init]; |
140 |
|
141 |
self.outgoingBubbleImage = [bubbleImageFactory outgoingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleBlueColor]]; |
142 |
|
143 |
self.incomingBubbleImage = [bubbleImageFactory incomingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleLightGrayColor]]; |
144 |
|
145 |
////// TitleView ////// |
146 |
OTRTitleSubtitleView *titleView = [self titleView]; |
147 |
[self refreshTitleView:titleView]; |
148 |
self.navigationItem.titleView = titleView; |
149 |
|
150 |
////// Send Button ////// |
151 |
self.sendButton = [JSQMessagesToolbarButtonFactory defaultSendButtonItem]; |
152 |
|
153 |
////// Attachment Button ////// |
154 |
self.inputToolbar.contentView.leftBarButtonItem = nil; |
155 |
self.cameraButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; |
156 |
self.cameraButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFont size:20]; |
157 |
self.cameraButton.titleLabel.textAlignment = NSTextAlignmentCenter; |
158 |
[self.cameraButton setTitle:[NSString fa_stringForFontAwesomeIcon:FACamera] forState:UIControlStateNormal]; |
159 |
self.cameraButton.frame = CGRectMake(0, 0, 32, 32); |
160 |
|
161 |
////// Microphone Button ////// |
162 |
self.microphoneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; |
163 |
self.microphoneButton.frame = CGRectMake(0, 0, 32, 32); |
164 |
self.microphoneButton.titleLabel.font = [UIFont fontWithName:kFontAwesomeFont size:20]; |
165 |
self.microphoneButton.titleLabel.textAlignment = NSTextAlignmentCenter; |
166 |
[self.microphoneButton setTitle:[NSString fa_stringForFontAwesomeIcon:FAMicrophone] |
167 |
forState:UIControlStateNormal]; |
168 |
|
169 |
self.audioPlaybackController = [[OTRAudioPlaybackController alloc] init]; |
170 |
|
171 |
////// TextViewUpdates ////// |
172 |
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedTextViewChangedNotification:) name:UITextViewTextDidChangeNotification object:self.inputToolbar.contentView.textView]; |
173 |
|
174 |
/** Setup databse view handler*/ |
175 |
self.viewHandler = [[OTRYapViewHandler alloc] initWithDatabaseConnection:[OTRDatabaseManager sharedInstance].longLivedReadOnlyConnection databaseChangeNotificationName:[DatabaseNotificationName LongLivedTransactionChanges]]; |
176 |
self.viewHandler.delegate = self; |
177 |
|
178 |
///Custom Layout to account for no bubble cells |
179 |
OTRMessagesCollectionViewFlowLayout *layout = [[OTRMessagesCollectionViewFlowLayout alloc] init]; |
180 |
layout.sizeDelegate = self; |
181 |
layout.supplementaryViewDelegate = self; |
182 |
self.collectionView.collectionViewLayout = layout; |
183 |
UINib *nib = [UINib nibWithNibName:@"OTRMessageUnknownSenderCell" bundle:OTRAssets.resourcesBundle]; |
184 |
[self.collectionView registerNib:nib forSupplementaryViewOfKind:[OTRMessagesUnknownSenderCell reuseIdentifier] withReuseIdentifier:[OTRMessagesUnknownSenderCell reuseIdentifier]]; |
185 |
|
186 |
///"Loading Earlier" header view |
187 |
[self.collectionView registerNib:[UINib nibWithNibName:@"OTRMessagesLoadingView" bundle:OTRAssets.resourcesBundle] |
188 |
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader |
189 |
withReuseIdentifier:[JSQMessagesLoadEarlierHeaderView headerReuseIdentifier]]; |
190 |
|
191 |
//Subscribe to changes in encryption state |
192 |
__weak typeof(self)weakSelf = self; |
193 |
[self.KVOController observe:self.state keyPath:NSStringFromSelector(@selector(messageSecurity)) options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew block:^(id _Nullable observer, id _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) { |
194 |
__typeof__(self) strongSelf = weakSelf; |
195 |
if (!strongSelf) { return; } |
196 |
|
197 |
if ([object isKindOfClass:[MessagesViewControllerState class]]) { |
198 |
MessagesViewControllerState *state = (MessagesViewControllerState*)object; |
199 |
NSString * placeHolderString = nil; |
200 |
switch (state.messageSecurity) { |
201 |
case OTRMessageTransportSecurityPlaintext: |
202 |
case OTRMessageTransportSecurityPlaintextWithOTR: |
203 |
placeHolderString = SEND_PLAINTEXT_STRING(); |
204 |
break; |
205 |
case OTRMessageTransportSecurityOTR: |
206 |
placeHolderString = [NSString stringWithFormat:SEND_ENCRYPTED_STRING(),@"OTR"]; |
207 |
break; |
208 |
case OTRMessageTransportSecurityOMEMO: |
209 |
placeHolderString = [NSString stringWithFormat:SEND_ENCRYPTED_STRING(),@"OMEMO"];; |
210 |
break; |
211 |
|
212 |
default: |
213 |
placeHolderString = [NSBundle jsq_localizedStringForKey:@"new_message"]; |
214 |
break; |
215 |
} |
216 |
strongSelf.inputToolbar.contentView.textView.placeHolder = placeHolderString; |
217 |
[self didUpdateState]; |
218 |
} |
219 |
}]; |
220 |
|
221 |
} |
222 |
|
223 |
- (void)viewDidAppear:(BOOL)animated |
224 |
{ |
225 |
[super viewDidAppear:animated]; |
226 |
[self tryToMarkAllMessagesAsRead]; |
227 |
// This is a hack to attempt fixing https://github.com/ChatSecure/ChatSecure-iOS/issues/657 |
228 |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ |
229 |
[self scrollToBottomAnimated:animated]; |
230 |
}); |
231 |
self.loadingMessages = NO; |
232 |
} |
233 |
|
234 |
- (void)viewWillAppear:(BOOL)animated |
235 |
{ |
236 |
self.currentIndexPath = nil; |
237 |
|
238 |
[super viewWillAppear:animated]; |
239 |
[[UIApplication sharedApplication] setStatusBarHidden:NO]; |
240 |
|
241 |
if (self.lastSeenRefreshTimer) { |
242 |
[self.lastSeenRefreshTimer invalidate]; |
243 |
_lastSeenRefreshTimer = nil; |
244 |
} |
245 |
_lastSeenRefreshTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshTitleTimerUpdate:) userInfo:nil repeats:YES]; |
246 |
|
247 |
__weak typeof(self)weakSelf = self; |
248 |
void (^refreshGeneratingLock)(OTRAccount *) = ^void(OTRAccount * account) { |
249 |
__strong typeof(weakSelf)strongSelf = weakSelf; |
250 |
__block NSString *accountKey = nil; |
251 |
[strongSelf.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
252 |
accountKey = [strongSelf buddyWithTransaction:transaction].accountUniqueId; |
253 |
}]; |
254 |
if ([account.uniqueId isEqualToString:accountKey]) { |
255 |
[strongSelf updateEncryptionState]; |
256 |
} |
257 |
|
258 |
|
259 |
}; |
260 |
|
261 |
self.didFinishGeneratingPrivateKeyNotificationObject = [[NSNotificationCenter defaultCenter] addObserverForName:OTRDidFinishGeneratingPrivateKeyNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { |
262 |
if ([note.object isKindOfClass:[OTRAccount class]]) { |
263 |
refreshGeneratingLock(note.object); |
264 |
} |
265 |
}]; |
266 |
|
267 |
self.messageStateDidChangeNotificationObject = [[NSNotificationCenter defaultCenter] addObserverForName:OTRMessageStateDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { |
268 |
__strong typeof(weakSelf)strongSelf = weakSelf; |
269 |
if ([note.object isKindOfClass:[OTRBuddy class]]) { |
270 |
OTRBuddy *notificationBuddy = note.object; |
271 |
__block NSString *buddyKey = nil; |
272 |
[strongSelf.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
273 |
buddyKey = [strongSelf buddyWithTransaction:transaction].uniqueId; |
274 |
}]; |
275 |
if ([notificationBuddy.uniqueId isEqualToString:buddyKey]) { |
276 |
[strongSelf updateEncryptionState]; |
277 |
} |
278 |
} |
279 |
}]; |
280 |
|
281 |
if ([self.threadKey length]) { |
282 |
[self.viewHandler.keyCollectionObserver observe:self.threadKey collection:self.threadCollection]; |
283 |
[self updateViewWithKey:self.threadKey collection:self.threadCollection]; |
284 |
[self.viewHandler setup:OTRFilteredChatDatabaseViewExtensionName groups:@[self.threadKey]]; |
285 |
if(![self.inputToolbar.contentView.textView.text length]) { |
286 |
[self moveLastComposingTextForThreadKey:self.threadKey colleciton:self.threadCollection toTextView:self.inputToolbar.contentView.textView]; |
287 |
} |
288 |
} |
289 |
|
290 |
self.loadingMessages = YES; |
291 |
[self.collectionView reloadData]; |
292 |
} |
293 |
|
294 |
- (void)viewWillDisappear:(BOOL)animated |
295 |
{ |
296 |
[super viewWillDisappear:animated]; |
297 |
|
298 |
[self.lastSeenRefreshTimer invalidate]; |
299 |
self.lastSeenRefreshTimer = nil; |
300 |
|
301 |
[self saveCurrentMessageText:self.inputToolbar.contentView.textView.text threadKey:self.threadKey colleciton:self.threadCollection]; |
302 |
|
303 |
[[NSNotificationCenter defaultCenter] removeObserver:self.messageStateDidChangeNotificationObject]; |
304 |
[[NSNotificationCenter defaultCenter] removeObserver:self.didFinishGeneratingPrivateKeyNotificationObject]; |
305 |
|
306 |
// [self.inputToolbar.contentView.textView resignFirstResponder]; |
307 |
} |
308 |
|
309 |
- (void)viewDidDisappear:(BOOL)animated |
310 |
{ |
311 |
[super viewDidDisappear:animated]; |
312 |
|
313 |
_warningAvatarImage = nil; |
314 |
_accountAvatarImage = nil; |
315 |
_buddyAvatarImage = nil; |
316 |
} |
317 |
|
318 |
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { |
319 |
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; |
320 |
|
321 |
// After the transition is done, we need to reset the size caches and relayout |
322 |
// Do this using the technique in https://stackoverflow.com/questions/26943808/ios-how-to-run-a-function-after-device-has-rotated-swift |
323 |
[coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { |
324 |
[self.messageSizeCache removeAllObjects]; |
325 |
[self.collectionView.collectionViewLayout invalidateLayoutWithContext:[JSQMessagesCollectionViewFlowLayoutInvalidationContext context]]; |
326 |
}]; |
327 |
} |
328 |
|
329 |
#pragma - mark Setters & getters |
330 |
|
331 |
- (OTRAttachmentPicker *)attachmentPicker |
332 |
{ |
333 |
if (!_attachmentPicker) { |
334 |
_attachmentPicker = [[OTRAttachmentPicker alloc] initWithParentViewController:self delegate:self]; |
335 |
} |
336 |
return _attachmentPicker; |
337 |
} |
338 |
|
339 |
- (NSArray*) indexPathsToCount:(NSUInteger)count { |
340 |
NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:count]; |
341 |
for (NSUInteger i = 0; i < count; i++) { |
342 |
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0]; |
343 |
[indexPaths addObject:indexPath]; |
344 |
} |
345 |
return indexPaths; |
346 |
} |
347 |
|
348 |
- (nullable id<OTRThreadOwner>)threadObjectWithTransaction:(nonnull YapDatabaseReadTransaction *)transaction { |
349 |
if (!self.threadKey || !self.threadCollection || !transaction) { return nil; } |
350 |
id object = [transaction objectForKey:self.threadKey inCollection:self.threadCollection]; |
351 |
if ([object conformsToProtocol:@protocol(OTRThreadOwner)]) { |
352 |
return object; |
353 |
} |
354 |
return nil; |
355 |
} |
356 |
|
357 |
- (nullable OTRBuddy *)buddyWithTransaction:(nonnull YapDatabaseReadTransaction *)transaction { |
358 |
id <OTRThreadOwner> object = [self threadObjectWithTransaction:transaction]; |
359 |
if ([object isKindOfClass:[OTRBuddy class]]) { |
360 |
return (OTRBuddy *)object; |
361 |
} |
362 |
return nil; |
363 |
} |
364 |
|
365 |
- (nullable OTRXMPPRoom *)roomWithTransaction:(nonnull YapDatabaseReadTransaction *)transaction { |
366 |
id <OTRThreadOwner> object = [self threadObjectWithTransaction:transaction]; |
367 |
if ([object isKindOfClass:[OTRXMPPRoom class]]) { |
368 |
return (OTRXMPPRoom *)object; |
369 |
} |
370 |
return nil; |
371 |
} |
372 |
|
373 |
- (nullable OTRAccount *)accountWithTransaction:(nonnull YapDatabaseReadTransaction *)transaction { |
374 |
id <OTRThreadOwner> thread = [self threadObjectWithTransaction:transaction]; |
375 |
if (!thread) { return nil; } |
376 |
OTRAccount *account = [OTRAccount fetchObjectWithUniqueID:[thread threadAccountIdentifier] transaction:transaction]; |
377 |
return account; |
378 |
} |
379 |
|
380 |
- (void)setThreadKey:(NSString *)key collection:(NSString *)collection |
381 |
{ |
382 |
self.currentIndexPath = nil; |
383 |
NSString *oldKey = self.threadKey; |
384 |
NSString *oldCollection = self.threadCollection; |
385 |
|
386 |
self.threadKey = key; |
387 |
self.threadCollection = collection; |
388 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
389 |
self.senderId = [[self threadObjectWithTransaction:transaction] threadAccountIdentifier]; |
390 |
self.automaticURLFetchingDisabled = [[self accountWithTransaction:transaction] disableAutomaticURLFetching]; |
391 |
}]; |
392 |
|
393 |
// Clear out old state (don't just alloc a new object, we have KVOs attached to this!) |
394 |
self.state.canSendMedia = NO; |
395 |
self.state.canKnock = NO; |
396 |
self.state.messageSecurity = OTRMessageTransportSecurityInvalid; |
397 |
self.state.hasText = NO; |
398 |
self.state.isThreadOnline = NO; |
399 |
self.showTypingIndicator = NO; |
400 |
|
401 |
// This is set to nil so the refreshTitleView: method knows to reset username instead of last seen time |
402 |
[self titleView].subtitleLabel.text = nil; |
403 |
|
404 |
if (![oldKey isEqualToString:key] || ![oldCollection isEqualToString:collection]) { |
405 |
[self saveCurrentMessageText:self.inputToolbar.contentView.textView.text threadKey:oldKey colleciton:oldCollection]; |
406 |
self.inputToolbar.contentView.textView.text = nil; |
407 |
[self receivedTextViewChanged:self.inputToolbar.contentView.textView]; |
408 |
} |
409 |
|
410 |
[self.viewHandler.keyCollectionObserver stopObserving:oldKey collection:oldCollection]; |
411 |
if (self.threadKey && self.threadCollection) { |
412 |
[self.viewHandler.keyCollectionObserver observe:self.threadKey collection:self.threadCollection]; |
413 |
[self updateViewWithKey:self.threadKey collection:self.threadCollection]; |
414 |
[self.viewHandler setup:OTRFilteredChatDatabaseViewExtensionName groups:@[self.threadKey]]; |
415 |
[self moveLastComposingTextForThreadKey:self.threadKey colleciton:self.threadCollection toTextView:self.inputToolbar.contentView.textView]; |
416 |
} else { |
417 |
// Reset the view handler |
418 |
self.viewHandler = [[OTRYapViewHandler alloc] initWithDatabaseConnection:[OTRDatabaseManager sharedInstance].longLivedReadOnlyConnection databaseChangeNotificationName:[DatabaseNotificationName LongLivedTransactionChanges]]; |
419 |
self.viewHandler.delegate = self; |
420 |
self.senderDisplayName = @""; |
421 |
self.senderId = @""; |
422 |
} |
423 |
|
424 |
[self.collectionView reloadData]; |
425 |
|
426 |
// Profile Info Button |
427 |
[self setupInfoButton]; |
428 |
|
429 |
[self updateEncryptionState]; |
430 |
[self updateJIDForwardingHeader]; |
431 |
|
432 |
__weak typeof(self)weakSelf = self; |
433 |
if (self.pendingApprovalDidChangeNotificationObject == nil) { |
434 |
self.pendingApprovalDidChangeNotificationObject = [[NSNotificationCenter defaultCenter] addObserverForName:OTRBuddyPendingApprovalDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { |
435 |
__strong typeof(weakSelf)strongSelf = weakSelf; |
436 |
OTRXMPPBuddy *notificationBuddy = [note.userInfo objectForKey:@"buddy"]; |
437 |
__block NSString *buddyKey = nil; |
438 |
[strongSelf.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
439 |
buddyKey = [strongSelf buddyWithTransaction:transaction].uniqueId; |
440 |
}]; |
441 |
if ([notificationBuddy.uniqueId isEqualToString:buddyKey]) { |
442 |
[strongSelf fetchOMEMODeviceList]; |
443 |
[strongSelf sendPresenceProbe]; |
444 |
} |
445 |
}]; |
446 |
} |
447 |
|
448 |
if (self.deviceListUpdateNotificationObject == nil) { |
449 |
self.deviceListUpdateNotificationObject = [[NSNotificationCenter defaultCenter] addObserverForName:OTROMEMOSignalCoordinator.DeviceListUpdateNotificationName object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) { |
450 |
__strong typeof(weakSelf)strongSelf = weakSelf; |
451 |
XMPPJID *notificationJid = [note.userInfo objectForKey:@"jid"]; |
452 |
__block NSString *buddyUser = nil; |
453 |
[strongSelf.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
454 |
buddyUser = [strongSelf buddyWithTransaction:transaction].username; |
455 |
}]; |
456 |
if (notificationJid != nil && [notificationJid.bare isEqualToString:buddyUser]) { |
457 |
[strongSelf updateEncryptionState]; |
458 |
} |
459 |
}]; |
460 |
} |
461 |
|
462 |
[self sendPresenceProbe]; |
463 |
[self fetchOMEMODeviceList]; |
464 |
} |
465 |
|
466 |
|
467 |
- (YapDatabaseConnection *)readOnlyDatabaseConnection |
468 |
{ |
469 |
if (!_readOnlyDatabaseConnection) { |
470 |
_readOnlyDatabaseConnection = [OTRDatabaseManager sharedInstance].readOnlyDatabaseConnection; |
471 |
} |
472 |
return _readOnlyDatabaseConnection; |
473 |
} |
474 |
|
475 |
- (YapDatabaseConnection *)readWriteDatabaseConnection |
476 |
{ |
477 |
if (!_readWriteDatabaseConnection) { |
478 |
_readWriteDatabaseConnection = [OTRDatabaseManager sharedInstance].readWriteDatabaseConnection; |
479 |
} |
480 |
return _readWriteDatabaseConnection; |
481 |
} |
482 |
|
483 |
|
484 |
- (nullable OTRXMPPManager *)xmppManagerWithTransaction:(nonnull YapDatabaseReadTransaction *)transaction { |
485 |
OTRAccount *account = [self accountWithTransaction:transaction]; |
486 |
if (!account) { return nil; } |
487 |
return (OTRXMPPManager *)[[OTRProtocolManager sharedInstance] protocolForAccount:account]; |
488 |
} |
489 |
|
490 |
/** Will send a probe to fetch last seen */ |
491 |
- (void) sendPresenceProbe { |
492 |
__block OTRXMPPManager *xmpp = nil; |
493 |
__block OTRXMPPBuddy *buddy = nil; |
494 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
495 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
496 |
buddy = (OTRXMPPBuddy*)[self buddyWithTransaction:transaction]; |
497 |
}]; |
498 |
if (!xmpp || ![buddy isKindOfClass:[OTRXMPPBuddy class]] || buddy.pendingApproval) { return; } |
499 |
[xmpp sendPresenceProbeForBuddy:buddy]; |
500 |
} |
501 |
|
502 |
- (void)updateViewWithKey:(NSString *)key collection:(NSString *)collection |
503 |
{ |
504 |
if ([collection isEqualToString:[OTRBuddy collection]]) { |
505 |
__block OTRBuddy *buddy = nil; |
506 |
__block OTRAccount *account = nil; |
507 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
508 |
buddy = [OTRBuddy fetchObjectWithUniqueID:key transaction:transaction]; |
509 |
account = [OTRAccount fetchObjectWithUniqueID:buddy.accountUniqueId transaction:transaction]; |
510 |
}]; |
511 |
|
512 |
|
513 |
|
514 |
//Update UI now |
515 |
if (buddy.chatState == OTRChatStateComposing || buddy.chatState == OTRChatStatePaused) { |
516 |
self.showTypingIndicator = YES; |
517 |
} |
518 |
else { |
519 |
self.showTypingIndicator = NO; |
520 |
} |
521 |
|
522 |
// Update Buddy Status |
523 |
BOOL previousState = self.state.isThreadOnline; |
524 |
self.state.isThreadOnline = buddy.status != OTRThreadStatusOffline; |
525 |
|
526 |
[self didUpdateState]; |
527 |
|
528 |
//Update Buddy knock status |
529 |
//Async because this calls down to the database and iterates over a relation. Might slowdown the UI if on main thread |
530 |
__weak __typeof__(self) weakSelf = self; |
531 |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ |
532 |
__typeof__(self) strongSelf = weakSelf; |
533 |
__block BOOL canKnock = [[[OTRProtocolManager sharedInstance].pushController pushStorage] numberOfTokensForBuddy:buddy.uniqueId createdByThisAccount:NO] > 0; |
534 |
dispatch_async(dispatch_get_main_queue(), ^{ |
535 |
if (canKnock != strongSelf.state.canKnock) { |
536 |
strongSelf.state.canKnock = canKnock; |
537 |
[strongSelf didUpdateState]; |
538 |
} |
539 |
}); |
540 |
|
541 |
}); |
542 |
|
543 |
[self refreshTitleView:[self titleView]]; |
544 |
|
545 |
// Auto-inititate OTR when contact comes online |
546 |
if (!previousState && self.state.isThreadOnline) { |
547 |
[[OTRProtocolManager sharedInstance].encryptionManager maybeRefreshOTRSessionForBuddyKey:key collection:collection]; |
548 |
} |
549 |
} else if ([collection isEqualToString:[OTRXMPPRoom collection]]) { |
550 |
__block OTRXMPPRoom *room = nil; |
551 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
552 |
room = [OTRXMPPRoom fetchObjectWithUniqueID:key transaction:transaction]; |
553 |
}]; |
554 |
self.state.isThreadOnline = room.currentStatus != OTRThreadStatusOffline; |
555 |
[self didUpdateState]; |
556 |
[self refreshTitleView:[self titleView]]; |
557 |
} |
558 |
[self tryToMarkAllMessagesAsRead]; |
559 |
} |
560 |
|
561 |
- (void)tryToMarkAllMessagesAsRead { |
562 |
// Set all messages as read |
563 |
if ([self otr_isVisible]) { |
564 |
__weak __typeof__(self) weakSelf = self; |
565 |
__block id <OTRThreadOwner>threadOwner = nil; |
566 |
__block NSArray <id <OTRMessageProtocol>>* unreadMessages = nil; |
567 |
[self.readOnlyDatabaseConnection asyncReadWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
568 |
threadOwner = [weakSelf threadObjectWithTransaction:transaction]; |
569 |
if (!threadOwner) { return; } |
570 |
unreadMessages = [transaction allUnreadMessagesForThread:threadOwner]; |
571 |
} completionBlock:^{ |
572 |
|
573 |
if ([unreadMessages count] == 0) { |
574 |
return; |
575 |
} |
576 |
|
577 |
//Mark as read |
578 |
|
579 |
NSMutableArray <id <OTRMessageProtocol>>*toBeSaved = [[NSMutableArray alloc] init]; |
580 |
|
581 |
[unreadMessages enumerateObjectsUsingBlock:^(id<OTRMessageProtocol> _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { |
582 |
if ([obj isKindOfClass:[OTRIncomingMessage class]]) { |
583 |
OTRIncomingMessage *message = [((OTRIncomingMessage *)obj) copy]; |
584 |
message.read = YES; |
585 |
[toBeSaved addObject:message]; |
586 |
} else if ([obj isKindOfClass:[OTRXMPPRoomMessage class]]) { |
587 |
OTRXMPPRoomMessage *message = [((OTRXMPPRoomMessage *)obj) copy]; |
588 |
message.read = YES; |
589 |
[toBeSaved addObject:message]; |
590 |
} |
591 |
}]; |
592 |
|
593 |
[weakSelf.readWriteDatabaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
594 |
[toBeSaved enumerateObjectsUsingBlock:^(id<OTRMessageProtocol> _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { |
595 |
[transaction setObject:obj forKey:[obj messageKey] inCollection:[obj messageCollection]]; |
596 |
}]; |
597 |
[transaction touchObjectForKey:[threadOwner threadIdentifier] inCollection:[threadOwner threadCollection]]; |
598 |
}]; |
599 |
}]; |
600 |
} |
601 |
} |
602 |
|
603 |
- (OTRTitleSubtitleView * __nonnull)titleView { |
604 |
UIView *titleView = self.navigationItem.titleView; |
605 |
if ([titleView isKindOfClass:[OTRTitleSubtitleView class]]) { |
606 |
return (OTRTitleSubtitleView*)titleView; |
607 |
} |
608 |
return [[OTRTitleSubtitleView alloc] initWithFrame:CGRectMake(0, 0, 200, 44)]; |
609 |
} |
610 |
|
611 |
- (void)refreshTitleTimerUpdate:(NSTimer*)timer { |
612 |
[self refreshTitleView:[self titleView]]; |
613 |
} |
614 |
|
615 |
/** Updates the title view with the current thread information on this view controller*/ |
616 |
- (void)refreshTitleView:(OTRTitleSubtitleView *)titleView |
617 |
{ |
618 |
__block id<OTRThreadOwner> thread = nil; |
619 |
__block OTRAccount *account = nil; |
620 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
621 |
thread = [self threadObjectWithTransaction:transaction]; |
622 |
account = [self accountWithTransaction:transaction]; |
623 |
}]; |
624 |
|
625 |
titleView.titleLabel.text = [thread threadName]; |
626 |
|
627 |
UIImage *statusImage = nil; |
628 |
if ([thread isKindOfClass:[OTRBuddy class]]) { |
629 |
OTRBuddy *buddy = (OTRBuddy*)thread; |
630 |
UIColor *color = [buddy avatarBorderColor]; |
631 |
if (color) { // only show online status |
632 |
statusImage = [OTRImages circleWithRadius:50 |
633 |
lineWidth:0 |
634 |
lineColor:nil |
635 |
fillColor:color]; |
636 |
} |
637 |
|
638 |
dispatch_block_t refreshTimeBlock = ^{ |
639 |
__block OTRBuddy *buddy = nil; |
640 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
641 |
buddy = (OTRBuddy*)[self threadObjectWithTransaction:transaction]; |
642 |
}]; |
643 |
if (![buddy isKindOfClass:[OTRBuddy class]]) { |
644 |
return; |
645 |
} |
646 |
NSDate *lastSeen = [OTRBuddyCache.shared lastSeenDateForBuddy:buddy]; |
647 |
OTRThreadStatus status = [OTRBuddyCache.shared threadStatusForBuddy:buddy]; |
648 |
if (!lastSeen) { |
649 |
titleView.subtitleLabel.text = buddy.username; |
650 |
return; |
651 |
} |
652 |
TTTTimeIntervalFormatter *tf = [[TTTTimeIntervalFormatter alloc] init]; |
653 |
tf.presentTimeIntervalMargin = 60; |
654 |
tf.usesAbbreviatedCalendarUnits = YES; |
655 |
NSTimeInterval lastSeenInterval = [lastSeen timeIntervalSinceDate:[NSDate date]]; |
656 |
NSString *labelString = nil; |
657 |
if (status == OTRThreadStatusAvailable) { |
658 |
labelString = buddy.username; |
659 |
} else { |
660 |
labelString = [NSString stringWithFormat:@"%@ %@", ACTIVE_STRING(), [tf stringForTimeInterval:lastSeenInterval]]; |
661 |
} |
662 |
titleView.subtitleLabel.text = labelString; |
663 |
}; |
664 |
|
665 |
// Set the username if nothing else is set. |
666 |
// This should be cleared out when buddy is changed |
667 |
if (!titleView.subtitleLabel.text) { |
668 |
titleView.subtitleLabel.text = buddy.username; |
669 |
} |
670 |
|
671 |
// Show an "Last seen 11 min ago" in title bar after brief delay |
672 |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ |
673 |
refreshTimeBlock(); |
674 |
}); |
675 |
} else if ([thread isGroupThread]) { |
676 |
titleView.subtitleLabel.text = GROUP_CHAT_STRING(); |
677 |
} else { |
678 |
titleView.subtitleLabel.text = nil; |
679 |
} |
680 |
|
681 |
titleView.titleImageView.image = statusImage; |
682 |
|
683 |
} |
684 |
|
685 |
/** |
686 |
This generates a UIAlertAction where the handler fetches the outgoing message (optionaly duplicates). Then if media message resend media message. If not update messageSecurityInfo and date and create new sending action. |
687 |
*/ |
688 |
- (UIAlertAction *)resendOutgoingMessageActionForMessageKey:(NSString *)messageKey |
689 |
messageCollection:(NSString *)messageCollection |
690 |
readWriteDatabaseConnection:(YapDatabaseConnection*)databaseConnection |
691 |
title:(NSString *)title |
692 |
{ |
693 |
UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { |
694 |
[databaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
695 |
id object = [[transaction objectForKey:messageKey inCollection:messageCollection] copy]; |
696 |
id<OTRMessageProtocol> message = nil; |
697 |
if ([object conformsToProtocol:@protocol(OTRMessageProtocol)]) { |
698 |
message = (id<OTRMessageProtocol>)object; |
699 |
} else { |
700 |
return; |
701 |
} |
702 |
// Messages that never sent properly don't need to be duplicated client-side |
703 |
NSError *messageError = message.messageError; |
704 |
message = [message duplicateMessage]; |
705 |
message.messageError = nil; |
706 |
message.messageSecurity = self.state.messageSecurity; |
707 |
message.messageDate = [NSDate date]; |
708 |
[message saveWithTransaction:transaction]; |
709 |
|
710 |
// We only need to re-upload failed media messages |
711 |
// otherwise just resend the URL directly |
712 |
if (message.messageMediaItemKey.length && |
713 |
(!message.messageText.length || messageError)) { |
714 |
OTRMediaItem *mediaItem = [OTRMediaItem fetchObjectWithUniqueID:message.messageMediaItemKey transaction:transaction]; |
715 |
[self sendMediaItem:mediaItem data:nil message:message transaction:transaction]; |
716 |
} else { |
717 |
OTRYapMessageSendAction *sendingAction = [OTRYapMessageSendAction sendActionForMessage:message date:message.messageDate]; |
718 |
[sendingAction saveWithTransaction:transaction]; |
719 |
} |
720 |
}]; |
721 |
}]; |
722 |
return action; |
723 |
} |
724 |
|
725 |
- (nonnull UIAlertAction *)viewProfileAction { |
726 |
return [UIAlertAction actionWithTitle:VIEW_PROFILE_STRING() style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { |
727 |
[self infoButtonPressed:action]; |
728 |
}]; |
729 |
} |
730 |
|
731 |
- (nonnull UIAlertAction *)cancleAction { |
732 |
return [UIAlertAction actionWithTitle:CANCEL_STRING() |
733 |
style:UIAlertActionStyleCancel |
734 |
handler:nil]; |
735 |
} |
736 |
|
737 |
- (NSArray <UIAlertAction *>*)actionForMessage:(id<OTRMessageProtocol>)message { |
738 |
NSMutableArray <UIAlertAction *>*actions = [[NSMutableArray alloc] init]; |
739 |
|
740 |
if (!message.isMessageIncoming) { |
741 |
// This is an outgoing message so we can offer to resend |
742 |
UIAlertAction *resendAction = [self resendOutgoingMessageActionForMessageKey:message.messageKey messageCollection:message.messageCollection readWriteDatabaseConnection:self.readWriteDatabaseConnection title:RESEND_STRING()]; |
743 |
[actions addObject:resendAction]; |
744 |
} |
745 |
|
746 |
if (![message isKindOfClass:[OTRXMPPRoomMessage class]]) { |
747 |
[actions addObject:[self viewProfileAction]]; |
748 |
} |
749 |
|
750 |
NSArray<UIAlertAction*> *mediaActions = [UIAlertAction actionsForMediaMessage:message sourceView:self.view viewController:self]; |
751 |
[actions addObjectsFromArray:mediaActions]; |
752 |
|
753 |
[actions addObject:[self cancleAction]]; |
754 |
return actions; |
755 |
} |
756 |
|
757 |
- (void)didTapAvatar:(id<OTRMessageProtocol>)message sender:(id)sender { |
758 |
NSError *error = [message messageError]; |
759 |
NSString *title = nil; |
760 |
NSString *alertMessage = nil; |
761 |
|
762 |
NSString * sendingType = UNENCRYPTED_STRING(); |
763 |
switch (self.state.messageSecurity) { |
764 |
case OTRMessageTransportSecurityOTR: |
765 |
sendingType = @"OTR"; |
766 |
break; |
767 |
case OTRMessageTransportSecurityOMEMO: |
768 |
sendingType = @"OMEMO"; |
769 |
break; |
770 |
|
771 |
default: |
772 |
break; |
773 |
} |
774 |
|
775 |
if ([message isKindOfClass:[OTROutgoingMessage class]]) { |
776 |
title = RESEND_MESSAGE_TITLE(); |
777 |
alertMessage = [NSString stringWithFormat:RESEND_DESCRIPTION_STRING(),sendingType]; |
778 |
} |
779 |
|
780 |
if (error) { |
781 |
NSUInteger otrFingerprintError = 32872; |
782 |
title = ERROR_STRING(); |
783 |
alertMessage = error.localizedDescription; |
784 |
|
785 |
if (error.code == otrFingerprintError) { |
786 |
alertMessage = NO_DEVICES_BUDDY_ERROR_STRING(); |
787 |
} |
788 |
|
789 |
if([message isKindOfClass:[OTROutgoingMessage class]]) { |
790 |
//If it's an outgoing message the error title should be that we were unable to send the message. |
791 |
title = UNABLE_TO_SEND_STRING(); |
792 |
|
793 |
|
794 |
|
795 |
NSString *resendDescription = [NSString stringWithFormat:RESEND_DESCRIPTION_STRING(),sendingType]; |
796 |
alertMessage = [alertMessage stringByAppendingString:[NSString stringWithFormat:@"\n%@",resendDescription]]; |
797 |
|
798 |
//If this is an error about not having a trusted identity then we should offer to connect to the |
799 |
if (error.code == OTROMEMOErrorNoDevicesForBuddy || |
800 |
error.code == OTROMEMOErrorNoDevices || |
801 |
error.code == otrFingerprintError) { |
802 |
|
803 |
alertMessage = [alertMessage stringByAppendingString:[NSString stringWithFormat:@"\n%@",VIEW_PROFILE_DESCRIPTION_STRING()]]; |
804 |
} |
805 |
} |
806 |
} |
807 |
|
808 |
|
809 |
if (![self isMessageTrusted:message]) { |
810 |
title = UNTRUSTED_DEVICE_STRING(); |
811 |
if ([message isMessageIncoming]) { |
812 |
alertMessage = UNTRUSTED_DEVICE_REVEIVED_STRING(); |
813 |
} else { |
814 |
alertMessage = UNTRUSTED_DEVICE_SENT_STRING(); |
815 |
} |
816 |
alertMessage = [alertMessage stringByAppendingString:[NSString stringWithFormat:@"\n%@",VIEW_PROFILE_DESCRIPTION_STRING()]]; |
817 |
} |
818 |
|
819 |
NSArray <UIAlertAction*>*actions = [self actionForMessage:message]; |
820 |
if ([actions count] > 0) { |
821 |
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:alertMessage preferredStyle:UIAlertControllerStyleActionSheet]; |
822 |
[actions enumerateObjectsUsingBlock:^(UIAlertAction * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { |
823 |
[alertController addAction:obj]; |
824 |
}]; |
825 |
if ([sender isKindOfClass:[UIView class]]) { |
826 |
UIView *sourceView = sender; |
827 |
alertController.popoverPresentationController.sourceView = sourceView; |
828 |
alertController.popoverPresentationController.sourceRect = sourceView.bounds; |
829 |
} |
830 |
[self presentViewController:alertController animated:YES completion:nil]; |
831 |
} |
832 |
} |
833 |
|
834 |
- (BOOL)isMessageTrusted:(id <OTRMessageProtocol>)message { |
835 |
BOOL trusted = YES; |
836 |
if (![message isKindOfClass:[OTRBaseMessage class]]) { |
837 |
return trusted; |
838 |
} |
839 |
|
840 |
OTRBaseMessage *baseMessage = (OTRBaseMessage *)message; |
841 |
|
842 |
|
843 |
if (baseMessage.messageSecurityInfo.messageSecurity == OTRMessageTransportSecurityOTR) { |
844 |
NSData *otrFingerprintData = baseMessage.messageSecurityInfo.otrFingerprint; |
845 |
if ([otrFingerprintData length]) { |
846 |
trusted = [[[OTRProtocolManager sharedInstance].encryptionManager otrFingerprintForKey:self.threadKey collection:self.threadCollection fingerprint:otrFingerprintData] isTrusted]; |
847 |
} |
848 |
} else if (baseMessage.messageSecurityInfo.messageSecurity == OTRMessageTransportSecurityOMEMO) { |
849 |
NSString *omemoDeviceYapKey = baseMessage.messageSecurityInfo.omemoDeviceYapKey; |
850 |
NSString *omemoDeviceYapCollection = baseMessage.messageSecurityInfo.omemoDeviceYapCollection; |
851 |
__block OTROMEMODevice *device = nil; |
852 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
853 |
device = [transaction objectForKey:omemoDeviceYapKey inCollection:omemoDeviceYapCollection]; |
854 |
}]; |
855 |
if(device != nil) { |
856 |
trusted = [device isTrusted]; |
857 |
} |
858 |
} |
859 |
return trusted; |
860 |
} |
861 |
|
862 |
- (BOOL) isGroupChat { |
863 |
__block OTRXMPPRoom *room = nil; |
864 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
865 |
room = [self roomWithTransaction:transaction]; |
866 |
}]; |
867 |
return (room != nil); |
868 |
} |
869 |
|
870 |
#pragma - mark Profile Button Methods |
871 |
|
872 |
- (void)setupInfoButton { |
873 |
if ([self isGroupChat]) { |
874 |
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"112-group" inBundle:[OTRAssets resourcesBundle] compatibleWithTraitCollection:nil] style:UIBarButtonItemStylePlain target:self action:@selector(didSelectOccupantsButton:)]; |
875 |
self.navigationItem.rightBarButtonItem = barButtonItem; |
876 |
} else { |
877 |
UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight]; |
878 |
infoButton.accessibilityIdentifier = @"profileButton"; |
879 |
[infoButton addTarget:self action:@selector(infoButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; |
880 |
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton]; |
881 |
} |
882 |
} |
883 |
|
884 |
- (void) infoButtonPressed:(id)sender { |
885 |
__block OTRAccount *account = nil; |
886 |
__block OTRBuddy *buddy = nil; |
887 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
888 |
account = [self accountWithTransaction:transaction]; |
889 |
buddy = [self buddyWithTransaction:transaction]; |
890 |
}]; |
891 |
if (!account || !buddy) { |
892 |
return; |
893 |
} |
894 |
|
895 |
// Hack to manually re-fetch OMEMO devicelist because PEP sucks |
896 |
// TODO: Ideally this should be moved to some sort of manual refresh in the Profile view |
897 |
[self fetchOMEMODeviceList]; |
898 |
|
899 |
XLFormDescriptor *form = [UserProfileViewController profileFormDescriptorForAccount:account buddies:@[buddy] connection:self.readOnlyDatabaseConnection]; |
900 |
|
901 |
UserProfileViewController *verify = [[UserProfileViewController alloc] initWithAccountKey:account.uniqueId connection:self.readOnlyDatabaseConnection form:form]; |
902 |
verify.completionBlock = ^{ |
903 |
[self updateEncryptionState]; |
904 |
}; |
905 |
UINavigationController *verifyNav = [[UINavigationController alloc] initWithRootViewController:verify]; |
906 |
verifyNav.modalPresentationStyle = UIModalPresentationFormSheet; |
907 |
[self presentViewController:verifyNav animated:YES completion:nil]; |
908 |
} |
909 |
|
910 |
- (void)didSelectOccupantsButton:(id)sender { |
911 |
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"OTRRoomOccupants" bundle:[OTRAssets resourcesBundle]]; |
912 |
OTRRoomOccupantsViewController *occupantsVC = [storyboard instantiateViewControllerWithIdentifier:@"roomOccupants"]; |
913 |
occupantsVC.delegate = self; |
914 |
[occupantsVC setupViewHandlerWithDatabaseConnection:[OTRDatabaseManager sharedInstance].longLivedReadOnlyConnection roomKey:self.threadKey]; |
915 |
[self.navigationController pushViewController:occupantsVC animated:YES]; |
916 |
} |
917 |
|
918 |
// Hack to manually re-fetch OMEMO devicelist because PEP sucks |
919 |
// TODO: Ideally this should be moved to some sort of manual refresh in the Profile view |
920 |
-(void) fetchOMEMODeviceList { |
921 |
__block OTRAccount *account = nil; |
922 |
__block OTRBuddy *buddy = nil; |
923 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
924 |
account = [self accountWithTransaction:transaction]; |
925 |
buddy = [self buddyWithTransaction:transaction]; |
926 |
}]; |
927 |
if (!account || !buddy) { |
928 |
return; |
929 |
} |
930 |
id manager = [[OTRProtocolManager sharedInstance] protocolForAccount:account]; |
931 |
if ([manager isKindOfClass:[OTRXMPPManager class]]) { |
932 |
XMPPJID *jid = [XMPPJID jidWithString:buddy.username]; |
933 |
OTRXMPPManager *xmpp = manager; |
934 |
[xmpp.omemoSignalCoordinator.omemoModule fetchDeviceIdsForJID:jid elementId:nil]; |
935 |
} |
936 |
} |
937 |
|
938 |
- (UIBarButtonItem *)rightBarButtonItem |
939 |
{ |
940 |
if (!self.lockBarButtonItem) { |
941 |
self.lockBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.lockButton]; |
942 |
} |
943 |
return self.lockBarButtonItem; |
944 |
} |
945 |
|
946 |
-(void)updateEncryptionState |
947 |
{ |
948 |
if ([self isGroupChat]) { |
949 |
__block OTRXMPPManager *xmpp = nil; |
950 |
[self.readOnlyDatabaseConnection asyncReadWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
951 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
952 |
} completionBlock:^{ |
953 |
BOOL canSendMedia = NO; |
954 |
// Check for XEP-0363 HTTP upload |
955 |
// TODO: move this check elsewhere so it isnt dependent on refreshing crypto state |
956 |
if (xmpp != nil && xmpp.fileTransferManager.canUploadFiles) { |
957 |
canSendMedia = YES; |
958 |
} |
959 |
self.state.canSendMedia = canSendMedia; |
960 |
self.state.messageSecurity = OTRMessageTransportSecurityPlaintext; |
961 |
[self didUpdateState]; |
962 |
}]; |
963 |
} else { |
964 |
__block OTRBuddy *buddy = nil; |
965 |
__block OTRAccount *account = nil; |
966 |
__block OTRXMPPManager *xmpp = nil; |
967 |
__block OTRMessageTransportSecurity messageSecurity = OTRMessageTransportSecurityInvalid; |
968 |
|
969 |
[self.readOnlyDatabaseConnection asyncReadWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
970 |
buddy = [self buddyWithTransaction:transaction]; |
971 |
account = [buddy accountWithTransaction:transaction]; |
972 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
973 |
messageSecurity = [buddy preferredTransportSecurityWithTransaction:transaction]; |
974 |
} completionBlock:^{ |
975 |
BOOL canSendMedia = NO; |
976 |
// Check for XEP-0363 HTTP upload |
977 |
// TODO: move this check elsewhere so it isnt dependent on refreshing crypto state |
978 |
if (xmpp != nil && xmpp.fileTransferManager.canUploadFiles) { |
979 |
canSendMedia = YES; |
980 |
} |
981 |
if (!buddy || !account || !xmpp || (messageSecurity == OTRMessageTransportSecurityInvalid)) { |
982 |
DDLogError(@"updateEncryptionState error: missing parameters"); |
983 |
} else { |
984 |
OTRKitMessageState messageState = [[OTRProtocolManager sharedInstance].encryptionManager.otrKit messageStateForUsername:buddy.username accountName:account.username protocol:account.protocolTypeString]; |
985 |
if (messageState == OTRKitMessageStateEncrypted && |
986 |
buddy.status != OTRThreadStatusOffline) { |
987 |
// If other side supports OTR, assume OTRDATA is possible |
988 |
canSendMedia = YES; |
989 |
} |
990 |
} |
991 |
self.state.canSendMedia = canSendMedia; |
992 |
self.state.messageSecurity = messageSecurity; |
993 |
[self didUpdateState]; |
994 |
}]; |
995 |
} |
996 |
} |
997 |
|
998 |
- (void)setupAccessoryButtonsWithMessageState:(OTRKitMessageState)messageState buddyStatus:(OTRThreadStatus)status textViewHasText:(BOOL)hasText |
999 |
{ |
1000 |
self.inputToolbar.contentView.rightBarButtonItem = self.sendButton; |
1001 |
self.inputToolbar.sendButtonLocation = JSQMessagesInputSendButtonLocationRight; |
1002 |
self.inputToolbar.contentView.leftBarButtonItem = nil; |
1003 |
} |
1004 |
|
1005 |
- (void)connectButtonPressed:(id)sender |
1006 |
{ |
1007 |
[self hideDropdownAnimated:YES completion:nil]; |
1008 |
__block OTRAccount *account = nil; |
1009 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1010 |
account = [self accountWithTransaction:transaction]; |
1011 |
}]; |
1012 |
|
1013 |
if (account == nil) { |
1014 |
return; |
1015 |
} |
1016 |
|
1017 |
//If we have the password then we can login with that password otherwise show login UI to enter password |
1018 |
if ([account.password length]) { |
1019 |
[[OTRProtocolManager sharedInstance] loginAccount:account userInitiated:YES]; |
1020 |
|
1021 |
} else { |
1022 |
OTRBaseLoginViewController *loginViewController = [[OTRBaseLoginViewController alloc] initWithAccount:account]; |
1023 |
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginViewController]; |
1024 |
nav.modalPresentationStyle = UIModalPresentationFormSheet; |
1025 |
[self presentViewController:nav animated:YES completion:nil]; |
1026 |
} |
1027 |
|
1028 |
|
1029 |
} |
1030 |
|
1031 |
#pragma - mark dropDown Methods |
1032 |
|
1033 |
- (void)showDropdownWithTitle:(NSString *)title buttons:(NSArray *)buttons animated:(BOOL)animated tag:(NSInteger)tag |
1034 |
{ |
1035 |
NSTimeInterval duration = 0.3; |
1036 |
if (!animated) { |
1037 |
duration = 0.0; |
1038 |
} |
1039 |
|
1040 |
self.buttonDropdownView = [[OTRButtonView alloc] initWithTitle:title buttons:buttons]; |
1041 |
self.buttonDropdownView.tag = tag; |
1042 |
|
1043 |
CGFloat height = [OTRButtonView heightForTitle:title width:self.view.bounds.size.width buttons:buttons]; |
1044 |
|
1045 |
[self.view addSubview:self.buttonDropdownView]; |
1046 |
|
1047 |
[self.buttonDropdownView autoSetDimension:ALDimensionHeight toSize:height]; |
1048 |
[self.buttonDropdownView autoPinEdgeToSuperviewEdge:ALEdgeLeading]; |
1049 |
[self.buttonDropdownView autoPinEdgeToSuperviewEdge:ALEdgeTrailing]; |
1050 |
self.buttonDropdownView.topLayoutConstraint = [self.buttonDropdownView autoPinToTopLayoutGuideOfViewController:self withInset:height*-1]; |
1051 |
|
1052 |
[self.buttonDropdownView layoutIfNeeded]; |
1053 |
|
1054 |
[UIView animateWithDuration:duration animations:^{ |
1055 |
self.buttonDropdownView.topLayoutConstraint.constant = 0.0; |
1056 |
[self.buttonDropdownView layoutIfNeeded]; |
1057 |
} completion:nil]; |
1058 |
|
1059 |
} |
1060 |
|
1061 |
- (void)hideDropdownAnimated:(BOOL)animated completion:(void (^)(void))completion |
1062 |
{ |
1063 |
if (!self.buttonDropdownView) { |
1064 |
if (completion) { |
1065 |
completion(); |
1066 |
} |
1067 |
} |
1068 |
else { |
1069 |
NSTimeInterval duration = 0.3; |
1070 |
if (!animated) { |
1071 |
duration = 0.0; |
1072 |
} |
1073 |
|
1074 |
[UIView animateWithDuration:duration animations:^{ |
1075 |
CGFloat height = self.buttonDropdownView.frame.size.height; |
1076 |
self.buttonDropdownView.topLayoutConstraint.constant = height*-1; |
1077 |
[self.buttonDropdownView layoutIfNeeded]; |
1078 |
|
1079 |
} completion:^(BOOL finished) { |
1080 |
if (finished) { |
1081 |
[self.buttonDropdownView removeFromSuperview]; |
1082 |
self.buttonDropdownView = nil; |
1083 |
} |
1084 |
|
1085 |
if (completion) { |
1086 |
completion(); |
1087 |
} |
1088 |
}]; |
1089 |
} |
1090 |
} |
1091 |
|
1092 |
- (void)saveCurrentMessageText:(NSString *)text threadKey:(NSString *)key colleciton:(NSString *)collection |
1093 |
{ |
1094 |
if (![key length] || ![collection length]) { |
1095 |
return; |
1096 |
} |
1097 |
|
1098 |
[self.readWriteDatabaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
1099 |
id <OTRThreadOwner> thread = [[transaction objectForKey:key inCollection:collection] copy]; |
1100 |
if (thread == nil) { |
1101 |
// this can happen when we've just approved a contact, then the thread key |
1102 |
// might have changed. |
1103 |
return; |
1104 |
} |
1105 |
[thread setCurrentMessageText:text]; |
1106 |
[transaction setObject:thread forKey:key inCollection:collection]; |
1107 |
|
1108 |
//Send inactive chat State |
1109 |
OTRAccount *account = [OTRAccount fetchObjectWithUniqueID:[thread threadAccountIdentifier] transaction:transaction]; |
1110 |
OTRXMPPManager *xmppManager = (OTRXMPPManager *)[[OTRProtocolManager sharedInstance] protocolForAccount:account]; |
1111 |
if (![text length]) { |
1112 |
[xmppManager sendChatState:OTRChatStateInactive withBuddyID:[thread threadIdentifier]]; |
1113 |
} |
1114 |
}]; |
1115 |
} |
1116 |
|
1117 |
//* Takes the current value out of the thread object and sets it to the text view and nils out result*/ |
1118 |
- (void)moveLastComposingTextForThreadKey:(NSString *)key colleciton:(NSString *)collection toTextView:(UITextView *)textView { |
1119 |
if (![key length] || ![collection length] || !textView) { |
1120 |
return; |
1121 |
} |
1122 |
__block id <OTRThreadOwner> thread = nil; |
1123 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1124 |
thread = [[transaction objectForKey:key inCollection:collection] copy]; |
1125 |
}]; |
1126 |
// Don't remove text you're already composing |
1127 |
NSString *oldThreadText = [thread currentMessageText]; |
1128 |
if (!textView.text.length && oldThreadText.length) { |
1129 |
textView.text = oldThreadText; |
1130 |
[self receivedTextViewChanged:textView]; |
1131 |
} |
1132 |
if (oldThreadText.length) { |
1133 |
[thread setCurrentMessageText:nil]; |
1134 |
[self.readWriteDatabaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
1135 |
[transaction setObject:thread forKey:key inCollection:collection]; |
1136 |
}]; |
1137 |
} |
1138 |
} |
1139 |
|
1140 |
- (id <OTRMessageProtocol,JSQMessageData>)messageAtIndexPath:(NSIndexPath *)indexPath |
1141 |
{ |
1142 |
// Multiple invocations with the same indexPath tend to come in groups, no need to hit the DB each time. |
1143 |
// Even though the object is cached, the row ID calculation still takes time |
1144 |
if (![indexPath isEqual:self.currentIndexPath]) { |
1145 |
self.currentIndexPath = indexPath; |
1146 |
self.currentMessage = [self.viewHandler object:indexPath]; |
1147 |
} |
1148 |
return self.currentMessage; |
1149 |
} |
1150 |
|
1151 |
/** |
1152 |
* Updates the flexible range of the DB connection. |
1153 |
* @param reset When NO, adds kOTRMessagePageSize to the range length, when YES resets the length to the kOTRMessagePageSize |
1154 |
*/ |
1155 |
- (void)updateRangeOptions:(BOOL)reset |
1156 |
{ |
1157 |
YapDatabaseViewRangeOptions *options = [self.viewHandler.mappings rangeOptionsForGroup:self.threadKey]; |
1158 |
if (reset) { |
1159 |
if (options != nil && !self.messageRangeExtended) { |
1160 |
return; |
1161 |
} |
1162 |
options = [YapDatabaseViewRangeOptions flexibleRangeWithLength:kOTRMessagePageSize |
1163 |
offset:0 |
1164 |
from:YapDatabaseViewEnd]; |
1165 |
self.messageSizeCache.countLimit = kOTRMessagePageSize; |
1166 |
self.messageRangeExtended = NO; |
1167 |
} else { |
1168 |
options = [options copyWithNewLength:options.length + kOTRMessagePageSize]; |
1169 |
self.messageSizeCache.countLimit += kOTRMessagePageSize; |
1170 |
self.messageRangeExtended = YES; |
1171 |
} |
1172 |
[self.viewHandler.mappings setRangeOptions:options forGroup:self.threadKey]; |
1173 |
|
1174 |
self.loadingMessages = YES; |
1175 |
|
1176 |
CGFloat distanceToBottom = self.collectionView.contentSize.height - self.collectionView.contentOffset.y; |
1177 |
|
1178 |
[self.collectionView reloadData]; |
1179 |
|
1180 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { |
1181 |
NSUInteger shownCount = [self.viewHandler.mappings numberOfItemsInGroup:self.threadKey]; |
1182 |
NSUInteger totalCount = [[transaction ext:OTRFilteredChatDatabaseViewExtensionName] numberOfItemsInGroup:self.threadKey]; |
1183 |
[self setShowLoadEarlierMessagesHeader:shownCount < totalCount]; |
1184 |
}]; |
1185 |
|
1186 |
if (!reset) { |
1187 |
[self.collectionView.collectionViewLayout invalidateLayout]; |
1188 |
[self.collectionView layoutSubviews]; |
1189 |
self.collectionView.contentOffset = CGPointMake(0, self.collectionView.contentSize.height - distanceToBottom); |
1190 |
} |
1191 |
|
1192 |
self.loadingMessages = NO; |
1193 |
} |
1194 |
|
1195 |
- (BOOL)showDateAtIndexPath:(NSIndexPath *)indexPath |
1196 |
{ |
1197 |
BOOL showDate = NO; |
1198 |
if (indexPath.row == 0) { |
1199 |
showDate = YES; |
1200 |
} |
1201 |
else { |
1202 |
id <OTRMessageProtocol> currentMessage = [self messageAtIndexPath:indexPath]; |
1203 |
id <OTRMessageProtocol> previousMessage = [self messageAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row-1 inSection:indexPath.section]]; |
1204 |
|
1205 |
NSTimeInterval timeDifference = [[currentMessage messageDate] timeIntervalSinceDate:[previousMessage messageDate]]; |
1206 |
if (timeDifference > kOTRMessageSentDateShowTimeInterval) { |
1207 |
showDate = YES; |
1208 |
} |
1209 |
} |
1210 |
return showDate; |
1211 |
} |
1212 |
|
1213 |
- (BOOL)showSenderDisplayNameAtIndexPath:(NSIndexPath *)indexPath { |
1214 |
id<OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1215 |
|
1216 |
if(![self.threadCollection isEqualToString:[OTRXMPPRoom collection]]) { |
1217 |
return NO; |
1218 |
} |
1219 |
|
1220 |
if ([[message senderId] isEqualToString:self.senderId]) { |
1221 |
return NO; |
1222 |
} |
1223 |
|
1224 |
if(indexPath.row -1 >= 0) { |
1225 |
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section]; |
1226 |
id<OTRMessageProtocol,JSQMessageData> previousMessage = [self messageAtIndexPath:previousIndexPath]; |
1227 |
if ([[previousMessage senderId] isEqualToString:message.senderId]) { |
1228 |
return NO; |
1229 |
} |
1230 |
} |
1231 |
|
1232 |
return YES; |
1233 |
} |
1234 |
|
1235 |
- (BOOL)isPushMessageAtIndexPath:(NSIndexPath *)indexPath { |
1236 |
id message = [self messageAtIndexPath:indexPath]; |
1237 |
return [message isKindOfClass:[PushMessage class]]; |
1238 |
} |
1239 |
|
1240 |
- (void)receivedTextViewChangedNotification:(NSNotification *)notification |
1241 |
{ |
1242 |
//Check if the text state changes from having some text to some or vice versa |
1243 |
UITextView *textView = notification.object; |
1244 |
[self receivedTextViewChanged:textView]; |
1245 |
} |
1246 |
|
1247 |
- (void)receivedTextViewChanged:(UITextView *)textView { |
1248 |
BOOL hasText = [textView.text length] > 0; |
1249 |
if(hasText != self.state.hasText) { |
1250 |
self.state.hasText = hasText; |
1251 |
[self didUpdateState]; |
1252 |
} |
1253 |
|
1254 |
//Everytime the textview has text and a notification comes through we are 'typing' otherwise we are done typing |
1255 |
if (hasText) { |
1256 |
[self isTyping]; |
1257 |
} else { |
1258 |
[self didFinishTyping]; |
1259 |
} |
1260 |
|
1261 |
return; |
1262 |
|
1263 |
} |
1264 |
|
1265 |
#pragma - mark Update UI |
1266 |
|
1267 |
- (void)didUpdateState { |
1268 |
|
1269 |
} |
1270 |
|
1271 |
- (void)isTyping { |
1272 |
|
1273 |
} |
1274 |
|
1275 |
- (void)didFinishTyping { |
1276 |
|
1277 |
} |
1278 |
|
1279 |
#pragma - mark Sending Media Items |
1280 |
|
1281 |
- (void)sendMediaItem:(OTRMediaItem *)mediaItem data:(NSData *)data message:(id<OTRMessageProtocol>)message transaction:(YapDatabaseReadWriteTransaction *)transaction |
1282 |
{ |
1283 |
id<OTRThreadOwner> thread = [self threadObjectWithTransaction:transaction]; |
1284 |
OTRXMPPManager *xmpp = [self xmppManagerWithTransaction:transaction]; |
1285 |
if (!message || !thread || !xmpp) { |
1286 |
DDLogError(@"Error sending file due to bad paramters"); |
1287 |
return; |
1288 |
} |
1289 |
if (data) { |
1290 |
thread.lastMessageIdentifier = message.messageKey; |
1291 |
[thread saveWithTransaction:transaction]; |
1292 |
} |
1293 |
// XEP-0363 |
1294 |
[xmpp.fileTransferManager sendWithMediaItem:mediaItem prefetchedData:data message:message]; |
1295 |
|
1296 |
[mediaItem touchParentMessageWithTransaction:transaction]; |
1297 |
} |
1298 |
|
1299 |
#pragma - mark Media Display Methods |
1300 |
|
1301 |
- (void)showImage:(OTRImageItem *)imageItem fromCollectionView:(JSQMessagesCollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath |
1302 |
{ |
1303 |
//FIXME: Possible for image to not be in cache? |
1304 |
UIImage *image = [OTRImages imageWithIdentifier:imageItem.uniqueId]; |
1305 |
JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init]; |
1306 |
imageInfo.image = image; |
1307 |
|
1308 |
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; |
1309 |
if ([cell isKindOfClass:[JSQMessagesCollectionViewCell class]]) { |
1310 |
UIView *cellContainterView = ((JSQMessagesCollectionViewCell *)cell).messageBubbleContainerView; |
1311 |
imageInfo.referenceRect = cellContainterView.bounds; |
1312 |
imageInfo.referenceView = cellContainterView; |
1313 |
imageInfo.referenceCornerRadius = 10; |
1314 |
} |
1315 |
|
1316 |
JTSImageViewController *imageViewer = [[JTSImageViewController alloc] |
1317 |
initWithImageInfo:imageInfo |
1318 |
mode:JTSImageViewControllerMode_Image |
1319 |
backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred]; |
1320 |
|
1321 |
[imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition]; |
1322 |
} |
1323 |
|
1324 |
- (void)showVideo:(OTRVideoItem *)videoItem fromCollectionView:(JSQMessagesCollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath |
1325 |
{ |
1326 |
if (videoItem.filename) { |
1327 |
NSURL *videoURL = [[OTRMediaServer sharedInstance] urlForMediaItem:videoItem buddyUniqueId:self.threadKey]; |
1328 |
MPMoviePlayerViewController *moviePlayerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL]; |
1329 |
[self presentViewController:moviePlayerViewController animated:YES completion:nil]; |
1330 |
} |
1331 |
} |
1332 |
|
1333 |
- (void)playOrPauseAudio:(OTRAudioItem *)audioItem fromCollectionView:(JSQMessagesCollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath |
1334 |
{ |
1335 |
NSError *error = nil; |
1336 |
if ([audioItem.uniqueId isEqualToString:self.audioPlaybackController.currentAudioItem.uniqueId]) { |
1337 |
if ([self.audioPlaybackController isPlaying]) { |
1338 |
[self.audioPlaybackController pauseCurrentlyPlaying]; |
1339 |
} |
1340 |
else { |
1341 |
[self.audioPlaybackController resumeCurrentlyPlaying]; |
1342 |
} |
1343 |
} |
1344 |
else { |
1345 |
[self.audioPlaybackController stopCurrentlyPlaying]; |
1346 |
OTRAudioControlsView *audioControls = [self audioControllsfromCollectionView:collectionView atIndexPath:indexPath]; |
1347 |
[self.audioPlaybackController attachAudioControlsView:audioControls]; |
1348 |
[self.audioPlaybackController playAudioItem:audioItem buddyUniqueId:self.threadKey error:&error]; |
1349 |
} |
1350 |
|
1351 |
if (error) { |
1352 |
DDLogError(@"Audio Playback Error: %@",error); |
1353 |
} |
1354 |
|
1355 |
} |
1356 |
|
1357 |
- (OTRAudioControlsView *)audioControllsfromCollectionView:(JSQMessagesCollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath { |
1358 |
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; |
1359 |
if ([cell isKindOfClass:[JSQMessagesCollectionViewCell class]]) { |
1360 |
UIView *mediaView = ((JSQMessagesCollectionViewCell *)cell).mediaView; |
1361 |
UIView *view = [mediaView viewWithTag:kOTRAudioControlsViewTag]; |
1362 |
if ([view isKindOfClass:[OTRAudioControlsView class]]) { |
1363 |
return (OTRAudioControlsView *)view; |
1364 |
} |
1365 |
} |
1366 |
|
1367 |
return nil; |
1368 |
} |
1369 |
|
1370 |
#pragma MARK - OTRMessagesCollectionViewFlowLayoutSizeProtocol methods |
1371 |
|
1372 |
- (BOOL)hasBubbleSizeForCellAtIndexPath:(NSIndexPath *)indexPath { |
1373 |
return ![self isPushMessageAtIndexPath:indexPath]; |
1374 |
} |
1375 |
|
1376 |
#pragma mark - JSQMessagesViewController method overrides |
1377 |
|
1378 |
- (UICollectionViewCell *)collectionView:(JSQMessagesCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath |
1379 |
{ |
1380 |
JSQMessagesCollectionViewCell *cell = (JSQMessagesCollectionViewCell *)[super collectionView:collectionView cellForItemAtIndexPath:indexPath]; |
1381 |
|
1382 |
//Fixes times when there needs to be two lines (date & knock sent) and doesn't seem to affect one line instances |
1383 |
cell.cellTopLabel.numberOfLines = 0; |
1384 |
|
1385 |
id <OTRMessageProtocol>message = [self messageAtIndexPath:indexPath]; |
1386 |
|
1387 |
__block OTRXMPPAccount *account = nil; |
1388 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1389 |
account = (OTRXMPPAccount*)[self accountWithTransaction:transaction]; |
1390 |
}]; |
1391 |
|
1392 |
UIColor *textColor = nil; |
1393 |
if ([message isMessageIncoming]) { |
1394 |
textColor = [UIColor blackColor]; |
1395 |
} |
1396 |
else { |
1397 |
textColor = [UIColor whiteColor]; |
1398 |
} |
1399 |
if (cell.textView != nil) |
1400 |
cell.textView.textColor = textColor; |
1401 |
|
1402 |
// Do not allow clickable links for Tor accounts to prevent information leakage |
1403 |
// Could be better to move this information to the message object to not need to do a database read. |
1404 |
if ([account isKindOfClass:[OTRXMPPTorAccount class]]) { |
1405 |
cell.textView.dataDetectorTypes = UIDataDetectorTypeNone; |
1406 |
} |
1407 |
else { |
1408 |
cell.textView.dataDetectorTypes = UIDataDetectorTypeLink; |
1409 |
cell.textView.linkTextAttributes = @{ NSForegroundColorAttributeName : textColor, |
1410 |
NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) }; |
1411 |
} |
1412 |
|
1413 |
if ([[message messageMediaItemKey] isEqualToString:self.audioPlaybackController.currentAudioItem.uniqueId]) { |
1414 |
UIView *view = [cell.mediaView viewWithTag:kOTRAudioControlsViewTag]; |
1415 |
if ([view isKindOfClass:[OTRAudioControlsView class]]) { |
1416 |
[self.audioPlaybackController attachAudioControlsView:(OTRAudioControlsView *)view]; |
1417 |
} |
1418 |
} |
1419 |
|
1420 |
// Needed for link interaction |
1421 |
cell.textView.delegate = self; |
1422 |
return cell; |
1423 |
} |
1424 |
|
1425 |
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender |
1426 |
{ |
1427 |
if (action == @selector(delete:)) { |
1428 |
return YES; |
1429 |
} |
1430 |
|
1431 |
return [super collectionView:collectionView canPerformAction:action forItemAtIndexPath:indexPath withSender:sender]; |
1432 |
} |
1433 |
|
1434 |
- (void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text senderId:(NSString *)senderId senderDisplayName:(NSString *)senderDisplayName date:(NSDate *)date |
1435 |
{ |
1436 |
if(!text.length) { |
1437 |
return; |
1438 |
} |
1439 |
|
1440 |
self.navigationController.providesPresentationContextTransitionStyle = YES; |
1441 |
self.navigationController.definesPresentationContext = YES; |
1442 |
|
1443 |
//0. Clear out message text immediately |
1444 |
// This is to prevent the scenario where multiple messages get sent because the message text isn't cleared out |
1445 |
// due to aggregated touch events during UI pauses. |
1446 |
// A side effect is that sent messages may not appear in the UI immediately |
1447 |
[self finishSendingMessage]; |
1448 |
|
1449 |
__block id<OTRMessageProtocol> message = nil; |
1450 |
__block OTRXMPPManager *xmpp = nil; |
1451 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1452 |
id<OTRThreadOwner> thread = [self threadObjectWithTransaction:transaction]; |
1453 |
message = [thread outgoingMessageWithText:text transaction:transaction]; |
1454 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
1455 |
}]; |
1456 |
if (!message || !xmpp) { return; } |
1457 |
[xmpp enqueueMessage:message]; |
1458 |
} |
1459 |
|
1460 |
- (void)didPressAccessoryButton:(UIButton *)sender |
1461 |
{ |
1462 |
if ([sender isEqual:self.cameraButton]) { |
1463 |
[self.attachmentPicker showAlertControllerFromSourceView:sender withCompletion:nil]; |
1464 |
} |
1465 |
} |
1466 |
|
1467 |
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender |
1468 |
{ |
1469 |
if (action == @selector(delete:)) { |
1470 |
[self deleteMessageAtIndexPath:indexPath]; |
1471 |
} |
1472 |
else { |
1473 |
[super collectionView:collectionView performAction:action forItemAtIndexPath:indexPath withSender:sender]; |
1474 |
} |
1475 |
} |
1476 |
|
1477 |
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath |
1478 |
{ |
1479 |
id <OTRMessageProtocol, JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1480 |
|
1481 |
NSNumber *key = @(message.messageHash); |
1482 |
NSValue *sizeValue = [self.messageSizeCache objectForKey:key]; |
1483 |
if (sizeValue != nil) { |
1484 |
return [sizeValue CGSizeValue]; |
1485 |
} |
1486 |
|
1487 |
// Although JSQMessagesBubblesSizeCalculator has its own cache, its size is fixed and quite small, so it quickly chokes on scrolling into the past |
1488 |
CGSize size = [super collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:indexPath]; |
1489 |
// The height of the first cell might change: on loading additional messages the date label most likely will disappear |
1490 |
if (indexPath.row > 0) { |
1491 |
[self.messageSizeCache setObject:[NSValue valueWithCGSize:size] forKey:key]; |
1492 |
} |
1493 |
return size; |
1494 |
} |
1495 |
|
1496 |
#pragma - mark UIPopoverPresentationControllerDelegate Methods |
1497 |
|
1498 |
- (void)prepareForPopoverPresentation:(UIPopoverPresentationController *)popoverPresentationController { |
1499 |
// Without setting this, there will be a crash on iPad |
1500 |
// This delegate is set in the OTRAttachmentPicker |
1501 |
popoverPresentationController.sourceView = self.cameraButton; |
1502 |
} |
1503 |
|
1504 |
- (void)sendPhoto:(UIImage *)photo asJPEG:(BOOL)asJPEG shouldResize:(BOOL)shouldResize { |
1505 |
NSParameterAssert(photo); |
1506 |
if (!photo) { return; } |
1507 |
__block OTRXMPPManager *xmpp = nil; |
1508 |
__block id<OTRThreadOwner> thread = nil; |
1509 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1510 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
1511 |
thread = [self threadObjectWithTransaction:transaction]; |
1512 |
}]; |
1513 |
NSParameterAssert(xmpp); |
1514 |
NSParameterAssert(thread); |
1515 |
if (!xmpp || !thread) { return; } |
1516 |
|
1517 |
[xmpp.fileTransferManager sendWithImage:photo thread:thread]; |
1518 |
} |
1519 |
|
1520 |
#pragma - mark OTRAttachmentPickerDelegate Methods |
1521 |
|
1522 |
- (void)attachmentPicker:(OTRAttachmentPicker *)attachmentPicker gotPhoto:(UIImage *)photo withInfo:(NSDictionary *)info |
1523 |
{ |
1524 |
[self sendPhoto:photo asJPEG:YES shouldResize:YES]; |
1525 |
} |
1526 |
|
1527 |
- (void)attachmentPicker:(OTRAttachmentPicker *)attachmentPicker gotVideoURL:(NSURL *)videoURL |
1528 |
{ |
1529 |
if (!videoURL) { return; } |
1530 |
__block OTRXMPPManager *xmpp = nil; |
1531 |
__block id<OTRThreadOwner> thread = nil; |
1532 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1533 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
1534 |
thread = [self threadObjectWithTransaction:transaction]; |
1535 |
}]; |
1536 |
NSParameterAssert(xmpp); |
1537 |
NSParameterAssert(thread); |
1538 |
if (!xmpp || !thread) { return; } |
1539 |
|
1540 |
[xmpp.fileTransferManager sendWithVideoURL:videoURL thread:thread]; |
1541 |
} |
1542 |
|
1543 |
- (NSArray <NSString *>*)attachmentPicker:(OTRAttachmentPicker *)attachmentPicker preferredMediaTypesForSource:(UIImagePickerControllerSourceType)source |
1544 |
{ |
1545 |
return @[(NSString*)kUTTypeImage]; |
1546 |
} |
1547 |
|
1548 |
- (void)sendAudioFileURL:(NSURL *)url |
1549 |
{ |
1550 |
if (!url) { return; } |
1551 |
__block OTRXMPPManager *xmpp = nil; |
1552 |
__block id<OTRThreadOwner> thread = nil; |
1553 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1554 |
xmpp = [self xmppManagerWithTransaction:transaction]; |
1555 |
thread = [self threadObjectWithTransaction:transaction]; |
1556 |
}]; |
1557 |
NSParameterAssert(xmpp); |
1558 |
NSParameterAssert(thread); |
1559 |
if (!xmpp || !thread) { return; } |
1560 |
|
1561 |
[xmpp.fileTransferManager sendWithAudioURL:url thread:thread]; |
1562 |
} |
1563 |
|
1564 |
- (void)sendImageFilePath:(NSString *)filePath asJPEG:(BOOL)asJPEG shouldResize:(BOOL)shouldResize |
1565 |
{ |
1566 |
[self sendPhoto:[UIImage imageWithContentsOfFile:filePath] asJPEG:asJPEG shouldResize:shouldResize]; |
1567 |
} |
1568 |
|
1569 |
|
1570 |
#pragma - mark UIScrollViewDelegate Methods |
1571 |
|
1572 |
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView |
1573 |
{ |
1574 |
[self hideDropdownAnimated:YES completion:nil]; |
1575 |
} |
1576 |
|
1577 |
- (void)scrollViewDidScroll:(UIScrollView *)scrollView |
1578 |
{ |
1579 |
if (!self.loadingMessages) { |
1580 |
UIEdgeInsets insets = scrollView.contentInset; |
1581 |
CGFloat highestOffset = -insets.top; |
1582 |
CGFloat lowestOffset = scrollView.contentSize.height - scrollView.frame.size.height + insets.bottom; |
1583 |
CGFloat pos = scrollView.contentOffset.y; |
1584 |
|
1585 |
if (self.showLoadEarlierMessagesHeader && (pos == highestOffset || (pos < 0 && (scrollView.isDecelerating || scrollView.isDragging)))) { |
1586 |
[self updateRangeOptions:NO]; |
1587 |
} else if (pos == lowestOffset) { |
1588 |
[self updateRangeOptions:YES]; |
1589 |
} |
1590 |
} |
1591 |
} |
1592 |
|
1593 |
#pragma mark - UICollectionView DataSource |
1594 |
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section |
1595 |
{ |
1596 |
NSInteger numberOfMessages = [self.viewHandler.mappings numberOfItemsInSection:section]; |
1597 |
return numberOfMessages; |
1598 |
} |
1599 |
|
1600 |
#pragma - mark JSQMessagesCollectionViewDataSource Methods |
1601 |
|
1602 |
- (NSString *)senderDisplayName |
1603 |
{ |
1604 |
__block OTRAccount *account = nil; |
1605 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1606 |
account = [self accountWithTransaction:transaction]; |
1607 |
}]; |
1608 |
|
1609 |
NSString *senderDisplayName = @""; |
1610 |
if (account) { |
1611 |
if ([account.displayName length]) { |
1612 |
senderDisplayName = account.displayName; |
1613 |
} else { |
1614 |
senderDisplayName = account.username; |
1615 |
} |
1616 |
} |
1617 |
|
1618 |
return senderDisplayName; |
1619 |
} |
1620 |
|
1621 |
- (id<JSQMessageData>)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath |
1622 |
{ |
1623 |
return (id <JSQMessageData>)[self messageAtIndexPath:indexPath]; |
1624 |
} |
1625 |
|
1626 |
- (id<JSQMessageBubbleImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView messageBubbleImageDataForItemAtIndexPath:(NSIndexPath *)indexPath |
1627 |
{ |
1628 |
id <OTRMessageProtocol> message = [self messageAtIndexPath:indexPath]; |
1629 |
JSQMessagesBubbleImage *image = nil; |
1630 |
if ([message isMessageIncoming]) { |
1631 |
image = self.incomingBubbleImage; |
1632 |
} |
1633 |
else { |
1634 |
image = self.outgoingBubbleImage; |
1635 |
} |
1636 |
return image; |
1637 |
} |
1638 |
|
1639 |
- (id <JSQMessageAvatarImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView avatarImageDataForItemAtIndexPath:(NSIndexPath *)indexPath |
1640 |
{ |
1641 |
id <OTRMessageProtocol> message = [self messageAtIndexPath:indexPath]; |
1642 |
if ([message isKindOfClass:[PushMessage class]]) { |
1643 |
return nil; |
1644 |
} |
1645 |
|
1646 |
NSError *messageError = [message messageError]; |
1647 |
if ((messageError && !messageError.isAutomaticDownloadError) || |
1648 |
![self isMessageTrusted:message]) { |
1649 |
return [self warningAvatarImage]; |
1650 |
} |
1651 |
|
1652 |
if ([message isKindOfClass:[OTRXMPPRoomMessage class]]) { |
1653 |
OTRXMPPRoomMessage *roomMessage = (OTRXMPPRoomMessage *)message; |
1654 |
__block OTRXMPPRoomOccupant *roomOccupant = nil; |
1655 |
__block OTRXMPPBuddy *roomOccupantBuddy = nil; |
1656 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { |
1657 |
roomOccupant = [OTRXMPPRoomOccupant occupantWithJid:[XMPPJID jidWithString:roomMessage.senderJID] realJID:[XMPPJID jidWithString:roomMessage.senderJID] roomJID:[XMPPJID jidWithString:roomMessage.roomJID] accountId:[self accountWithTransaction:transaction].uniqueId createIfNeeded:NO transaction:transaction]; |
1658 |
if (roomOccupant != nil) { |
1659 |
roomOccupantBuddy = [roomOccupant buddyWith:transaction]; |
1660 |
} |
1661 |
}]; |
1662 |
UIImage *avatarImage = nil; |
1663 |
if (roomOccupant) { |
1664 |
if (roomOccupantBuddy != nil) { |
1665 |
avatarImage = [roomOccupantBuddy avatarImage]; |
1666 |
} |
1667 |
if (!avatarImage) { |
1668 |
avatarImage = [roomOccupant avatarImage]; |
1669 |
} |
1670 |
} else { |
1671 |
avatarImage = [OTRImages avatarImageWithUsername:[[XMPPJID jidWithString:roomMessage.senderJID] resource]]; |
1672 |
} |
1673 |
if (avatarImage) { |
1674 |
NSUInteger diameter = MIN(avatarImage.size.width, avatarImage.size.height); |
1675 |
return [JSQMessagesAvatarImageFactory avatarImageWithImage:avatarImage diameter:diameter]; |
1676 |
} |
1677 |
} |
1678 |
|
1679 |
if ([message isMessageIncoming]) { |
1680 |
return [self buddyAvatarImage]; |
1681 |
} |
1682 |
|
1683 |
return [self accountAvatarImage]; |
1684 |
} |
1685 |
|
1686 |
- (JSQMessagesAvatarImage *)createAvatarImage:(UIImage *(^)(YapDatabaseReadTransaction *))getImage |
1687 |
{ |
1688 |
__block UIImage *avatarImage; |
1689 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *_Nonnull transaction) { |
1690 |
avatarImage = getImage(transaction); |
1691 |
}]; |
1692 |
if (avatarImage != nil) { |
1693 |
NSUInteger diameter = (NSUInteger) MIN(avatarImage.size.width, avatarImage.size.height); |
1694 |
return [JSQMessagesAvatarImageFactory avatarImageWithImage:avatarImage diameter:diameter]; |
1695 |
} |
1696 |
return nil; |
1697 |
} |
1698 |
|
1699 |
- (JSQMessagesAvatarImage *)warningAvatarImage |
1700 |
{ |
1701 |
if (_warningAvatarImage == nil) { |
1702 |
_warningAvatarImage = [self createAvatarImage:^(YapDatabaseReadTransaction *transaction) { |
1703 |
return [OTRImages circleWarningWithColor:[OTRColors warnColor]]; |
1704 |
}]; |
1705 |
} |
1706 |
return _warningAvatarImage; |
1707 |
} |
1708 |
|
1709 |
- (JSQMessagesAvatarImage *)accountAvatarImage |
1710 |
{ |
1711 |
if (_accountAvatarImage == nil) { |
1712 |
_accountAvatarImage = [self createAvatarImage:^(YapDatabaseReadTransaction *transaction) { |
1713 |
return [[self accountWithTransaction:transaction] avatarImage]; |
1714 |
}]; |
1715 |
} |
1716 |
return _accountAvatarImage; |
1717 |
} |
1718 |
|
1719 |
- (JSQMessagesAvatarImage *)buddyAvatarImage |
1720 |
{ |
1721 |
if (_buddyAvatarImage == nil) { |
1722 |
_buddyAvatarImage = [self createAvatarImage:^(YapDatabaseReadTransaction *transaction) { |
1723 |
return [[self buddyWithTransaction:transaction] avatarImage]; |
1724 |
}]; |
1725 |
} |
1726 |
return _buddyAvatarImage; |
1727 |
} |
1728 |
|
1729 |
////// Optional ////// |
1730 |
|
1731 |
- (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath |
1732 |
{ |
1733 |
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] init]; |
1734 |
|
1735 |
if ([self showDateAtIndexPath:indexPath]) { |
1736 |
id <OTRMessageProtocol> message = [self messageAtIndexPath:indexPath]; |
1737 |
NSDate *date = [message messageDate]; |
1738 |
if (date != nil) { |
1739 |
[text appendAttributedString: [[JSQMessagesTimestampFormatter sharedFormatter] attributedTimestampForDate:date]]; |
1740 |
} |
1741 |
} |
1742 |
|
1743 |
if ([self isPushMessageAtIndexPath:indexPath]) { |
1744 |
JSQMessagesTimestampFormatter *formatter = [JSQMessagesTimestampFormatter sharedFormatter]; |
1745 |
NSString *knockString = KNOCK_SENT_STRING(); |
1746 |
//Add new line if there is already a date string |
1747 |
if ([text length] > 0) { |
1748 |
knockString = [@"\n" stringByAppendingString:knockString]; |
1749 |
} |
1750 |
[text appendAttributedString:[[NSAttributedString alloc] initWithString:knockString attributes:formatter.dateTextAttributes]]; |
1751 |
} |
1752 |
|
1753 |
return text; |
1754 |
} |
1755 |
|
1756 |
|
1757 |
- (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForMessageBubbleTopLabelAtIndexPath:(NSIndexPath *)indexPath |
1758 |
{ |
1759 |
if ([self showSenderDisplayNameAtIndexPath:indexPath]) { |
1760 |
id<OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1761 |
|
1762 |
__block NSString *displayName = nil; |
1763 |
if ([message isKindOfClass:[OTRXMPPRoomMessage class]]) { |
1764 |
OTRXMPPRoomMessage *roomMessage = (OTRXMPPRoomMessage *)message; |
1765 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
1766 |
OTRXMPPRoomOccupant *occupant = [OTRXMPPRoomOccupant occupantWithJid:[XMPPJID jidWithString:roomMessage.senderJID] realJID:[XMPPJID jidWithString:roomMessage.senderJID] roomJID:[XMPPJID jidWithString:roomMessage.roomJID] accountId:[self accountWithTransaction:transaction].uniqueId createIfNeeded:NO transaction:transaction]; |
1767 |
if (occupant) { |
1768 |
OTRXMPPBuddy *buddy = [occupant buddyWith:transaction]; |
1769 |
if (buddy) { |
1770 |
displayName = [buddy displayName]; |
1771 |
} else { |
1772 |
displayName = [[XMPPJID jidWithString:occupant.jid] resource]; |
1773 |
} |
1774 |
} |
1775 |
}]; |
1776 |
} |
1777 |
if (!displayName) { |
1778 |
displayName = [message senderDisplayName]; |
1779 |
} |
1780 |
return [[NSAttributedString alloc] initWithString:displayName]; |
1781 |
} |
1782 |
|
1783 |
return nil; |
1784 |
} |
1785 |
|
1786 |
/** Currently uses clock for queued, and checkmark for delivered. */ |
1787 |
- (nullable NSAttributedString*) deliveryStatusStringForMessage:(nonnull id<OTRMessageProtocol>)message { |
1788 |
if (!message) { return nil; } |
1789 |
// Only applies to outgoing messages |
1790 |
if ([message isMessageIncoming]) { |
1791 |
return nil; |
1792 |
} |
1793 |
NSString *deliveryStatusString = nil; |
1794 |
if(message.isMessageSent == NO && ![message messageMediaItemKey]) { |
1795 |
// Waiting to send message. This message is in the queue. |
1796 |
deliveryStatusString = [NSString fa_stringForFontAwesomeIcon:FAClockO]; |
1797 |
} else if (message.isMessageDelivered){ |
1798 |
deliveryStatusString = [NSString stringWithFormat:@"%@ ",[NSString fa_stringForFontAwesomeIcon:FACheck]]; |
1799 |
} |
1800 |
if (deliveryStatusString != nil) { |
1801 |
UIFont *font = [UIFont fontWithName:kFontAwesomeFont size:12]; |
1802 |
if (!font) { |
1803 |
font = [UIFont systemFontOfSize:12]; |
1804 |
} |
1805 |
return [[NSAttributedString alloc] initWithString:deliveryStatusString attributes:@{NSFontAttributeName: font}]; |
1806 |
} |
1807 |
return nil; |
1808 |
} |
1809 |
|
1810 |
- (nullable NSAttributedString *) encryptionStatusStringForMessage:(nonnull id<OTRMessageProtocol>)message { |
1811 |
NSString *lockString = nil; |
1812 |
if (message.messageSecurity == OTRMessageTransportSecurityOTR) { |
1813 |
lockString = [NSString stringWithFormat:@"%@ OTR ",[NSString fa_stringForFontAwesomeIcon:FALock]]; |
1814 |
} else if (message.messageSecurity == OTRMessageTransportSecurityOMEMO) { |
1815 |
lockString = [NSString stringWithFormat:@"%@ OMEMO ",[NSString fa_stringForFontAwesomeIcon:FALock]]; |
1816 |
} |
1817 |
else { |
1818 |
lockString = [NSString fa_stringForFontAwesomeIcon:FAUnlock]; |
1819 |
} |
1820 |
UIFont *font = [UIFont fontWithName:kFontAwesomeFont size:12]; |
1821 |
if (!font) { |
1822 |
font = [UIFont systemFontOfSize:12]; |
1823 |
} |
1824 |
return [[NSAttributedString alloc] initWithString:lockString attributes:@{NSFontAttributeName: font}]; |
1825 |
} |
1826 |
|
1827 |
|
1828 |
- (NSAttributedString *)collectionView:(JSQMessagesCollectionView *)collectionView attributedTextForCellBottomLabelAtIndexPath:(NSIndexPath *)indexPath |
1829 |
{ |
1830 |
id <OTRMessageProtocol> message = [self messageAtIndexPath:indexPath]; |
1831 |
if (!message) { |
1832 |
return [[NSAttributedString alloc] initWithString:@""]; |
1833 |
} |
1834 |
|
1835 |
UIFont *font = [UIFont fontWithName:kFontAwesomeFont size:12]; |
1836 |
if (!font) { |
1837 |
font = [UIFont systemFontOfSize:12]; |
1838 |
} |
1839 |
NSDictionary *iconAttributes = @{NSFontAttributeName: font}; |
1840 |
NSDictionary *lockAttributes = [iconAttributes copy]; |
1841 |
|
1842 |
////// Lock Icon ////// |
1843 |
NSAttributedString *lockString = [self encryptionStatusStringForMessage:message]; |
1844 |
if (!lockString) { |
1845 |
lockString = [[NSAttributedString alloc] initWithString:@""]; |
1846 |
} |
1847 |
NSMutableAttributedString *attributedString = [lockString mutableCopy]; |
1848 |
|
1849 |
BOOL trusted = YES; |
1850 |
if([message isKindOfClass:[OTRBaseMessage class]]) { |
1851 |
trusted = [self isMessageTrusted:message]; |
1852 |
}; |
1853 |
|
1854 |
if (!trusted) { |
1855 |
NSMutableDictionary *mutableCopy = [lockAttributes mutableCopy]; |
1856 |
[mutableCopy setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName]; |
1857 |
lockAttributes = mutableCopy; |
1858 |
} |
1859 |
|
1860 |
NSAttributedString *deliveryString = [self deliveryStatusStringForMessage:message]; |
1861 |
if (deliveryString) { |
1862 |
[attributedString appendAttributedString:deliveryString]; |
1863 |
} |
1864 |
|
1865 |
if([[message messageMediaItemKey] length] > 0) { |
1866 |
|
1867 |
__block OTRMediaItem *mediaItem = nil; |
1868 |
//Get the media item |
1869 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) { |
1870 |
mediaItem = [OTRMediaItem fetchObjectWithUniqueID:[message messageMediaItemKey] transaction:transaction]; |
1871 |
}]; |
1872 |
if (!mediaItem) { |
1873 |
return attributedString; |
1874 |
} |
1875 |
|
1876 |
float percentProgress = mediaItem.transferProgress * 100; |
1877 |
|
1878 |
NSString *progressString = nil; |
1879 |
NSUInteger insertIndex = 0; |
1880 |
|
1881 |
if (mediaItem.isIncoming && mediaItem.transferProgress < 1) { |
1882 |
if (message.messageError) { |
1883 |
progressString = [NSString stringWithFormat:@"%@ ",WAITING_STRING()]; |
1884 |
} else { |
1885 |
progressString = [NSString stringWithFormat:@" %@ %.0f%%",INCOMING_STRING(),percentProgress]; |
1886 |
} |
1887 |
insertIndex = [attributedString length]; |
1888 |
} else if (!mediaItem.isIncoming && mediaItem.transferProgress < 1) { |
1889 |
if(percentProgress > 0) { |
1890 |
progressString = [NSString stringWithFormat:@"%@ %.0f%% ",SENDING_STRING(),percentProgress]; |
1891 |
} else { |
1892 |
progressString = [NSString stringWithFormat:@"%@ ",WAITING_STRING()]; |
1893 |
} |
1894 |
} |
1895 |
|
1896 |
if ([progressString length]) { |
1897 |
UIFont *font = [UIFont systemFontOfSize:12]; |
1898 |
[attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:progressString attributes:@{NSFontAttributeName: font}] atIndex:insertIndex]; |
1899 |
} |
1900 |
} |
1901 |
|
1902 |
return attributedString; |
1903 |
} |
1904 |
|
1905 |
|
1906 |
#pragma - mark JSQMessagesCollectionViewDelegateFlowLayout Methods |
1907 |
|
1908 |
- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView |
1909 |
layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout |
1910 |
heightForCellTopLabelAtIndexPath:(NSIndexPath *)indexPath |
1911 |
{ |
1912 |
CGFloat height = 0.0f; |
1913 |
if ([self showDateAtIndexPath:indexPath]) { |
1914 |
height += kJSQMessagesCollectionViewCellLabelHeightDefault; |
1915 |
} |
1916 |
|
1917 |
if ([self isPushMessageAtIndexPath:indexPath]) { |
1918 |
height += kJSQMessagesCollectionViewCellLabelHeightDefault; |
1919 |
} |
1920 |
return height; |
1921 |
} |
1922 |
|
1923 |
- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView |
1924 |
layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout |
1925 |
heightForMessageBubbleTopLabelAtIndexPath:(NSIndexPath *)indexPath |
1926 |
{ |
1927 |
if ([self showSenderDisplayNameAtIndexPath:indexPath]) { |
1928 |
return kJSQMessagesCollectionViewCellLabelHeightDefault; |
1929 |
} |
1930 |
return 0.0f; |
1931 |
} |
1932 |
|
1933 |
- (CGFloat)collectionView:(JSQMessagesCollectionView *)collectionView |
1934 |
layout:(JSQMessagesCollectionViewFlowLayout *)collectionViewLayout |
1935 |
heightForCellBottomLabelAtIndexPath:(NSIndexPath *)indexPath |
1936 |
{ |
1937 |
CGFloat height = kJSQMessagesCollectionViewCellLabelHeightDefault; |
1938 |
if ([self isPushMessageAtIndexPath:indexPath]) { |
1939 |
height = 0.0f; |
1940 |
} |
1941 |
return height; |
1942 |
} |
1943 |
|
1944 |
- (void)deleteMessageAtIndexPath:(NSIndexPath *)indexPath |
1945 |
{ |
1946 |
__block id <OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1947 |
__weak __typeof__(self) weakSelf = self; |
1948 |
[self.readWriteDatabaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { |
1949 |
__typeof__(self) strongSelf = weakSelf; |
1950 |
[transaction removeObjectForKey:[message messageKey] inCollection:[message messageCollection]]; |
1951 |
//Update Last message date for sorting and grouping |
1952 |
OTRBuddy *buddy = [[strongSelf buddyWithTransaction:transaction] copy]; |
1953 |
buddy.lastMessageId = nil; |
1954 |
[buddy saveWithTransaction:transaction]; |
1955 |
}]; |
1956 |
} |
1957 |
|
1958 |
- (void)collectionView:(JSQMessagesCollectionView *)collectionView didTapAvatarImageView:(UIImageView *)avatarImageView atIndexPath:(NSIndexPath *)indexPath |
1959 |
{ |
1960 |
id <OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1961 |
[self didTapAvatar:message sender:avatarImageView]; |
1962 |
} |
1963 |
|
1964 |
- (void)collectionView:(JSQMessagesCollectionView *)collectionView didTapMessageBubbleAtIndexPath:(NSIndexPath *)indexPath |
1965 |
{ |
1966 |
id <OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
1967 |
if (!message.isMediaMessage) { |
1968 |
return; |
1969 |
} |
1970 |
__block OTRMediaItem *item = nil; |
1971 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) { |
1972 |
item = [OTRMediaItem mediaItemForMessage:message transaction:transaction]; |
1973 |
}]; |
1974 |
if (!item) { return; } |
1975 |
if (item.transferProgress != 1 && item.isIncoming) { |
1976 |
return; |
1977 |
} |
1978 |
|
1979 |
if ([item isKindOfClass:[OTRImageItem class]]) { |
1980 |
[self showImage:(OTRImageItem *)item fromCollectionView:collectionView atIndexPath:indexPath]; |
1981 |
} |
1982 |
else if ([item isKindOfClass:[OTRVideoItem class]]) { |
1983 |
[self showVideo:(OTRVideoItem *)item fromCollectionView:collectionView atIndexPath:indexPath]; |
1984 |
} |
1985 |
else if ([item isKindOfClass:[OTRAudioItem class]]) { |
1986 |
[self playOrPauseAudio:(OTRAudioItem *)item fromCollectionView:collectionView atIndexPath:indexPath]; |
1987 |
} else if ([message conformsToProtocol:@protocol(OTRDownloadMessage)]) { |
1988 |
id<OTRDownloadMessage> download = (id<OTRDownloadMessage>)message; |
1989 |
// Janky hack to open URL for now |
1990 |
NSArray<UIAlertAction*> *actions = [UIAlertAction actionsForMediaMessage:download sourceView:self.view viewController:self]; |
1991 |
UIAlertController *alert = [UIAlertController alertControllerWithTitle:message.text message:nil preferredStyle:UIAlertControllerStyleActionSheet]; |
1992 |
[actions enumerateObjectsUsingBlock:^(UIAlertAction * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { |
1993 |
[alert addAction:obj]; |
1994 |
}]; |
1995 |
[alert addAction:[self cancleAction]]; |
1996 |
|
1997 |
// Get the anchor |
1998 |
alert.popoverPresentationController.sourceView = self.view; |
1999 |
alert.popoverPresentationController.sourceRect = self.view.bounds; |
2000 |
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; |
2001 |
if ([cell isKindOfClass:[JSQMessagesCollectionViewCell class]]) { |
2002 |
UIView *cellContainterView = ((JSQMessagesCollectionViewCell *)cell).messageBubbleContainerView; |
2003 |
alert.popoverPresentationController.sourceRect = cellContainterView.bounds; |
2004 |
alert.popoverPresentationController.sourceView = cellContainterView; |
2005 |
} |
2006 |
|
2007 |
[self presentViewController:alert animated:YES completion:nil]; |
2008 |
} |
2009 |
} |
2010 |
|
2011 |
#pragma - mark database view delegate |
2012 |
|
2013 |
- (void)didSetupMappings:(OTRYapViewHandler *)handler |
2014 |
{ |
2015 |
// The databse view is setup now so refresh from there |
2016 |
[self updateViewWithKey:self.threadKey collection:self.threadCollection]; |
2017 |
[self updateRangeOptions:YES]; |
2018 |
[self.collectionView reloadData]; |
2019 |
} |
2020 |
|
2021 |
- (void)didReceiveChanges:(OTRYapViewHandler *)handler key:(NSString *)key collection:(NSString *)collection |
2022 |
{ |
2023 |
[self updateViewWithKey:key collection:collection]; |
2024 |
} |
2025 |
|
2026 |
- (void)didReceiveChanges:(OTRYapViewHandler *)handler sectionChanges:(NSArray<YapDatabaseViewSectionChange *> *)sectionChanges rowChanges:(NSArray<YapDatabaseViewRowChange *> *)rowChanges |
2027 |
{ |
2028 |
if (!rowChanges.count) { |
2029 |
return; |
2030 |
} |
2031 |
|
2032 |
// Important to clear our "one message cache" here, since things may have changed. |
2033 |
self.currentIndexPath = nil; |
2034 |
|
2035 |
NSUInteger collectionViewNumberOfItems = [self.collectionView numberOfItemsInSection:0]; |
2036 |
NSUInteger numberMappingsItems = [self.viewHandler.mappings numberOfItemsInSection:0]; |
2037 |
|
2038 |
[self.collectionView performBatchUpdates:^{ |
2039 |
|
2040 |
for (YapDatabaseViewRowChange *rowChange in rowChanges) |
2041 |
{ |
2042 |
switch (rowChange.type) |
2043 |
{ |
2044 |
case YapDatabaseViewChangeDelete : |
2045 |
{ |
2046 |
[self.collectionView deleteItemsAtIndexPaths:@[rowChange.indexPath]]; |
2047 |
break; |
2048 |
} |
2049 |
case YapDatabaseViewChangeInsert : |
2050 |
{ |
2051 |
[self.collectionView insertItemsAtIndexPaths:@[ rowChange.newIndexPath ]]; |
2052 |
break; |
2053 |
} |
2054 |
case YapDatabaseViewChangeMove : |
2055 |
{ |
2056 |
[self.collectionView moveItemAtIndexPath:rowChange.indexPath toIndexPath:rowChange.newIndexPath]; |
2057 |
break; |
2058 |
} |
2059 |
case YapDatabaseViewChangeUpdate : |
2060 |
{ |
2061 |
// Update could be e.g. when we are done auto-loading a link. We |
2062 |
// need to reset the stored size of this item, so the image/message |
2063 |
// will get the correct bubble height. |
2064 |
id <JSQMessageData> message = [self messageAtIndexPath:rowChange.indexPath]; |
2065 |
[self.collectionView.collectionViewLayout.bubbleSizeCalculator resetBubbleSizeCacheForMessageData:message]; |
2066 |
[self.messageSizeCache removeObjectForKey:@(message.messageHash)]; |
2067 |
[self.collectionView reloadItemsAtIndexPaths:@[ rowChange.indexPath]]; |
2068 |
break; |
2069 |
} |
2070 |
} |
2071 |
} |
2072 |
} completion:^(BOOL finished){ |
2073 |
if(numberMappingsItems > collectionViewNumberOfItems && numberMappingsItems > 0) { |
2074 |
//Inserted new item, probably at the end |
2075 |
//Get last message and test if isIncoming |
2076 |
NSIndexPath *lastMessageIndexPath = [NSIndexPath indexPathForRow:numberMappingsItems - 1 inSection:0]; |
2077 |
id <OTRMessageProtocol>lastMessage = [self messageAtIndexPath:lastMessageIndexPath]; |
2078 |
if ([lastMessage isMessageIncoming]) { |
2079 |
[self finishReceivingMessage]; |
2080 |
} else { |
2081 |
// We can't use finishSendingMessage here because it might |
2082 |
// accidentally clear out unsent message text |
2083 |
[self.collectionView.collectionViewLayout invalidateLayoutWithContext:[JSQMessagesCollectionViewFlowLayoutInvalidationContext context]]; |
2084 |
[self scrollToBottomAnimated:YES]; |
2085 |
} |
2086 |
} else { |
2087 |
[self.collectionView.collectionViewLayout invalidateLayoutWithContext:[JSQMessagesCollectionViewFlowLayoutInvalidationContext context]]; |
2088 |
} |
2089 |
}]; |
2090 |
} |
2091 |
|
2092 |
#pragma - mark UITextViewDelegateMethods |
2093 |
|
2094 |
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange |
2095 |
{ |
2096 |
if ([URL otr_isInviteLink]) { |
2097 |
NSUserActivity *activity = [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb]; |
2098 |
activity.webpageURL = URL; |
2099 |
[[OTRAppDelegate appDelegate] application:[UIApplication sharedApplication] continueUserActivity:activity restorationHandler:^(NSArray * _Nullable restorableObjects) { |
2100 |
// TODO: restore stuff |
2101 |
}]; |
2102 |
return NO; |
2103 |
} |
2104 |
|
2105 |
UIActivityViewController *activityViewController = [UIActivityViewController otr_linkActivityViewControllerWithURLs:@[URL]]; |
2106 |
|
2107 |
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) { |
2108 |
activityViewController.popoverPresentationController.sourceView = textView; |
2109 |
activityViewController.popoverPresentationController.sourceRect = textView.bounds; |
2110 |
} |
2111 |
|
2112 |
[self presentViewController:activityViewController animated:YES completion:nil]; |
2113 |
return NO; |
2114 |
} |
2115 |
|
2116 |
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ |
2117 |
return NO; |
2118 |
} |
2119 |
|
2120 |
- (void)viewWillLayoutSubviews { |
2121 |
self.currentIndexPath = nil; |
2122 |
[super viewWillLayoutSubviews]; |
2123 |
} |
2124 |
|
2125 |
- (void)viewDidLayoutSubviews { |
2126 |
[super viewDidLayoutSubviews]; |
2127 |
[self layoutJIDForwardingHeader]; |
2128 |
} |
2129 |
|
2130 |
#pragma - mark Buddy Migration methods |
2131 |
|
2132 |
- (nullable XMPPJID *)getForwardingJIDForBuddy:(OTRXMPPBuddy *)xmppBuddy { |
2133 |
XMPPJID *ret = nil; |
2134 |
if (xmppBuddy != nil && xmppBuddy.vCardTemp != nil) { |
2135 |
ret = xmppBuddy.vCardTemp.jid; |
2136 |
} |
2137 |
return ret; |
2138 |
} |
2139 |
|
2140 |
- (void)layoutJIDForwardingHeader { |
2141 |
if (self.jidForwardingHeaderView != nil) { |
2142 |
[self.jidForwardingHeaderView setNeedsLayout]; |
2143 |
[self.jidForwardingHeaderView layoutIfNeeded]; |
2144 |
int height = [self.jidForwardingHeaderView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 1; |
2145 |
self.jidForwardingHeaderView.frame = CGRectMake(0, self.topLayoutGuide.length, self.view.frame.size.width, height); |
2146 |
[self.view bringSubviewToFront:self.jidForwardingHeaderView]; |
2147 |
self.topContentAdditionalInset = height; |
2148 |
} |
2149 |
} |
2150 |
|
2151 |
- (void)updateJIDForwardingHeader { |
2152 |
|
2153 |
__block id<OTRThreadOwner> thread = nil; |
2154 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
2155 |
thread = [self threadObjectWithTransaction:transaction]; |
2156 |
}]; |
2157 |
OTRXMPPBuddy *buddy = nil; |
2158 |
if ([thread isKindOfClass:[OTRXMPPBuddy class]]) { |
2159 |
buddy = (OTRXMPPBuddy*)thread; |
2160 |
} |
2161 |
|
2162 |
// If we have a buddy with vcard JID set to something else than the username, show a |
2163 |
// "buddy has moved" warning to allow the user to start a chat with that JID instead. |
2164 |
BOOL showHeader = NO; |
2165 |
XMPPJID *forwardingJid = [self getForwardingJIDForBuddy:buddy]; |
2166 |
if (forwardingJid != nil && ![forwardingJid isEqualToJID:buddy.bareJID options:XMPPJIDCompareBare]) { |
2167 |
showHeader = YES; |
2168 |
} |
2169 |
|
2170 |
if (showHeader) { |
2171 |
[self showJIDForwardingHeaderWithNewJID:forwardingJid]; |
2172 |
} else if (!showHeader && self.jidForwardingHeaderView != nil) { |
2173 |
self.topContentAdditionalInset = 0; |
2174 |
[self.jidForwardingHeaderView removeFromSuperview]; |
2175 |
self.jidForwardingHeaderView = nil; |
2176 |
} |
2177 |
} |
2178 |
|
2179 |
- (void)showJIDForwardingHeaderWithNewJID:(XMPPJID *)newJid { |
2180 |
if (self.jidForwardingHeaderView == nil) { |
2181 |
UINib *nib = [UINib nibWithNibName:@"MigratedBuddyHeaderView" bundle:OTRAssets.resourcesBundle]; |
2182 |
MigratedBuddyHeaderView *header = (MigratedBuddyHeaderView*)[nib instantiateWithOwner:self options:nil][0]; |
2183 |
[header setForwardingJID:newJid]; |
2184 |
[header.titleLabel setText:MIGRATED_BUDDY_STRING()]; |
2185 |
[header.descriptionLabel setText:MIGRATED_BUDDY_INFO_STRING()]; |
2186 |
[header.switchButton setTitle:MIGRATED_BUDDY_SWITCH() forState:UIControlStateNormal]; |
2187 |
[header.ignoreButton setTitle:MIGRATED_BUDDY_IGNORE() forState:UIControlStateNormal]; |
2188 |
[header setBackgroundColor:UIColor.whiteColor]; |
2189 |
[self.view addSubview:header]; |
2190 |
[self.view bringSubviewToFront:header]; |
2191 |
self.jidForwardingHeaderView = header; |
2192 |
[self.view setNeedsLayout]; |
2193 |
} |
2194 |
} |
2195 |
|
2196 |
- (IBAction)didPressMigratedIgnore { |
2197 |
if (self.jidForwardingHeaderView != nil) { |
2198 |
self.jidForwardingHeaderView.hidden = YES; |
2199 |
self.topContentAdditionalInset = 0; |
2200 |
} |
2201 |
} |
2202 |
|
2203 |
- (IBAction)didPressMigratedSwitch { |
2204 |
if (self.jidForwardingHeaderView != nil) { |
2205 |
self.jidForwardingHeaderView.hidden = YES; |
2206 |
self.topContentAdditionalInset = 0; |
2207 |
} |
2208 |
|
2209 |
__block OTRXMPPBuddy *buddy = nil; |
2210 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
2211 |
buddy = (OTRXMPPBuddy*)[self buddyWithTransaction:transaction]; |
2212 |
}]; |
2213 |
|
2214 |
XMPPJID *forwardingJid = [self getForwardingJIDForBuddy:buddy]; |
2215 |
if (forwardingJid != nil) { |
2216 |
// Try to find buddy |
2217 |
// |
2218 |
[[OTRDatabaseManager sharedInstance].readWriteDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) { |
2219 |
OTRAccount *account = [self accountWithTransaction:transaction]; |
2220 |
OTRXMPPBuddy *buddy = [OTRXMPPBuddy fetchBuddyWithJid:forwardingJid accountUniqueId:account.uniqueId transaction:transaction]; |
2221 |
if (!buddy) { |
2222 |
buddy = [[OTRXMPPBuddy alloc] init]; |
2223 |
buddy.accountUniqueId = account.uniqueId; |
2224 |
buddy.username = forwardingJid.bare; |
2225 |
[buddy saveWithTransaction:transaction]; |
2226 |
id<OTRProtocol> proto = [[OTRProtocolManager sharedInstance] protocolForAccount:account]; |
2227 |
if (proto != nil) { |
2228 |
[proto addBuddy:buddy]; |
2229 |
} |
2230 |
} |
2231 |
[self setThreadKey:buddy.uniqueId collection:[OTRBuddy collection]]; |
2232 |
}]; |
2233 |
} |
2234 |
} |
2235 |
|
2236 |
#pragma - mark Group chat support |
2237 |
|
2238 |
- (void)setupWithBuddies:(NSArray<NSString *> *)buddies accountId:(NSString *)accountId name:(NSString *)name |
2239 |
{ |
2240 |
__block OTRXMPPAccount *account = nil; |
2241 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
2242 |
account = [OTRXMPPAccount fetchObjectWithUniqueID:accountId transaction:transaction]; |
2243 |
}]; |
2244 |
OTRXMPPManager *xmppManager = (OTRXMPPManager *)[[OTRProtocolManager sharedInstance] protocolForAccount:account]; |
2245 |
NSString *service = [xmppManager.roomManager.conferenceServicesJID firstObject]; |
2246 |
if (service.length > 0) { |
2247 |
NSString *roomName = [NSUUID UUID].UUIDString; |
2248 |
XMPPJID *roomJID = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",roomName,service]]; |
2249 |
self.threadKey = [xmppManager.roomManager startGroupChatWithBuddies:buddies roomJID:roomJID nickname:account.displayName subject:name]; |
2250 |
[self setThreadKey:self.threadKey collection:[OTRXMPPRoom collection]]; |
2251 |
} else { |
2252 |
DDLogError(@"No conference server for account: %@", account.username); |
2253 |
} |
2254 |
} |
2255 |
|
2256 |
#pragma - mark OTRRoomOccupantsViewControllerDelegate |
2257 |
|
2258 |
- (void)didLeaveRoom:(OTRRoomOccupantsViewController *)roomOccupantsViewController { |
2259 |
__block OTRXMPPRoom *room = nil; |
2260 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
2261 |
room = [self roomWithTransaction:transaction]; |
2262 |
}]; |
2263 |
if (room) { |
2264 |
[self setThreadKey:nil collection:nil]; |
2265 |
[self.readWriteDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
2266 |
[room removeWithTransaction:transaction]; |
2267 |
}]; |
2268 |
} |
2269 |
[self.navigationController popViewControllerAnimated:NO]; |
2270 |
if ([[self.navigationController viewControllers] count] > 1) { |
2271 |
[self.navigationController popViewControllerAnimated:YES]; |
2272 |
} else { |
2273 |
[self.navigationController.navigationController popViewControllerAnimated:YES]; |
2274 |
} |
2275 |
|
2276 |
} |
2277 |
|
2278 |
- (void)didArchiveRoom:(OTRRoomOccupantsViewController *)roomOccupantsViewController { |
2279 |
__block OTRXMPPRoom *room = nil; |
2280 |
[self.readOnlyDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction * _Nonnull transaction) { |
2281 |
room = [self roomWithTransaction:transaction]; |
2282 |
}]; |
2283 |
if (room) { |
2284 |
[self setThreadKey:nil collection:nil]; |
2285 |
[self.readWriteDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) { |
2286 |
room.isArchived = YES; |
2287 |
[room saveWithTransaction:transaction]; |
2288 |
}]; |
2289 |
} |
2290 |
[self.navigationController popViewControllerAnimated:NO]; |
2291 |
if ([[self.navigationController viewControllers] count] > 1) { |
2292 |
[self.navigationController popViewControllerAnimated:YES]; |
2293 |
} else { |
2294 |
[self.navigationController.navigationController popViewControllerAnimated:YES]; |
2295 |
} |
2296 |
} |
2297 |
|
2298 |
#pragma - mark OTRMessagesCollectionViewFlowLayoutSupplementaryViewProtocol |
2299 |
|
2300 |
- (nullable NSArray *)supplementaryViewsForCellAtIndexPath:(NSIndexPath *)indexPath { |
2301 |
id<OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
2302 |
if ([self isGroupChat] && [message isKindOfClass:[OTRGroupDownloadMessage class]]) { |
2303 |
OTRGroupDownloadMessage *roomMessage = (OTRGroupDownloadMessage *)message; |
2304 |
// A message that is not automatically downloaded, even though auto download not disabled, means that this is group download message from someone who is not our friend. |
2305 |
if ([roomMessage.messageError isAutomaticDownloadError] && !self.automaticURLFetchingDisabled && [roomMessage.media isKindOfClass:[OTRImageItem class]]) { |
2306 |
if (!_prototypeCellUnknownSender) { |
2307 |
UINib *nib = [UINib nibWithNibName:@"OTRMessageUnknownSenderCell" bundle:OTRAssets.resourcesBundle]; |
2308 |
_prototypeCellUnknownSender = (OTRMessagesUnknownSenderCell *)[nib instantiateWithOwner:self options:nil][0]; |
2309 |
} |
2310 |
[self populateUnknownSenderCell:_prototypeCellUnknownSender withMessage:message]; |
2311 |
[_prototypeCellUnknownSender setNeedsLayout]; |
2312 |
[_prototypeCellUnknownSender layoutIfNeeded]; |
2313 |
_prototypeCellUnknownSender.frame = CGRectMake(0, 0, self.collectionView.bounds.size.width, _prototypeCellUnknownSender.frame.size.height); |
2314 |
int height = [_prototypeCellUnknownSender systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 1; |
2315 |
|
2316 |
OTRMessagesCollectionSupplementaryViewInfo *info = [[OTRMessagesCollectionSupplementaryViewInfo alloc] initWithKind:[OTRMessagesUnknownSenderCell reuseIdentifier] height:height]; |
2317 |
return [NSArray arrayWithObject:info]; |
2318 |
} |
2319 |
} |
2320 |
return nil; |
2321 |
} |
2322 |
|
2323 |
- (void)populateUnknownSenderCell:(OTRMessagesUnknownSenderCell *)cell withMessage:(id<OTRMessageProtocol,JSQMessageData>)message { |
2324 |
cell.titleLabel.text = [NSString stringWithFormat:ADD_FRIEND_TO_AUTO_DOWNLOAD(), message.senderDisplayName]; |
2325 |
} |
2326 |
|
2327 |
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { |
2328 |
if ([OTRMessagesUnknownSenderCell.reuseIdentifier isEqualToString:kind]) { |
2329 |
id<OTRMessageProtocol,JSQMessageData> message = [self messageAtIndexPath:indexPath]; |
2330 |
OTRMessagesUnknownSenderCell *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kind forIndexPath:indexPath]; |
2331 |
[self populateUnknownSenderCell:cell withMessage:message]; |
2332 |
return cell; |
2333 |
} |
2334 |
// We should never get there, but if we do, don't return nil |
2335 |
return [[UICollectionReusableView alloc] initWithFrame:CGRectZero]; |
2336 |
} |
2337 |
|
2338 |
@end |