JLChen
2021-08-02 38f4fb064df09f344fc3237409c76a9fba2a8a9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-iphone
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
 
#import "UIChatBubbleTextCell.h"
#import "LinphoneManager.h"
#import "PhoneMainView.h"
 
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
 
@implementation UIChatBubbleTextCell
 
#pragma mark - Lifecycle Functions
 
- (id)initWithIdentifier:(NSString *)identifier {
    if ((self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]) != nil) {
        if ([identifier isEqualToString:NSStringFromClass(self.class)]) {
            NSArray *arrayOfViews =
                [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
            // resize cell to match .nib size. It is needed when resized the cell to
            // correctly adapt its height too
            UIView *sub = ((UIView *)[arrayOfViews objectAtIndex:arrayOfViews.count - 1]);
            [self setFrame:CGRectMake(0, 0, sub.frame.size.width, sub.frame.size.height)];
            [self addSubview:sub];
        }
    }
 
    UITapGestureRecognizer *limeRecognizer =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onLime)];
    limeRecognizer.numberOfTapsRequired = 1;
    //[_LIMEKO addGestureRecognizer:limeRecognizer];
    //_LIMEKO.userInteractionEnabled = YES;
    UITapGestureRecognizer *resendRecognizer =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onResend)];
    resendRecognizer.numberOfTapsRequired = 1;
    [_bubbleView addGestureRecognizer:resendRecognizer];
    _imdmIcon.userInteractionEnabled = YES;
    UITapGestureRecognizer *resendRecognizer2 =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onResend)];
    resendRecognizer2.numberOfTapsRequired = 1;
    //[_imdmLabel addGestureRecognizer:resendRecognizer2];
    //_imdmLabel.userInteractionEnabled = YES;
 
    self.contentView.userInteractionEnabled = NO;
    return self;
}
 
- (void)dealloc {
    [self setEvent:NULL];
    [self setChatMessageForCbs:NULL];
}
 
#pragma mark -
 
- (void)clearEncryptedFiles {
    if ([VFSUtil vfsEnabledWithGroupName:kLinphoneMsgNotificationAppGroupId]) {
        NSMutableDictionary<NSString *, NSString *> *encrptedFilePaths = [LinphoneManager getMessageAppDataForKey:@"encryptedfiles" inMessage:_message];
        if ([encrptedFilePaths count] > 0) {
            for(NSString *path in [encrptedFilePaths allValues]) {
                if (![path isEqualToString:@""]) {
                    LOGW(@"[vfs]s remove item at %@",path);
                    if ([path isEqualToString:[LinphoneManager imagesDirectory]]) {
                        LOGE(@"[vfs] something is wrong, can not delete the cache directory");
                        break;
                    }
                    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                    
                }
            }
            [LinphoneManager setValueInMessageAppData:NULL forKey:@"encryptedfiles" inMessage:_message];
            return;
        }
 
        NSString *filePath = [LinphoneManager getMessageAppDataForKey:@"encryptedfile" inMessage:_message];
        if (filePath) {
            if (![filePath isEqualToString:@""]) {
                NSError *error = nil;
                LOGW(@"[vfs] remove item at %@",filePath);
                if ([filePath isEqualToString:[LinphoneManager imagesDirectory]]) {
                    LOGE(@"[vfs] something is wrong, can not delete the cache directory");
                } else {
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
                
                    if (error) {
                        LOGI(@"clean failed %@", error.description);
                    }
                }
            }
            [LinphoneManager setValueInMessageAppData:NULL forKey:@"encryptedfile" inMessage:_message];
        }
    }
}
 
- (void)setEvent:(LinphoneEventLog *)event {
    if(!event)
        return;
 
    _event = event;
    if (!(linphone_event_log_get_type(event) == LinphoneEventLogTypeConferenceChatMessage)) {
        LOGE(@"Impossible to create a ChatBubbleText whit a non message event");
        return;
    }
    [self setChatMessageForCbs:linphone_event_log_get_chat_message(event)];
}
 
