ChatFileMessageCell.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2015-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "ChatFileMessageCell.h"
  21. #import "FileMessage.h"
  22. #import "ImageData.h"
  23. #import "FileMessageSender.h"
  24. #import "RectUtil.h"
  25. #import "Utils.h"
  26. #import "BlobMessageLoader.h"
  27. #import "ProtocolDefines.h"
  28. #import "UTIConverter.h"
  29. #import "BundleUtil.h"
  30. #import "FileMessagePreview.h"
  31. #import "UIImage+ColoredImage.h"
  32. #import "MDMSetup.h"
  33. #import "BlobUtil.h"
  34. #import "PinnedHTTPSURLLoader.h"
  35. #import "NaClCrypto.h"
  36. #import "EntityManager.h"
  37. #define DOWNLOAD_VIEW_HEIGHT 18.0f
  38. #define THUMBNAIL_SIZE 64.0
  39. #define THUMBNAIL_SMALL_SIZE 36.0
  40. #define MIN_HEIGHT 34.0f
  41. #define NAME_LABEL_PADDING 16.0f
  42. #define PROGRESSBAR_PADDING 40.0f
  43. #define THUMBNAIL_PADDING 8.0f
  44. #define RESEND_BUTTON_WIDTH 114.0f
  45. @interface ChatFileMessageCell ()
  46. @property UIImageView *thumbnailView;
  47. @property UILabel *downloadSizeLabel;
  48. @property UILabel *nameLabel;
  49. @property UIImageView *downloadBackground;
  50. @property FileMessagePreview *fileMessagPreview;
  51. @end
  52. @implementation ChatFileMessageCell
  53. + (CGFloat)heightForMessage:(BaseMessage*)message forTableWidth:(CGFloat)tableWidth {
  54. CGSize maxSize = CGSizeMake([ChatMessageCell maxContentWidthForTableWidth:tableWidth] - NAME_LABEL_PADDING, CGFLOAT_MAX);
  55. static UILabel *dummyLabel = nil;
  56. if (dummyLabel == nil) {
  57. dummyLabel = [[UILabel alloc] init];
  58. dummyLabel.clearsContextBeforeDrawing = NO;
  59. dummyLabel.numberOfLines = 0;
  60. dummyLabel.lineBreakMode = NSLineBreakByWordWrapping;
  61. dummyLabel.textAlignment = NSTextAlignmentCenter;
  62. }
  63. dummyLabel.font = [ChatMessageCell textFont];
  64. dummyLabel.attributedText = [self displayTextForMessage:message];
  65. CGSize textSize = [dummyLabel sizeThatFits:maxSize];
  66. textSize.height = ceilf(textSize.height);
  67. CGFloat thumbnailSize = [self thumbnailSizeForMessage:(FileMessage*)message];
  68. return MAX(textSize.height + DOWNLOAD_VIEW_HEIGHT + thumbnailSize + 2*THUMBNAIL_PADDING, MIN_HEIGHT);
  69. }
  70. + (CGFloat)thumbnailSizeForMessage:(FileMessage *)message {
  71. CGFloat thumbnailSize = THUMBNAIL_SIZE;
  72. if (((FileMessage*)message).thumbnail == nil) {
  73. thumbnailSize = THUMBNAIL_SMALL_SIZE;
  74. }
  75. return thumbnailSize;
  76. }
  77. - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier transparent:(BOOL)transparent
  78. {
  79. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier transparent:transparent];
  80. if (self) {
  81. CGRect rect = CGRectMake(0.0, 0.0, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
  82. _thumbnailView = [[UIImageView alloc] initWithFrame:rect];
  83. _thumbnailView.clearsContextBeforeDrawing = NO;
  84. _thumbnailView.contentMode = UIViewContentModeScaleAspectFit;
  85. [self setBubbleHighlighted:NO];
  86. [self.contentView addSubview:self.thumbnailView];
  87. UIImage *downloadBackgroundImage = [[UIImage imageNamed:@"VideoDownloadBg"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 32, 0, 0)];
  88. _downloadBackground = [[UIImageView alloc] initWithImage:downloadBackgroundImage];
  89. _downloadBackground.opaque = NO;
  90. [self.contentView addSubview:self.downloadBackground];
  91. _downloadSizeLabel = [[UILabel alloc] init];
  92. _downloadSizeLabel.backgroundColor = [UIColor clearColor];
  93. _downloadSizeLabel.opaque = NO;
  94. _downloadSizeLabel.font = [UIFont boldSystemFontOfSize:12.0];
  95. _downloadSizeLabel.textColor = [UIColor whiteColor];
  96. _downloadSizeLabel.textAlignment = NSTextAlignmentRight;
  97. _downloadSizeLabel.adjustsFontSizeToFitWidth = YES;
  98. [self.contentView addSubview:_downloadSizeLabel];
  99. _nameLabel = [[UILabel alloc] init];
  100. _nameLabel.clearsContextBeforeDrawing = NO;
  101. _nameLabel.backgroundColor = [UIColor clearColor];
  102. _nameLabel.numberOfLines = 0;
  103. _nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
  104. _nameLabel.font = [ChatMessageCell textFont];
  105. _nameLabel.textAlignment = NSTextAlignmentCenter;
  106. [self.contentView addSubview:_nameLabel];
  107. }
  108. return self;
  109. }
  110. - (void)setupColors {
  111. [super setupColors];
  112. _nameLabel.textColor = [Colors fontNormal];
  113. }
  114. - (void)dealloc {
  115. @try {
  116. [self.message removeObserver:self forKeyPath:@"data"];
  117. }
  118. @catch(NSException *e) {}
  119. }
  120. - (void)setMessage:(BaseMessage *)newMessage {
  121. @try {
  122. [self.message removeObserver:self forKeyPath:@"data"];
  123. }
  124. @catch(NSException *e) {}
  125. FileMessage *fileMessage = (FileMessage*)newMessage;
  126. [super setMessage:fileMessage];
  127. if (!self.chatVc.isOpenWithForceTouch) {
  128. [self.message addObserver:self forKeyPath:@"data" options:0 context:nil];
  129. }
  130. [_nameLabel setAttributedText:[ChatFileMessageCell displayTextForMessage:self.message]];
  131. [_downloadSizeLabel setText: [Utils formatDataLength:fileMessage.fileSize.floatValue]];
  132. [self updateThumbnailImage];
  133. UIViewAutoresizing resizing = UIViewAutoresizingFlexibleRightMargin;
  134. if (fileMessage.isOwn.boolValue) {
  135. resizing = UIViewAutoresizingFlexibleLeftMargin;
  136. }
  137. _thumbnailView.autoresizingMask = resizing;
  138. _downloadBackground.autoresizingMask = resizing;
  139. _downloadSizeLabel.autoresizingMask = resizing;
  140. [self updateDownloadSize];
  141. [self setNeedsLayout];
  142. }
  143. - (void)layoutSubviews {
  144. CGFloat messageTextWidth;
  145. if (@available(iOS 11.0, *)) {
  146. messageTextWidth = [ChatMessageCell maxContentWidthForTableWidth:self.safeAreaLayoutGuide.layoutFrame.size.width];
  147. } else {
  148. messageTextWidth = [ChatMessageCell maxContentWidthForTableWidth:self.frame.size.width];
  149. }
  150. CGSize textSize = [_nameLabel sizeThatFits:CGSizeMake(messageTextWidth - NAME_LABEL_PADDING, CGFLOAT_MAX)];
  151. CGFloat thumbnailSize = [ChatFileMessageCell thumbnailSizeForMessage:(FileMessage*)self.message];
  152. CGFloat height = ceilf(textSize.height + DOWNLOAD_VIEW_HEIGHT + thumbnailSize + 2*THUMBNAIL_PADDING);
  153. CGSize size = CGSizeMake(textSize.width + NAME_LABEL_PADDING, height);
  154. [self setBubbleContentSize:size];
  155. [super layoutSubviews];
  156. CGRect backgroundRect = self.msgBackground.frame;
  157. CALayer *mask = [self bubbleMaskForImageSize:backgroundRect.size];
  158. _downloadBackground.layer.mask = mask;
  159. _downloadBackground.layer.masksToBounds = YES;
  160. _downloadBackground.frame = CGRectMake(backgroundRect.origin.x, backgroundRect.origin.y, backgroundRect.size.width, DOWNLOAD_VIEW_HEIGHT);
  161. _downloadSizeLabel.frame = CGRectMake(backgroundRect.origin.x + NAME_LABEL_PADDING/2.0, backgroundRect.origin.y, backgroundRect.size.width - NAME_LABEL_PADDING - 10.0, DOWNLOAD_VIEW_HEIGHT);
  162. CGFloat yOffset = CGRectGetMaxY(_downloadBackground.frame) + THUMBNAIL_PADDING;
  163. _thumbnailView.frame = [RectUtil setYPositionOf:_thumbnailView.frame y: yOffset];
  164. _thumbnailView.frame = [RectUtil rect:_thumbnailView.frame centerHorizontalIn:backgroundRect round:YES];
  165. _thumbnailView.frame = [RectUtil offsetRect:_thumbnailView.frame byX:backgroundRect.origin.x byY:0.0];
  166. yOffset += _thumbnailView.frame.size.height + THUMBNAIL_PADDING/2.0;
  167. self.progressBar.frame = CGRectMake(backgroundRect.origin.x + PROGRESSBAR_PADDING/2.0, yOffset, backgroundRect.size.width - PROGRESSBAR_PADDING, self.progressBar.frame.size.height);
  168. yOffset += THUMBNAIL_PADDING;
  169. if (self.message.isOwn.boolValue) {
  170. CGFloat resendButtonX = backgroundRect.origin.x - RESEND_BUTTON_WIDTH;
  171. CGFloat resendButtonHeight;
  172. CGFloat resendButtonWidth;
  173. if (resendButtonX < 8.0) {
  174. self.resendButton.titleLabel.numberOfLines = 2;
  175. resendButtonWidth = backgroundRect.origin.x - 16.0;
  176. resendButtonX = 8.0;
  177. resendButtonHeight = 64.0;
  178. } else {
  179. self.resendButton.titleLabel.numberOfLines = 1;
  180. resendButtonHeight = 32.0;
  181. resendButtonWidth = RESEND_BUTTON_WIDTH;
  182. }
  183. self.resendButton.frame = CGRectMake(resendButtonX, _thumbnailView.frame.origin.y + (_thumbnailView.frame.size.height - resendButtonHeight) / 2.0, resendButtonWidth, resendButtonHeight);
  184. }
  185. _nameLabel.frame = CGRectMake(0, yOffset, textSize.width, textSize.height);
  186. _nameLabel.frame = [RectUtil rect:_nameLabel.frame centerHorizontalIn:backgroundRect round:YES];
  187. _nameLabel.frame = [RectUtil offsetRect:_nameLabel.frame byX:backgroundRect.origin.x byY:0.0];
  188. }
  189. - (void)updateThumbnailImage {
  190. FileMessage *fileMessage = (FileMessage*) self.message;
  191. if (fileMessage.blobThumbnailId != nil && fileMessage.thumbnail == nil) {
  192. // load thumbnail
  193. [self loadThumbnail: fileMessage];
  194. }
  195. UIImage *thumbnailImage = [FileMessagePreview thumbnailForFileMessage:fileMessage];
  196. CGFloat thumbnailSize = [ChatFileMessageCell thumbnailSizeForMessage:(FileMessage*)self.message];
  197. _thumbnailView.frame = [RectUtil setSizeOf:_thumbnailView.frame width:thumbnailSize height:thumbnailSize];
  198. _thumbnailView.frame = [RectUtil rect:_thumbnailView.frame centerIn:self.msgBackground.frame];
  199. _thumbnailView.image = thumbnailImage;
  200. }
  201. - (void)loadThumbnail:(FileMessage *)fileMessage {
  202. NSURLRequest *request = [BlobUtil urlRequestForBlobId:fileMessage.blobThumbnailId];
  203. PinnedHTTPSURLLoader *thumbnailLoader = [[PinnedHTTPSURLLoader alloc] init];
  204. [thumbnailLoader startWithURLRequest:request onCompletion:^(NSData *data) {
  205. /* Decrypt the box */
  206. NSData *thumbnailData = [[NaClCrypto sharedCrypto] symmetricDecryptData:data withKey:[fileMessage encryptionKey] nonce:[NSData dataWithBytesNoCopy:kNonce_2 length:sizeof(kNonce_2) freeWhenDone:NO]];
  207. if (thumbnailData != nil) {
  208. EntityManager *entityManager = [[EntityManager alloc] init];
  209. [entityManager performSyncBlockAndSafe:^{
  210. ImageData *thumbnail = [entityManager.entityCreator imageData];
  211. thumbnail.data = thumbnailData;
  212. // load image to determine size
  213. UIImage *thumbnailImage = [UIImage imageWithData:thumbnailData];
  214. thumbnail.width = [NSNumber numberWithInt:thumbnailImage.size.width];
  215. thumbnail.height = [NSNumber numberWithInt:thumbnailImage.size.height];
  216. fileMessage.thumbnail = thumbnail;
  217. }];
  218. [self setNeedsLayout];
  219. }
  220. } onError:^(NSError *error) {
  221. // do nothing
  222. }];
  223. }
  224. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  225. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. if (object == self.message && [keyPath isEqualToString:@"data"]) {
  228. [self updateDownloadSize];
  229. }
  230. });
  231. }
  232. - (void)updateDownloadSize {
  233. FileMessage *fileMessage = (FileMessage*)self.message;
  234. if (fileMessage.data != nil) {
  235. _downloadBackground.hidden = YES;
  236. _downloadSizeLabel.textColor = [Colors fontNormal];
  237. } else {
  238. // blob ID equals nil means media was deleted
  239. _downloadBackground.hidden = fileMessage.blobId != nil ? NO : YES;
  240. _downloadSizeLabel.textColor = [UIColor whiteColor];
  241. }
  242. }
  243. - (void)messageTapped:(id)sender {
  244. FileMessage *fileMessage = (FileMessage*)self.message;
  245. if (fileMessage.data == nil) {
  246. /* need to download this file first */
  247. BlobMessageLoader *loader = [[BlobMessageLoader alloc] init];
  248. [loader startWithMessage:fileMessage onCompletion:^(BaseMessage *message) {
  249. [self showDetails];
  250. } onError:^(NSError *error) {
  251. if (error.code != kErrorCodeUserCancelled) {
  252. [UIAlertTemplate showAlertWithOwner:[[AppDelegate sharedAppDelegate] currentTopViewController] title:error.localizedDescription message:error.localizedFailureReason actionOk:nil];
  253. }
  254. }];
  255. } else {
  256. [self showDetails];
  257. }
  258. }
  259. - (void)showDetails {
  260. if (self.chatVc.visible == NO) {
  261. return;
  262. }
  263. // to prevent keyboard issue when playing audio using UIDocumentInteractionController (IOS-163)
  264. [self.chatVc.chatBar resignFirstResponder];
  265. FileMessage *fileMessage = (FileMessage*)self.message;
  266. _fileMessagPreview = [FileMessagePreview fileMessagePreviewFor:fileMessage];
  267. [_fileMessagPreview showOn:self.chatVc];
  268. }
  269. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  270. if (action == @selector(resendMessage:) && self.message.isOwn.boolValue && self.message.sendFailed.boolValue)
  271. return YES;
  272. else if (action == @selector(deleteMessage:) && self.message.isOwn.boolValue && !self.message.sent.boolValue && !self.message.sendFailed.boolValue)
  273. return NO; /* don't allow messages in progress to be deleted */
  274. else if (action == @selector(copyMessage:))
  275. return NO; /* cannot copy files */
  276. else if (action == @selector(shareMessage:)) {
  277. if (@available(iOS 13.0, *)) {
  278. MDMSetup *mdmSetup = [[MDMSetup alloc] initWithSetup:false];
  279. if ([mdmSetup disableShareMedia] == true) {
  280. return NO;
  281. }
  282. }
  283. return (((FileMessage*)self.message).data != nil); /* can only save downloaded files */
  284. } else if (action == @selector(forwardMessage:))
  285. if (@available(iOS 13.0, *)) {
  286. return (((FileMessage*)self.message).data != nil); /* can only save downloaded files */
  287. } else {
  288. return NO;
  289. }
  290. else
  291. return [super canPerformAction:action withSender:sender];
  292. }
  293. - (NSString *)textForQuote {
  294. FileMessage *fileMessage = (FileMessage*)self.message;
  295. return [fileMessage getCaption];
  296. }
  297. - (void)resendMessage:(UIMenuController*)menuController {
  298. FileMessage *fileMessage = (FileMessage*)self.message;
  299. FileMessageSender *sender = [[FileMessageSender alloc] init];
  300. [sender retryMessage:fileMessage];
  301. }
  302. - (BOOL)performPlayActionForAccessibility {
  303. [self messageTapped:self];
  304. return YES;
  305. }
  306. - (BOOL)highlightOccurencesOf:(NSString *)pattern {
  307. NSAttributedString *attributedString = [ChatMessageCell highlightedOccurencesOf:pattern inString:_nameLabel.text];
  308. if (attributedString) {
  309. _nameLabel.attributedText = attributedString;
  310. return YES;
  311. }
  312. return NO;
  313. }
  314. + (NSAttributedString*)displayTextForMessage:(BaseMessage*)message {
  315. FileMessage *fileMessage = (FileMessage*)message;
  316. NSString *caption = [fileMessage getCaption];
  317. NSMutableAttributedString *labelText;
  318. UIFont *font = [ChatMessageCell textFont];
  319. if (caption.length > 0) {
  320. UIFont *captionFont = [font fontWithSize:font.pointSize*0.85];
  321. labelText = [[NSMutableAttributedString alloc] initWithString:fileMessage.fileName attributes:@{ NSFontAttributeName : font }];
  322. [labelText appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n\n" attributes:@{ NSFontAttributeName : captionFont }]];
  323. [labelText appendAttributedString:[[NSAttributedString alloc] initWithString:caption attributes:@{ NSFontAttributeName : captionFont }]];
  324. } else {
  325. NSString *name = fileMessage.fileName;
  326. if (name == nil || name.length == 0) {
  327. name = @"Unknown";
  328. }
  329. labelText = [[NSMutableAttributedString alloc] initWithString:name];
  330. }
  331. return labelText;
  332. }
  333. - (NSString *)accessibilityLabelForContent {
  334. FileMessage *fileMessage = (FileMessage*)self.message;
  335. NSString *type = [UTIConverter localizedDescriptionForMimeType:fileMessage.mimeType];
  336. NSString *name = fileMessage.fileName;
  337. NSString *size = [Utils formatDataLength:fileMessage.fileSize.floatValue];
  338. NSString *fileInfo = [NSString stringWithFormat:@"%@. %@. %@", type, name, size];
  339. NSString *caption = [fileMessage getCaption];
  340. if (caption.length > 0) {
  341. return [NSString stringWithFormat:@"%@. %@", fileInfo, caption];
  342. } else {
  343. return fileInfo;
  344. }
  345. }
  346. - (UIContextMenuConfiguration *)getContextMenu:(NSIndexPath *)indexPath point:(CGPoint)point API_AVAILABLE(ios(13.0)) {
  347. if (!self.editing) {
  348. CGPoint convertedPoint = [_thumbnailView convertPoint:point fromView:self.chatVc.chatContent];
  349. FileMessage *fileMessage = (FileMessage*)self.message;
  350. if ([_thumbnailView pointInside:convertedPoint withEvent:nil] && fileMessage.data != nil) {
  351. if (fileMessage.data.data != nil) {
  352. UIContextMenuConfiguration *conf = [UIContextMenuConfiguration configurationWithIdentifier:indexPath previewProvider:^UIViewController * _Nullable{
  353. return [self.chatVc.headerView getPhotoBrowserAtMessage:self.message forPeeking:YES];
  354. } actionProvider:^UIMenu * _Nullable(NSArray<UIMenuElement *> * _Nonnull suggestedActions) {
  355. return nil;
  356. }];
  357. return conf;
  358. } else {
  359. return [super getContextMenu:indexPath point:point];
  360. }
  361. }
  362. }
  363. return [super getContextMenu:indexPath point:point];
  364. }
  365. @end