- (void)setChatMessageForCbs:(LinphoneChatMessage *)amessage {
    if (!amessage || amessage == _message) {
        return;
    }
 
    _message = amessage;
    linphone_chat_message_set_user_data(_message, (void *)CFBridgingRetain(self));
    LinphoneChatMessageCbs *cbs = linphone_chat_message_get_callbacks(_message);
    linphone_chat_message_cbs_set_msg_state_changed(cbs, message_status);
    linphone_chat_message_cbs_set_participant_imdn_state_changed(cbs, participant_imdn_status);
    linphone_chat_message_cbs_set_user_data(cbs, (void *)_event);
}
 
+ (NSString *)TextMessageForChat:(LinphoneChatMessage *)message {
    const char *url = linphone_chat_message_get_external_body_url(message);
    const LinphoneContent *last_content = linphone_chat_message_get_file_transfer_information(message);
    // Last message was a file transfer (image) so display a picture...
    if (url || last_content) {
        if (linphone_chat_message_get_text_content(message))
            return [NSString stringWithUTF8String:linphone_chat_message_get_text_content(message)];
        return @"🗻";
    } else {
        const char *text = linphone_chat_message_get_text_content(message) ?: "";
        return [NSString stringWithUTF8String:text] ?: [NSString stringWithCString:text encoding:NSASCIIStringEncoding]
                                                           ?: NSLocalizedString(@"(invalid string)", nil);
    }
}
 
+ (NSString *)ContactDateForChat:(LinphoneChatMessage *)message {
    const LinphoneAddress *address =
        linphone_chat_message_get_from_address(message)
            ? linphone_chat_message_get_from_address(message)
            : linphone_chat_room_get_peer_address(linphone_chat_message_get_chat_room(message));
    return [NSString stringWithFormat:@"%@ - %@", [LinphoneUtils timeToString:linphone_chat_message_get_time(message)
                                                                   withFormat:LinphoneDateChatBubble],
                                      [FastAddressBook displayNameForAddress:address]];
}
 
- (NSString *)textMessage {
    return [self.class TextMessageForChat:_message];
}
 
- (void)update {
    if (_message == nil) {
        LOGW(@"Cannot update message room cell: null message");
        return;
    }
 
    if (_messageText && ![LinphoneManager getMessageAppDataForKey:@"localvideo" inMessage:_message]) {
        [_messageText setHidden:FALSE];
        /* We need to use an attributed string here so that data detector don't mess
         * with the text style. See http://stackoverflow.com/a/20669356 */
        UIColor *color = [UIColor darkGrayColor];
        if (@available(iOS 13,*)) {
            color = [UIColor secondaryLabelColor];
        }
 
        NSAttributedString *attr_text =
            [[NSAttributedString alloc] initWithString:self.textMessage
                                            attributes:@{
                                                NSFontAttributeName : _messageText.font,
                                                NSForegroundColorAttributeName : color
                                            }];
        _messageText.attributedText = attr_text;
    }
 
    LinphoneChatMessageState state = linphone_chat_message_get_state(_message);
    BOOL outgoing = linphone_chat_message_is_outgoing(_message);
   
    
    _contactDateLabel.hidden = !_isFirst;
    if (outgoing) {
        _contactDateLabel.text = [LinphoneUtils timeToString:linphone_chat_message_get_time(_message)
                                                  withFormat:LinphoneDateChatBubble];
        _contactDateLabel.textAlignment = NSTextAlignmentRight;
        _avatarImage.hidden = TRUE;
        
    } else {
        [_avatarImage setImage:[FastAddressBook imageForAddress:linphone_chat_message_get_from_address(_message)]
                      bordered:NO
             withRoundedRadius:YES];
        _contactDateLabel.text = [self.class ContactDateForChat:_message];
        _contactDateLabel.textAlignment = NSTextAlignmentLeft;
        _avatarImage.hidden = !_isFirst;
    }
    
    // Not use [UIImage imageNamed], it takes too much time
    NSString *imageName = outgoing ? @"color_A.png" : @"color_D.png";
    _backgroundColorImage.image =
        [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],imageName]];
    
    // set maskedCorners
    if (@available(iOS 11.0, *)) {
        _backgroundColorImage.layer.cornerRadius = 10;
        if (outgoing) {
            _backgroundColorImage.layer.maskedCorners = kCALayerMinXMaxYCorner | kCALayerMinXMinYCorner;
            if (_isFirst)
                _backgroundColorImage.layer.maskedCorners = _backgroundColorImage.layer.maskedCorners | kCALayerMaxXMinYCorner;
            if (_isLast)
                _backgroundColorImage.layer.maskedCorners = _backgroundColorImage.layer.maskedCorners | kCALayerMaxXMaxYCorner;
        } else {
            _backgroundColorImage.layer.maskedCorners = kCALayerMaxXMinYCorner | kCALayerMaxXMaxYCorner;
            if (_isFirst)
                _backgroundColorImage.layer.maskedCorners = _backgroundColorImage.layer.maskedCorners | kCALayerMinXMinYCorner;
            if (_isLast)
                _backgroundColorImage.layer.maskedCorners = _backgroundColorImage.layer.maskedCorners | kCALayerMinXMaxYCorner;
        }
        _backgroundColorImage.layer.masksToBounds = YES;
    } else {
        // TODO it doesn't work for ios < 11.0
        UIRectCorner corner;
        if (outgoing) {
            corner = UIRectCornerTopLeft | UIRectCornerBottomLeft;
            if (_isFirst)
                corner = corner | UIRectCornerTopRight;
            if (_isLast)
                corner = corner | UIRectCornerBottomRight;
        } else {
            corner = UIRectCornerTopRight | UIRectCornerBottomRight;
            if (_isFirst)
                corner = corner | UIRectCornerTopLeft;
            if (_isLast)
                corner = corner | UIRectCornerBottomLeft;
        }
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_backgroundColorImage.frame byRoundingCorners:corner cornerRadii:CGSizeMake(10,10)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = _backgroundColorImage.frame;
        maskLayer.path = maskPath.CGPath;
        _backgroundColorImage.layer.mask = maskLayer;
    }
    
    // need space for dateLabel
    CGRect frame = _innerView.frame;
    frame.origin.y = _isFirst ? 20 : 0;
    _innerView.frame = frame;
    
    [_messageText setAccessibilityLabel:outgoing ? @"Outgoing message" : @"Incoming message"];
    if (outgoing &&
        (state == LinphoneChatMessageStateDeliveredToUser || state == LinphoneChatMessageStateDisplayed ||
         state == LinphoneChatMessageStateNotDelivered || state == LinphoneChatMessageStateFileTransferError)) {
        [self displayImdmStatus:state];
    } else
        [self displayImdmStatus:LinphoneChatMessageStateInProgress];
}
 
- (void)setEditing:(BOOL)editing {
    [self setEditing:editing animated:FALSE];
}
 
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    _messageText.userInteractionEnabled = !editing;
    _resendRecognizer.enabled = !editing;
}
 
- (void)displayLIMEWarning {
    UIAlertController *errView =
        [UIAlertController alertControllerWithTitle:NSLocalizedString(@"LIME warning", nil)
                                            message:NSLocalizedString(@"This message is not encrypted.", nil)
                                     preferredStyle:UIAlertControllerStyleAlert];
 
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil)
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction *action){
                                                          }];
 
    [errView addAction:defaultAction];
    [PhoneMainView.instance presentViewController:errView animated:YES completion:nil];
}
 
#pragma mark - Action Functions
 
- (void)onDelete {
    if (_message != NULL) {
        UITableView *tableView = VIEW(ChatConversationView).tableController.tableView;
        NSIndexPath *indexPath = [tableView indexPathForCell:self];
        [tableView.dataSource tableView:tableView
                     commitEditingStyle:UITableViewCellEditingStyleDelete
                      forRowAtIndexPath:indexPath];
    }
}
 
- (void)onLime {
    /*if (!_LIMEKO.hidden)
        [self displayLIMEWarning];*/
}
 
- (void)onResend {
    if (_message == nil || !linphone_chat_message_is_outgoing(_message))
        return;
 
    LinphoneChatMessageState state = linphone_chat_message_get_state(_message);
    if (state != LinphoneChatMessageStateNotDelivered && state != LinphoneChatMessageStateFileTransferError)
        return;
 
    const bctbx_list_t *contents = linphone_chat_message_get_contents(_message);
    BOOL multiParts = ((linphone_chat_message_get_text_content(self.message) != NULL) ? bctbx_list_size(contents) > 2 : bctbx_list_size(contents) > 1);
    if (multiParts) {
        FileContext *newfileContext = [[FileContext alloc] init];
        [newfileContext clear];
        NSMutableDictionary<NSString *, NSString *> *encrptedFilePaths = encrptedFilePaths = [LinphoneManager getMessageAppDataForKey:@"encryptedfiles" inMessage:_message];
        int i;
        const bctbx_list_t *it;
        for (it = contents, i=0; it != NULL; it=bctbx_list_next(it)){
            LinphoneContent *content = (LinphoneContent *)it->data;
            if (linphone_content_is_file_transfer(content) || linphone_content_is_file(content)){
                NSString *name = [NSString stringWithUTF8String:linphone_content_get_name(content)];
                NSString *filePath = [encrptedFilePaths valueForKey:name];
                if (filePath == NULL) {
                    filePath = [LinphoneManager validFilePath:name];
                }
                [newfileContext addObject:[NSData dataWithContentsOfFile:filePath] name:name type:[NSString stringWithUTF8String:linphone_content_get_type(content)]];
            }
        }
        [self onDelete];
        dispatch_async(dispatch_get_main_queue(), ^ {
            const char *text = linphone_chat_message_get_text_content(_message);
            [_chatRoomDelegate resendMultiFiles:newfileContext message: text? [NSString stringWithUTF8String:text]: NULL];
        });
        return;
    }
    if (linphone_chat_message_get_file_transfer_information(_message) != NULL) {
        NSString *localImage = [LinphoneManager getMessageAppDataForKey:@"localimage" inMessage:_message];
        NSString *localVideo = [LinphoneManager getMessageAppDataForKey:@"localvideo" inMessage:_message];
        NSString *localFile = [LinphoneManager getMessageAppDataForKey:@"localfile" inMessage:_message];
        NSString *filePath = [LinphoneManager getMessageAppDataForKey:@"encryptedfile" inMessage:self.message];
 
        [self onDelete];
        dispatch_async(dispatch_get_main_queue(), ^ {
            NSData *data = NULL;
            if (filePath) {
                data = [NSData dataWithContentsOfFile:filePath];
            }
            const char *text = linphone_chat_message_get_text_content(_message);
            NSString *str = text ? [NSString stringWithUTF8String:text] : NULL;
            if (localImage) {
                [_chatRoomDelegate resendFile: (data?:[ChatConversationView getFileData:localImage]) withName:localImage type:@"image" key:@"localimage" message:str];
            } else if (localVideo) {
                [_chatRoomDelegate resendFile:(data?:[ChatConversationView getFileData:localVideo]) withName:localVideo type:@"video" key:@"localvideo" message:str];
            } else {
                [_chatRoomDelegate resendFile:(data?:[ChatConversationView getFileData:localFile]) withName:localFile type:@"image" key:@"localfile" message:str];
            }
        });
    } else {
        [self onDelete];
        double delayInSeconds = 0.4;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
            [_chatRoomDelegate resendChat:self.textMessage withExternalUrl:nil];
        });
    }
}
#pragma mark - State changed handling
static void message_status(LinphoneChatMessage *msg, LinphoneChatMessageState state) {
    LOGI(@"State for message [%p] changed to %s", msg, linphone_chat_message_state_to_string(state));
    if (!linphone_chat_message_is_outgoing(msg) || (state != LinphoneChatMessageStateFileTransferDone && state != LinphoneChatMessageStateFileTransferInProgress)) {
        LinphoneEventLog *event = (LinphoneEventLog *)linphone_chat_message_cbs_get_user_data(linphone_chat_message_get_callbacks(msg));
        ChatConversationView *view = VIEW(ChatConversationView);
        [view.tableController updateEventEntry:event];
        [view.tableController scrollToBottom:true];
    }
}
 
static void participant_imdn_status(LinphoneChatMessage* msg, const LinphoneParticipantImdnState *state) {
    ChatConversationImdnView *imdnView = VIEW(ChatConversationImdnView);
    [imdnView updateImdnList];
}
 
- (void)displayImdmStatus:(LinphoneChatMessageState)state {
    NSString *imageName = nil;
    _notDelivered = FALSE;
    if (state == LinphoneChatMessageStateDeliveredToUser) {
        imageName = @"chat_delivered.png";
        [_imdmIcon setHidden:FALSE];
    } else if (state == LinphoneChatMessageStateDisplayed) {
        imageName = @"chat_read";
        [_imdmIcon setHidden:FALSE];
    } else if (state == LinphoneChatMessageStateNotDelivered || state == LinphoneChatMessageStateFileTransferError) {
        imageName = @"chat_error";
        [_imdmIcon setHidden:FALSE];
        _notDelivered = TRUE;
    } else {
        [_imdmIcon setHidden:TRUE];
    }
    [_imdmIcon setImage:[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],imageName]]];
}
 
#pragma mark - Bubble size computing
 
+ (CGSize)computeBoundingBox:(NSString *)text size:(CGSize)size font:(UIFont *)font {
    if (!text || text.length == 0)
        return CGSizeMake(0, 0);
 
    return [text boundingRectWithSize:size
                              options:(NSStringDrawingUsesLineFragmentOrigin |
                                       NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading)
                           attributes:@{
                               NSFontAttributeName : font
                           }
                              context:nil].size;
}
 
static const CGFloat CELL_MIN_HEIGHT = 65.0f;
static const CGFloat CELL_MIN_WIDTH = 190.0f;
static const CGFloat CELL_MESSAGE_X_MARGIN = 68 + 10.0f;
static const CGFloat CELL_MESSAGE_Y_MARGIN = 44;
 
+ (CGSize)ViewHeightForMessage:(LinphoneChatMessage *)chat withWidth:(int)width {
    return [self ViewHeightForMessageText:chat withWidth:width textForImdn:nil];
}
 
+ (CGSize)ViewHeightForFile:(int)width {
    CGSize fileSize = CGSizeMake(230, 50);
    CGSize size = [self getMediaMessageSizefromOriginalSize:fileSize withWidth:width];
    size.width = MAX(size.width + CELL_MESSAGE_X_MARGIN, CELL_MIN_WIDTH);
    size.height = MAX(size.height + CELL_MESSAGE_Y_MARGIN, CELL_MIN_HEIGHT);
    return size;
}
 
+ (UIImage *)getImageFromContent:(LinphoneContent *)content filePath:(NSString *)filePath; {
    NSString *type = [NSString stringWithUTF8String:linphone_content_get_type(content)];
    NSString *name = [NSString stringWithUTF8String:linphone_content_get_name(content)];
    if (!filePath) {
        filePath = [LinphoneManager validFilePath:name];
    }
    
    UIImage *image = nil;
    if ([type isEqualToString:@"video"]) {
        image = [UIChatBubbleTextCell getImageFromVideoUrl:[NSURL fileURLWithPath:filePath]];
    } else if ([type isEqualToString:@"image"]) {
        NSData* data = [NSData dataWithContentsOfFile:filePath];
        image = [[UIImage alloc] initWithData:data];
    }
    if (image) return image;
    UIImage *basicImage = [ChatConversationView getBasicImage];
    image = [ChatConversationView drawText:[NSString stringWithFormat:@"📎 %@",name] image:basicImage textSize:25];
    return image;
}
 
 
+ (CGSize)ViewHeightForMessageText:(LinphoneChatMessage *)chat withWidth:(int)width textForImdn:(NSString *)imdnText {
    NSString *messageText = [UIChatBubbleTextCell TextMessageForChat:chat];
    static UIFont *messageFont = nil;
 
    if (!messageFont) {
        UIChatBubbleTextCell *cell =
            [[UIChatBubbleTextCell alloc] initWithIdentifier:NSStringFromClass(UIChatBubbleTextCell.class)];
        messageFont = cell.messageText.font;
    }
    width -= CELL_IMAGE_X_MARGIN;
    CGSize size;
    const char *url = linphone_chat_message_get_external_body_url(chat);
    
    if (imdnText) {
        size = [self computeBoundingBox:imdnText
                                   size:CGSizeMake(width - 4, CGFLOAT_MAX)
                                   font:messageFont];
        size.width = MAX(size.width + CELL_MESSAGE_X_MARGIN, CELL_MIN_WIDTH);
        size.height = MAX(size.height + CELL_MESSAGE_Y_MARGIN + 50, CELL_MIN_HEIGHT);
        return size;
    }
 
    CGFloat imagesw=0;
    CGFloat imagesh=0;
    CGFloat max_imagesw=0;
    CGFloat max_imagesh=0;
    const bctbx_list_t *contents = linphone_chat_message_get_contents(chat);
    BOOL multiParts = ((linphone_chat_message_get_text_content(chat) != NULL) ? bctbx_list_size(contents) > 2 : bctbx_list_size(contents) > 1);
    if (multiParts) {
        const bctbx_list_t *it = contents;
        NSMutableDictionary<NSString *, NSString *> *encrptedFilePaths = [LinphoneManager getMessageAppDataForKey:@"encryptedfiles" inMessage:chat];
 
        for (it = contents; it != NULL; it=bctbx_list_next(it)){
            LinphoneContent *content = (LinphoneContent *)it->data;
            UIImage *image;
            if(!linphone_chat_message_is_outgoing(chat) && linphone_content_is_file_transfer(content)) {
                // not yet downloaded
                UIImage *basicImage = [ChatConversationView getBasicImage];
                NSString *name = [NSString stringWithUTF8String:linphone_content_get_name(content)] ;
                image = [ChatConversationView drawText:name image:basicImage textSize:25];
            } else if (linphone_content_is_file_transfer(content) || linphone_content_is_file(content)) {
                NSString *name = [NSString stringWithUTF8String:linphone_content_get_name(content)];
                NSString *filePath=[encrptedFilePaths valueForKey:name];
                if (filePath == NULL) {
                    filePath = [LinphoneManager validFilePath:name];
                }
 
                image = [UIChatBubbleTextCell getImageFromContent:content filePath:filePath];
            }
            if (image) {
                CGSize sSize = [self getMediaMessageSizefromOriginalSize:image.size withWidth:IMAGE_DEFAULT_WIDTH];
                imagesw += sSize.width;
                if (imagesw > width) {
                    imagesw = sSize.width;
                    max_imagesw = MAX(max_imagesw, imagesw);
                    max_imagesh += imagesh;
                    imagesh = sSize.height;
                } else {
                    max_imagesw = MAX(max_imagesw, imagesw);
                    imagesh = MAX(imagesh, sSize.height);
                }
            }
        }
        max_imagesh += imagesh;
 
        size = CGSizeMake(max_imagesw, max_imagesh);
        CGSize textSize = CGSizeMake(0, 0);
        if (![messageText isEqualToString:@"🗻"]) {
            textSize = [self computeBoundingBox:messageText
                                           size:CGSizeMake(max_imagesw , CGFLOAT_MAX)
                                           font:messageFont];
        }
        
        // add size for message text
        size.height += textSize.height;
        size.width = MAX(textSize.width, size.width);
        size.width = MAX(size.width + CELL_MESSAGE_X_MARGIN, CELL_MIN_WIDTH);
        size.height = MAX(size.height + CELL_MESSAGE_Y_MARGIN, CELL_MIN_HEIGHT) ;
        return size;
    }
 
 
    LinphoneContent *fileContent = linphone_chat_message_get_file_transfer_information(chat);
    if (url == nil && fileContent == NULL) {
        size = [self computeBoundingBox:messageText
                                    size:CGSizeMake(width - CELL_MESSAGE_X_MARGIN - 4, CGFLOAT_MAX)
                                    font:messageFont];
    } else {
        NSString *localImage = [LinphoneManager getMessageAppDataForKey:@"localimage" inMessage:chat];
        NSString *localFile = [LinphoneManager getMessageAppDataForKey:@"localfile" inMessage:chat];
        NSString *localVideo = [LinphoneManager getMessageAppDataForKey:@"localvideo" inMessage:chat];
        NSString *filePath = [LinphoneManager getMessageAppDataForKey:@"encryptedfile" inMessage:chat];
        NSString *fileName = [NSString stringWithUTF8String:linphone_content_get_name(fileContent)];
        
        CGSize textSize = CGSizeMake(0, 0);
        if (![messageText isEqualToString:@"🗻"]) {
            textSize = [self computeBoundingBox:messageText
                                           size:CGSizeMake(width - CELL_MESSAGE_X_MARGIN - 4, CGFLOAT_MAX)
                                           font:messageFont];
            size.height += textSize.height;
        }
 
        CGSize originalImageSize = CGSizeMake(230, 50);
        if (!filePath) {
            filePath = [LinphoneManager validFilePath:fileName];
        }
        if (localFile) {
            UIImage *image = nil;
            NSString *type = [NSString stringWithUTF8String:linphone_content_get_type(fileContent)];
            
            if ([type isEqualToString:@"video"]) {
                if ([[NSFileManager defaultManager] fileExistsAtPath: filePath]) {
                    image = [self getImageFromVideoUrl:[NSURL fileURLWithPath:filePath]];
                } else {
                    image = [self getImageFromVideoUrl:[VIEW(ChatConversationView) getICloudFileUrl:localFile]];
                }
            } else if ([localFile hasSuffix:@"JPG"] || [localFile hasSuffix:@"PNG"] || [localFile hasSuffix:@"jpg"] || [localFile hasSuffix:@"png"]) {
                if ([[NSFileManager defaultManager] fileExistsAtPath: filePath]) {
                    NSData *data = [NSData dataWithContentsOfFile:filePath];
                    image = [[UIImage alloc] initWithData:data];
                } else {
                    NSData *data = [NSData dataWithContentsOfURL:[VIEW(ChatConversationView) getICloudFileUrl:localFile]];
                    image = [[UIImage alloc] initWithData:data];
                }
            } else {
                return [self ViewHeightForFile:width];
            }
 
            originalImageSize = image.size;
        } else {
            if (!localImage && !localVideo) {
                //We are loading the image
                return CGSizeMake(CELL_MIN_WIDTH + CELL_MESSAGE_X_MARGIN, CELL_MIN_HEIGHT + CELL_MESSAGE_Y_MARGIN + textSize.height + 20);
            }
 
            if (localImage && [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                NSData* data = [NSData dataWithContentsOfFile:filePath];
                UIImage *image = [[UIImage alloc] initWithData:data];
                if (!image) {
                    return [self ViewHeightForFile:width];
                }
                originalImageSize = image.size;
            } else if (localVideo && [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                UIImage *image = [UIChatBubbleTextCell getImageFromVideoUrl:[NSURL fileURLWithPath:filePath]];
                if (!image) {
                    return [self ViewHeightForFile:width];
                }
                originalImageSize = image.size;
            } else {
                // support previous versions
                PHFetchResult<PHAsset *> *assets;
                if(localImage)
                    assets = [LinphoneManager getPHAssets:localImage];
                else
                    assets = [PHAsset fetchAssetsWithLocalIdentifiers:[NSArray arrayWithObject:localVideo] options:nil];
 
                if (![assets firstObject]) {
                    return CGSizeMake(CELL_MIN_WIDTH, CELL_MIN_WIDTH + CELL_MESSAGE_Y_MARGIN + textSize.height);
                } else {
                    PHAsset *asset = [assets firstObject];
                    originalImageSize = CGSizeMake([asset pixelWidth], [asset pixelHeight]);
                }
            }
        }
        size = [self getMediaMessageSizefromOriginalSize:originalImageSize withWidth:width];
        // add size for message text
        size.height += textSize.height;
        size.width = MAX(textSize.width, size.width);
    }
 
    size.width = MAX(size.width + CELL_MESSAGE_X_MARGIN, CELL_MIN_WIDTH);
    size.height = MAX(size.height + CELL_MESSAGE_Y_MARGIN, CELL_MIN_HEIGHT);
    return size;
}
 
+ (CGSize)ViewSizeForMessage:(LinphoneChatMessage *)chat withWidth:(int)width {
    static UIFont *dateFont = nil;
    static CGSize dateViewSize;
 
    if (!dateFont) {
        UIChatBubbleTextCell *cell =
            [[UIChatBubbleTextCell alloc] initWithIdentifier:NSStringFromClass(UIChatBubbleTextCell.class)];
        dateFont = cell.contactDateLabel.font;
        dateViewSize = cell.contactDateLabel.frame.size;
        dateViewSize.width = CGFLOAT_MAX;
    }
 
    CGSize messageSize = [self ViewHeightForMessage:chat withWidth:width];
    CGSize dateSize = [self computeBoundingBox:[self ContactDateForChat:chat] size:dateViewSize font:dateFont];
    messageSize.width = MAX(MAX(messageSize.width, MIN(dateSize.width + CELL_MESSAGE_X_MARGIN, width)), CELL_MIN_WIDTH);
    messageSize.width = MAX(MAX(messageSize.width, MIN(CELL_MESSAGE_X_MARGIN, width)), CELL_MIN_WIDTH);
 
    return messageSize;
}
 
+ (UIImage *)getImageFromVideoUrl:(NSURL *)url {
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVAssetImageGenerator* generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    return [UIImage imageWithCGImage:[generator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil]];
}
 
- (void)layoutSubviews {
    [super layoutSubviews];
    if (_message != nil) {
        UITableView *tableView = VIEW(ChatConversationView).tableController.tableView;
        BOOL is_outgoing = linphone_chat_message_is_outgoing(_message);
        CGRect bubbleFrame = _bubbleView.frame;
        int available_width = self.frame.size.width;
        int origin_x;
 
        bubbleFrame.size = [self.class ViewSizeForMessage:_message withWidth:available_width];
 
        if (tableView.isEditing) {
            origin_x = 0;
        } else {
            origin_x = (is_outgoing ? self.frame.size.width - bubbleFrame.size.width : 0);
        }
 
        bubbleFrame.origin.x = origin_x;
        _bubbleView.frame = bubbleFrame;
    }
}
 
 
+ (CGSize)getMediaMessageSizefromOriginalSize:(CGSize)originalSize withWidth:(int)width {
    CGSize mediaSize = CGSizeMake(0, 0);
    int availableWidth = width;
    if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]) || IPAD) {
        availableWidth = availableWidth /1.7;
    }
    
    int newHeight = originalSize.height;
    float originalAspectRatio = originalSize.width / originalSize.height;
    // We resize in width and crop in height
    if (originalSize.width > availableWidth) {
        newHeight = availableWidth / originalAspectRatio;
    }
    
    if (newHeight > availableWidth) {
        newHeight = availableWidth;
        availableWidth = newHeight * originalAspectRatio;
    }
    mediaSize.height = newHeight;
    mediaSize.width = MIN(availableWidth, originalSize.width);
    return mediaSize;
}
 
@end