WFCUMessageListViewController.m 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  1. //
  2. // MessageListViewController.m
  3. // WFChat UIKit
  4. //
  5. // Created by WF Chat on 2017/8/31.
  6. // Copyright © 2017年 WildFireChat. All rights reserved.
  7. //
  8. #import "WFCUMessageListViewController.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. #import "WFCUImagePreviewViewController.h"
  11. #import "WFCUVoiceRecordView.h"
  12. #import "WFCUImageCell.h"
  13. #import "WFCUTextCell.h"
  14. #import "WFCUVoiceCell.h"
  15. #import "WFCULocationCell.h"
  16. #import "WFCUFileCell.h"
  17. #import "WFCUInformationCell.h"
  18. #import "WFCUCallSummaryCell.h"
  19. #import "WFCUStickerCell.h"
  20. #import "WFCUVideoCell.h"
  21. #import "WFCURecallCell.h"
  22. #import "WFCUConferenceInviteCell.h"
  23. #import "WFCUCardCell.h"
  24. #import "WFCUBrowserViewController.h"
  25. #import <WFChatClient/WFCChatClient.h>
  26. #import "WFCUProfileTableViewController.h"
  27. #import "WFCUMultiVideoViewController.h"
  28. #import "WFCUChatInputBar.h"
  29. #import "UIView+Toast.h"
  30. #import "WFCUConversationSettingViewController.h"
  31. #import "SDPhotoBrowser.h"
  32. #import "WFCULocationViewController.h"
  33. #import "WFCULocationPoint.h"
  34. #import "WFCUVideoViewController.h"
  35. #import "WFCUContactListViewController.h"
  36. #import "WFCUBrowserViewController.h"
  37. #import "MBProgressHUD.h"
  38. #import "WFCUMediaMessageDownloader.h"
  39. #import "VideoPlayerKit.h"
  40. #import "WFCUForwardViewController.h"
  41. #import <WFChatClient/WFCChatClient.h>
  42. #if WFCU_SUPPORT_VOIP
  43. #import <WFAVEngineKit/WFAVEngineKit.h>
  44. #endif
  45. #import "WFCUConfigManager.h"
  46. #import "WFCUSeletedUserViewController.h"
  47. #import "WFCUReceiptViewController.h"
  48. #import "UIColor+YH.h"
  49. #import "WFCUConversationTableViewController.h"
  50. #import "WFCUConversationSearchTableViewController.h"
  51. #import "WFCUMediaMessageGridViewController.h"
  52. #import "WFCUConferenceViewController.h"
  53. @interface WFCUMessageListViewController () <UITextFieldDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UINavigationControllerDelegate, WFCUMessageCellDelegate, AVAudioPlayerDelegate, WFCUChatInputBarDelegate, SDPhotoBrowserDelegate, UIGestureRecognizerDelegate>
  54. @property (nonatomic, strong)NSMutableArray<WFCUMessageModel *> *modelList;
  55. @property (nonatomic, strong)NSMutableArray<WFCCMessage *> *mentionedMsgs;
  56. @property (nonatomic, strong)NSMutableDictionary<NSNumber *, Class> *cellContentDict;
  57. @property(nonatomic) AVAudioPlayer *player;
  58. @property(nonatomic) NSTimer *playTimer;
  59. @property(nonatomic, assign)long playingMessageId;
  60. @property(nonatomic, assign)BOOL loadingMore;
  61. @property(nonatomic, assign)BOOL hasMoreOld;
  62. @property(nonatomic, strong)WFCCUserInfo *targetUser;
  63. @property(nonatomic, strong)WFCCGroupInfo *targetGroup;
  64. @property(nonatomic, strong)WFCCChannelInfo *targetChannel;
  65. @property(nonatomic, strong)WFCCChatroomInfo *targetChatroom;
  66. @property(nonatomic, strong)WFCUChatInputBar *chatInputBar;
  67. @property(nonatomic, strong)VideoPlayerKit *videoPlayerViewController;
  68. @property (strong, nonatomic) UICollectionView *collectionView;
  69. @property (strong, nonatomic)NSArray<WFCCMessage *> *imageMsgs;
  70. @property (strong, nonatomic)NSString *orignalDraft;
  71. @property (nonatomic, strong)id<UIGestureRecognizerDelegate> scrollBackDelegate;
  72. @property (nonatomic, strong)UIView *backgroundView;
  73. @property (nonatomic, assign)BOOL showAlias;
  74. @property (nonatomic, strong)WFCUMessageCellBase *cell4Menu;
  75. @property (nonatomic, assign)BOOL firstAppear;
  76. @property (nonatomic, assign)BOOL hasNewMessage;
  77. @property (nonatomic, assign)BOOL loadingNew;
  78. @property (nonatomic, strong)UICollectionReusableView *headerView;
  79. @property (nonatomic, strong)UICollectionReusableView *footerView;
  80. @property (nonatomic, strong)UIActivityIndicatorView *headerActivityView;
  81. @property (nonatomic, strong)UIActivityIndicatorView *footerActivityView;
  82. @property (nonatomic, strong)NSTimer *showTypingTimer;
  83. @property (nonatomic, assign)BOOL isShowingKeyboard;
  84. @property (nonatomic, strong)NSMutableDictionary<NSString *, NSNumber *> *deliveryDict;
  85. @property (nonatomic, strong)NSMutableDictionary<NSString *, NSNumber *> *readDict;
  86. @property (nonatomic, strong)UIView *multiSelectPanel;
  87. @end
  88. @implementation WFCUMessageListViewController
  89. - (void)viewDidLoad {
  90. [super viewDidLoad];
  91. [self removeControllerStackIfNeed];
  92. self.cellContentDict = [[NSMutableDictionary alloc] init];
  93. [self initializedSubViews];
  94. self.firstAppear = YES;
  95. self.hasMoreOld = YES;
  96. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onResetKeyboard:)];
  97. [self.collectionView addGestureRecognizer:tap];
  98. [self reloadMessageList];
  99. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceiveMessages:) name:kReceiveMessages object:nil];
  100. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRecallMessages:) name:kRecallMessages object:nil];
  101. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeleteMessages:) name:kDeleteMessages object:nil];
  102. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageDelivered:) name:kMessageDelivered object:nil];
  103. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReaded:) name:kMessageReaded object:nil];
  104. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSendingMessage:) name:kSendingMessageStatusUpdated object:nil];
  105. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageListChanged:) name:kMessageListChanged object:self.conversation];
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMenuHidden:) name:UIMenuControllerDidHideMenuNotification object:nil];
  107. #if WFCU_SUPPORT_VOIP
  108. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCallStateChanged:) name:kCallStateUpdated object:nil];
  109. #endif
  110. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSettingUpdated:) name:kSettingUpdated object:nil];
  111. __weak typeof(self) ws = self;
  112. if(self.conversation.type == Single_Type) {
  113. [[NSNotificationCenter defaultCenter] addObserverForName:kUserInfoUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
  114. if ([ws.conversation.target isEqualToString:note.object]) {
  115. ws.targetUser = note.userInfo[@"userInfo"];
  116. }
  117. }];
  118. } else if(self.conversation.type == Group_Type) {
  119. [[NSNotificationCenter defaultCenter] addObserverForName:kGroupInfoUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
  120. if ([ws.conversation.target isEqualToString:note.object]) {
  121. ws.targetGroup = note.userInfo[@"groupInfo"];
  122. }
  123. }];
  124. [[NSNotificationCenter defaultCenter] addObserverForName:kGroupMemberUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
  125. if ([ws.conversation.target isEqualToString:note.object]) {
  126. ws.targetGroup = ws.targetGroup;
  127. }
  128. }];
  129. } else if(self.conversation.type == Channel_Type) {
  130. [[NSNotificationCenter defaultCenter] addObserverForName:kChannelInfoUpdated object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
  131. if ([ws.conversation.target isEqualToString:note.object]) {
  132. ws.targetChannel = note.userInfo[@"channelInfo"];
  133. }
  134. }];
  135. }
  136. [self setupNavigationItem];
  137. self.chatInputBar = [[WFCUChatInputBar alloc] initWithSuperView:self.backgroundView conversation:self.conversation delegate:self];
  138. self.orignalDraft = [[WFCCIMService sharedWFCIMService] getConversationInfo:self.conversation].draft;
  139. if (self.conversation.type == Chatroom_Type) {
  140. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
  141. hud.label.text = WFCString(@"JoinChatroom");
  142. [hud showAnimated:YES];
  143. [[WFCCIMService sharedWFCIMService] joinChatroom:ws.conversation.target success:^{
  144. NSLog(@"join chatroom successs");
  145. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  146. [ws sendChatroomWelcomeMessage];
  147. });
  148. [hud hideAnimated:YES];
  149. } error:^(int error_code) {
  150. NSLog(@"join chatroom error");
  151. hud.mode = MBProgressHUDModeText;
  152. hud.label.text = WFCString(@"JoinChatroomFailure");
  153. // hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
  154. [hud hideAnimated:YES afterDelay:1.f];
  155. hud.completionBlock = ^{
  156. [ws.navigationController popViewControllerAnimated:YES];
  157. };
  158. }];
  159. }
  160. WFCCConversationInfo *info = [[WFCCIMService sharedWFCIMService] getConversationInfo:self.conversation];
  161. self.chatInputBar.draft = info.draft;
  162. if (self.conversation.type == Group_Type) {
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. NSArray<WFCCGroupMember *> *groupMembers = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  165. NSMutableArray *memberIds = [[NSMutableArray alloc] init];
  166. for (WFCCGroupMember *member in groupMembers) {
  167. [memberIds addObject:member.memberId];
  168. }
  169. [[WFCCIMService sharedWFCIMService] getUserInfos:memberIds inGroup:self.conversation.target];
  170. });
  171. }
  172. if (self.multiSelecting) {
  173. self.multiSelectPanel.hidden = NO;
  174. }
  175. }
  176. //The VC maybe pushed from search VC, so no need go back to search VC, need remove all the VC between current VC to WFCUConversationTableViewController
  177. - (void)removeControllerStackIfNeed {
  178. //highlightMessageId will be positive if the VC pushed from search VC
  179. if (self.highlightMessageId > 0) {
  180. if (self.navigationController.viewControllers.count < 3) {
  181. return;
  182. }
  183. NSMutableArray *controllers = [self.navigationController.viewControllers mutableCopy];
  184. BOOL foundParent = NO;
  185. NSMutableArray *tobeDeleteVCs = [[NSMutableArray alloc] init];
  186. for (int i = (int)controllers.count - 2; i >=0; i--) {
  187. UIViewController *controller = controllers[i];
  188. if ([controller isKindOfClass:[WFCUConversationTableViewController class]]) {
  189. foundParent = YES;
  190. break;
  191. } else {
  192. [tobeDeleteVCs addObject:controller];
  193. }
  194. }
  195. if (foundParent) {
  196. [controllers removeObjectsInArray:tobeDeleteVCs];
  197. self.navigationController.viewControllers = [controllers copy];
  198. }
  199. }
  200. }
  201. - (void)setupNavigationItem {
  202. if (self.multiSelecting) {
  203. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStyleDone target:self action:@selector(onSearchBarBtn:)];
  204. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(onMultiSelectCancel:)];
  205. } else {
  206. if(self.conversation.type == Single_Type) {
  207. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_chat_single"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  208. } else if(self.conversation.type == Group_Type) {
  209. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_chat_group"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  210. } else if(self.conversation.type == Channel_Type) {
  211. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_chat_channel"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  212. }
  213. self.navigationItem.leftBarButtonItem = nil;
  214. }
  215. }
  216. - (void)onMultiSelectCancel:(id)sender {
  217. self.multiSelecting = !self.multiSelecting;
  218. }
  219. - (void)setLoadingMore:(BOOL)loadingMore {
  220. _loadingMore = loadingMore;
  221. if (_loadingMore) {
  222. [self.headerActivityView startAnimating];
  223. } else {
  224. [self.headerActivityView stopAnimating];
  225. }
  226. }
  227. - (UIActivityIndicatorView *)headerActivityView {
  228. if (!_headerActivityView) {
  229. _headerActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  230. }
  231. return _headerActivityView;
  232. }
  233. - (UIActivityIndicatorView *)footerActivityView {
  234. if (!_footerActivityView) {
  235. _footerActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  236. }
  237. return _footerActivityView;
  238. }
  239. - (void)setLoadingNew:(BOOL)loadingNew {
  240. _loadingNew = loadingNew;
  241. if (loadingNew) {
  242. [self.footerActivityView startAnimating];
  243. } else {
  244. [self.footerActivityView stopAnimating];
  245. }
  246. }
  247. - (void)setHasNewMessage:(BOOL)hasNewMessage {
  248. _hasNewMessage = hasNewMessage;
  249. UICollectionViewFlowLayout *_customFlowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
  250. if (hasNewMessage) {
  251. _customFlowLayout.footerReferenceSize = CGSizeMake(320.0f, 20.0f);
  252. } else {
  253. _customFlowLayout.footerReferenceSize = CGSizeZero;
  254. }
  255. }
  256. - (void)loadMoreMessage:(BOOL)isHistory {
  257. __weak typeof(self) weakSelf = self;
  258. if (isHistory) {
  259. if (self.loadingMore) {
  260. return;
  261. }
  262. self.loadingMore = YES;
  263. long lastIndex = 0;
  264. if (weakSelf.modelList.count) {
  265. lastIndex = [weakSelf.modelList firstObject].message.messageId;
  266. }
  267. dispatch_async(dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
  268. NSArray *messageList = [[WFCCIMService sharedWFCIMService] getMessages:weakSelf.conversation contentTypes:nil from:lastIndex count:10 withUser:self.privateChatUser];
  269. if (!messageList.count) {
  270. long long lastUid = self.modelList.lastObject.message.messageUid;
  271. for (WFCUMessageModel *model in self.modelList) {
  272. if (model.message.messageUid > 0 && model.message.messageUid < lastUid) {
  273. lastUid = model.message.messageUid;
  274. }
  275. }
  276. [[WFCCIMService sharedWFCIMService] getRemoteMessages:weakSelf.conversation before:lastUid count:10 success:^(NSArray<WFCCMessage *> *messages) {
  277. NSMutableArray *reversedMsgs = [[NSMutableArray alloc] init];
  278. for (WFCCMessage *msg in messages) {
  279. [reversedMsgs insertObject:msg atIndex:0];
  280. }
  281. dispatch_async(dispatch_get_main_queue(), ^{
  282. if (!reversedMsgs.count) {
  283. weakSelf.hasMoreOld = NO;
  284. } else {
  285. [weakSelf appendMessages:reversedMsgs newMessage:NO highlightId:0 forceButtom:NO];
  286. }
  287. weakSelf.loadingMore = NO;
  288. });
  289. } error:^(int error_code) {
  290. dispatch_async(dispatch_get_main_queue(), ^{
  291. weakSelf.hasMoreOld = NO;
  292. weakSelf.loadingMore = NO;
  293. });
  294. }];
  295. } else {
  296. [NSThread sleepForTimeInterval:0.5];
  297. dispatch_async(dispatch_get_main_queue(), ^{
  298. [weakSelf appendMessages:messageList newMessage:NO highlightId:0 forceButtom:NO];
  299. weakSelf.loadingMore = NO;
  300. });
  301. }
  302. });
  303. } else {
  304. if (weakSelf.loadingNew || !weakSelf.hasNewMessage) {
  305. return;
  306. }
  307. weakSelf.loadingNew = YES;
  308. long lastIndex = 0;
  309. if (self.modelList.count) {
  310. lastIndex = [self.modelList lastObject].message.messageId;
  311. }
  312. dispatch_async(dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
  313. NSArray *messageList = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:lastIndex count:-10 withUser:self.privateChatUser];
  314. if (!messageList.count || messageList.count < 10) {
  315. self.hasNewMessage = NO;
  316. }
  317. NSMutableArray *mutableMessages = [messageList mutableCopy];
  318. for (int i = 0; i < mutableMessages.count/2; i++) {
  319. int j = (int)mutableMessages.count - 1 - i;
  320. WFCCMessage *msg = [mutableMessages objectAtIndex:i];
  321. [mutableMessages insertObject:[mutableMessages objectAtIndex:j] atIndex:i];
  322. [mutableMessages removeObjectAtIndex:i+1];
  323. [mutableMessages insertObject:msg atIndex:j];
  324. [mutableMessages removeObjectAtIndex:j+1];
  325. }
  326. [NSThread sleepForTimeInterval:0.5];
  327. dispatch_async(dispatch_get_main_queue(), ^{
  328. [weakSelf appendMessages:mutableMessages newMessage:YES highlightId:0 forceButtom:NO];
  329. weakSelf.loadingNew = NO;
  330. });
  331. });
  332. }
  333. }
  334. - (void)sendChatroomWelcomeMessage {
  335. WFCCTipNotificationContent *tip = [[WFCCTipNotificationContent alloc] init];
  336. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];
  337. tip.tip = [NSString stringWithFormat:WFCString(@"WelcomeJoinChatroomHint"), userInfo.displayName];
  338. [self sendMessage:tip];
  339. }
  340. - (void)sendChatroomLeaveMessage {
  341. __block WFCCConversation *strongConv = self.conversation;
  342. dispatch_async(dispatch_get_main_queue(), ^{
  343. WFCCTipNotificationContent *tip = [[WFCCTipNotificationContent alloc] init];
  344. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];
  345. tip.tip = [NSString stringWithFormat:WFCString(@"LeaveChatroomHint"), userInfo.displayName];
  346. [[WFCCIMService sharedWFCIMService] send:strongConv content:tip success:^(long long messageUid, long long timestamp) {
  347. [[WFCCIMService sharedWFCIMService] quitChatroom:strongConv.target success:nil error:nil];
  348. } error:^(int error_code) {
  349. }];
  350. });
  351. }
  352. - (void)onLeftBtnPressed:(id)sender {
  353. [self.navigationController popViewControllerAnimated:YES];
  354. }
  355. - (void)didMoveToParentViewController:(UIViewController*)parent
  356. {
  357. [super didMoveToParentViewController:parent];
  358. if(!parent){
  359. [self leftMessageVC];
  360. }
  361. }
  362. - (void)leftMessageVC {
  363. if (self.conversation.type == Chatroom_Type) {
  364. [self sendChatroomLeaveMessage];
  365. }
  366. }
  367. - (void)onRightBarBtn:(UIBarButtonItem *)sender {
  368. WFCUConversationSettingViewController *gvc = [[WFCUConversationSettingViewController alloc] init];
  369. gvc.conversation = self.conversation;
  370. [self.navigationController pushViewController:gvc animated:YES];
  371. }
  372. - (void)onSearchBarBtn:(id)sender {
  373. if (self.multiSelecting) {
  374. for (WFCUMessageModel *model in self.modelList) {
  375. if (model.selected && ![self.selectedMessageIds containsObject:@(model.message.messageId)]) {
  376. [self.selectedMessageIds addObject:@(model.message.messageId)];
  377. }
  378. }
  379. WFCUConversationSearchTableViewController *mvc = [[WFCUConversationSearchTableViewController alloc] init];
  380. mvc.conversation = self.conversation;
  381. mvc.hidesBottomBarWhenPushed = YES;
  382. mvc.messageSelecting = YES;
  383. mvc.selectedMessageIds = self.selectedMessageIds;
  384. [self.navigationController pushViewController:mvc animated:YES];
  385. }
  386. }
  387. - (void)setTargetUser:(WFCCUserInfo *)targetUser {
  388. _targetUser = targetUser;
  389. if(targetUser.friendAlias.length) {
  390. self.title = targetUser.friendAlias;
  391. } else if(targetUser.displayName.length == 0) {
  392. self.title = [NSString stringWithFormat:@"%@<%@>", WFCString(@"User"), self.conversation.target];
  393. } else {
  394. self.title = targetUser.displayName;
  395. }
  396. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  397. self.navigationItem.backBarButtonItem.title = self.title;
  398. }
  399. - (void)setTargetGroup:(WFCCGroupInfo *)targetGroup {
  400. _targetGroup = targetGroup;
  401. if(targetGroup.name.length == 0) {
  402. self.title = WFCString(@"GroupChat");
  403. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  404. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  405. } else {
  406. self.title = [NSString stringWithFormat:@"%@(%d)", targetGroup.name, (int)targetGroup.memberCount];
  407. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  408. self.navigationItem.backBarButtonItem.title = targetGroup.name;
  409. }
  410. ChatInputBarStatus defaultStatus = ChatInputBarDefaultStatus;
  411. WFCCGroupMember *member = [[WFCCIMService sharedWFCIMService] getGroupMember:targetGroup.target memberId:[WFCCNetworkService sharedInstance].userId];
  412. if (targetGroup.mute || member.type == Member_Type_Muted) {
  413. if ([targetGroup.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  414. self.chatInputBar.inputBarStatus = defaultStatus;
  415. } else if(targetGroup.mute && member.type == Member_Type_Allowed) {
  416. self.chatInputBar.inputBarStatus = defaultStatus;
  417. } else {
  418. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:targetGroup.target memberId:[WFCCNetworkService sharedInstance].userId];
  419. if (gm.type == Member_Type_Manager) {
  420. self.chatInputBar.inputBarStatus = defaultStatus;
  421. } else {
  422. self.chatInputBar.inputBarStatus = ChatInputBarMuteStatus;
  423. }
  424. }
  425. } else {
  426. self.chatInputBar.inputBarStatus = defaultStatus;
  427. }
  428. }
  429. - (void)setTargetChannel:(WFCCChannelInfo *)targetChannel {
  430. _targetChannel = targetChannel;
  431. if(targetChannel.name.length == 0) {
  432. self.title = WFCString(@"Channel");
  433. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  434. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  435. } else {
  436. self.title = targetChannel.name;
  437. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  438. self.navigationItem.backBarButtonItem.title = targetChannel.name;
  439. }
  440. }
  441. - (void)setTargetChatroom:(WFCCChatroomInfo *)targetChatroom {
  442. _targetChatroom = targetChatroom;
  443. if(targetChatroom.title.length == 0) {
  444. self.title = WFCString(@"Chatroom");
  445. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  446. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  447. } else {
  448. self.title = targetChatroom.title;
  449. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  450. self.navigationItem.backBarButtonItem.title = targetChatroom.title;
  451. }
  452. }
  453. - (void)setShowAlias:(BOOL)showAlias {
  454. _showAlias = showAlias;
  455. if (self.modelList) {
  456. for (WFCUMessageModel *model in self.modelList) {
  457. if (showAlias && model.message.direction == MessageDirection_Receive) {
  458. model.showNameLabel = YES;
  459. } else {
  460. model.showNameLabel = NO;
  461. }
  462. }
  463. }
  464. }
  465. - (void)setMultiSelecting:(BOOL)multiSelecting {
  466. _multiSelecting = multiSelecting;
  467. if (multiSelecting) {
  468. for (WFCUMessageModel *model in self.modelList) {
  469. model.selecting = YES;
  470. model.selected = NO;
  471. }
  472. if (!self.selectedMessageIds) {
  473. self.selectedMessageIds = [[NSMutableArray alloc] init];
  474. }
  475. self.multiSelectPanel.hidden = NO;
  476. } else {
  477. for (WFCUMessageModel *model in self.modelList) {
  478. model.selecting = NO;
  479. model.selected = NO;
  480. }
  481. self.selectedMessageIds = nil;
  482. self.multiSelectPanel.hidden = YES;
  483. }
  484. [self setupNavigationItem];
  485. [self.collectionView reloadData];
  486. }
  487. - (UIView *)multiSelectPanel {
  488. if (!_multiSelectPanel) {
  489. if (!self.backgroundView) {
  490. return nil;
  491. }
  492. _multiSelectPanel = [[UIView alloc] initWithFrame:CGRectMake(0, self.backgroundView.bounds.size.height - CHAT_INPUT_BAR_HEIGHT, self.backgroundView.bounds.size.width, CHAT_INPUT_BAR_HEIGHT)];
  493. _multiSelectPanel.backgroundColor = [UIColor colorWithHexString:@"0xf7f7f7"];
  494. UIButton *deleteBtn = [[UIButton alloc] initWithFrame:_multiSelectPanel.bounds];
  495. [deleteBtn setTitle:@"Delete" forState:UIControlStateNormal];
  496. [deleteBtn addTarget:self action:@selector(onDeleteMultiSelectedMessage:) forControlEvents:UIControlEventTouchDown];
  497. [deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  498. [_multiSelectPanel addSubview:deleteBtn];
  499. [self.backgroundView addSubview:_multiSelectPanel];
  500. }
  501. return _multiSelectPanel;
  502. }
  503. - (void)onDeleteMultiSelectedMessage:(id)sender {
  504. NSMutableArray *deletedModels = [[NSMutableArray alloc] init];
  505. for (WFCUMessageModel *model in self.modelList) {
  506. if (model.selected) {
  507. [[WFCCIMService sharedWFCIMService] deleteMessage:model.message.messageId];
  508. [deletedModels addObject:model];
  509. [self.selectedMessageIds removeObject:@(model.message.messageId)];
  510. }
  511. }
  512. [self.modelList removeObjectsInArray:deletedModels];
  513. //有可能是经过多次搜索,选中了当前model列表中没有包含的
  514. for (NSNumber *IDS in self.selectedMessageIds) {
  515. [[WFCCIMService sharedWFCIMService] deleteMessage:[IDS longValue]];
  516. }
  517. self.multiSelecting = NO;
  518. }
  519. - (void)scrollToBottom:(BOOL)animated {
  520. NSUInteger rowCount = [self.collectionView numberOfItemsInSection:0];
  521. if (rowCount == 0) {
  522. return;
  523. }
  524. NSUInteger finalRow = rowCount - 1;
  525. for (int i = 0; i < self.modelList.count; i++) {
  526. if ([self.modelList objectAtIndex:i].highlighted) {
  527. finalRow = i;
  528. break;
  529. }
  530. }
  531. NSIndexPath *finalIndexPath = [NSIndexPath indexPathForItem:finalRow inSection:0];
  532. [self.collectionView scrollToItemAtIndexPath:finalIndexPath
  533. atScrollPosition:UICollectionViewScrollPositionBottom
  534. animated:animated];
  535. }
  536. - (void)initializedSubViews {
  537. UICollectionViewFlowLayout *_customFlowLayout = [[UICollectionViewFlowLayout alloc] init];
  538. _customFlowLayout.minimumLineSpacing = 0.0f;
  539. _customFlowLayout.sectionInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
  540. _customFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
  541. _customFlowLayout.headerReferenceSize = CGSizeMake(320.0f, 20.0f);
  542. UIEdgeInsets insets = UIEdgeInsetsZero;
  543. if (@available(iOS 11.0, *)) {
  544. insets = self.view.safeAreaInsets;
  545. }
  546. CGRect frame = self.view.bounds;
  547. frame.origin.y += kStatusBarAndNavigationBarHeight;
  548. frame.size.height -= (kTabbarSafeBottomMargin + kStatusBarAndNavigationBarHeight);
  549. self.backgroundView = [[UIView alloc] initWithFrame:frame];
  550. [self.view addSubview:self.backgroundView];
  551. self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.backgroundView.bounds.size.width, self.backgroundView.bounds.size.height - CHAT_INPUT_BAR_HEIGHT) collectionViewLayout:_customFlowLayout];
  552. [self.backgroundView addSubview:self.collectionView];
  553. self.backgroundView.backgroundColor = [UIColor whiteColor];
  554. self.collectionView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
  555. self.collectionView.showsHorizontalScrollIndicator = NO;
  556. self.collectionView.showsVerticalScrollIndicator = NO;
  557. self.collectionView.alwaysBounceVertical = YES;
  558. self.view.backgroundColor = self.collectionView.backgroundColor;
  559. [self registerCell:[WFCUTextCell class] forContent:[WFCCTextMessageContent class]];
  560. [self registerCell:[WFCUTextCell class] forContent:[WFCCPTextMessageContent class]];
  561. [self registerCell:[WFCUImageCell class] forContent:[WFCCImageMessageContent class]];
  562. [self registerCell:[WFCUVoiceCell class] forContent:[WFCCSoundMessageContent class]];
  563. [self registerCell:[WFCUVideoCell class] forContent:[WFCCVideoMessageContent class]];
  564. [self registerCell:[WFCULocationCell class] forContent:[WFCCLocationMessageContent class]];
  565. [self registerCell:[WFCUFileCell class] forContent:[WFCCFileMessageContent class]];
  566. [self registerCell:[WFCUStickerCell class] forContent:[WFCCStickerMessageContent class]];
  567. [self registerCell:[WFCUInformationCell class] forContent:[WFCCCreateGroupNotificationContent class]];
  568. [self registerCell:[WFCUInformationCell class] forContent:[WFCCAddGroupeMemberNotificationContent class]];
  569. [self registerCell:[WFCUInformationCell class] forContent:[WFCCKickoffGroupMemberNotificaionContent class]];
  570. [self registerCell:[WFCUInformationCell class] forContent:[WFCCQuitGroupNotificationContent class]];
  571. [self registerCell:[WFCUInformationCell class] forContent:[WFCCDismissGroupNotificationContent class]];
  572. [self registerCell:[WFCUInformationCell class] forContent:[WFCCTransferGroupOwnerNotificationContent class]];
  573. [self registerCell:[WFCUInformationCell class] forContent:[WFCCModifyGroupAliasNotificationContent class]];
  574. [self registerCell:[WFCUInformationCell class] forContent:[WFCCChangeGroupNameNotificationContent class]];
  575. [self registerCell:[WFCUInformationCell class] forContent:[WFCCChangeGroupPortraitNotificationContent class]];
  576. [self registerCell:[WFCUInformationCell class] forContent:[WFCCFriendAddedMessageContent class]];
  577. [self registerCell:[WFCUInformationCell class] forContent:[WFCCFriendGreetingMessageContent class]];
  578. [self registerCell:[WFCUCallSummaryCell class] forContent:[WFCCCallStartMessageContent class]];
  579. [self registerCell:[WFCUInformationCell class] forContent:[WFCCTipNotificationContent class]];
  580. [self registerCell:[WFCUInformationCell class] forContent:[WFCCUnknownMessageContent class]];
  581. [self registerCell:[WFCURecallCell class] forContent:[WFCCRecallMessageContent class]];
  582. [self registerCell:[WFCUConferenceInviteCell class] forContent:[WFCCConferenceInviteMessageContent class]];
  583. [self registerCell:[WFCUCardCell class] forContent:[WFCCCardMessageContent class]];
  584. [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
  585. [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
  586. self.collectionView.dataSource = self;
  587. self.collectionView.delegate = self;
  588. }
  589. - (void)registerCell:(Class)cellCls forContent:(Class)msgContentCls {
  590. [self.collectionView registerClass:cellCls
  591. forCellWithReuseIdentifier:[NSString stringWithFormat:@"%d", [msgContentCls getContentType]]];
  592. [self.cellContentDict setObject:cellCls forKey:@([msgContentCls getContentType])];
  593. }
  594. - (void)showTyping:(WFCCTypingType)typingType {
  595. if (self.showTypingTimer) {
  596. [self.showTypingTimer invalidate];
  597. }
  598. self.showTypingTimer = [NSTimer timerWithTimeInterval:TYPING_INTERVAL/2 target:self selector:@selector(stopShowTyping) userInfo:nil repeats:NO];
  599. [[NSRunLoop mainRunLoop] addTimer:self.showTypingTimer forMode:NSDefaultRunLoopMode];
  600. if (typingType == Typing_TEXT) {
  601. self.title = WFCString(@"TypingHint");
  602. } else if(typingType == Typing_VOICE) {
  603. self.title = WFCString(@"RecordingHint");
  604. } else if(typingType == Typing_CAMERA) {
  605. self.title = WFCString(@"PhotographingHint");
  606. } else if(typingType == Typing_LOCATION) {
  607. self.title = WFCString(@"GetLocationHint");
  608. } else if(typingType == Typing_FILE) {
  609. self.title = WFCString(@"SelectingFileHint");
  610. }
  611. }
  612. - (void)stopShowTyping {
  613. if(self.showTypingTimer != nil) {
  614. [self.showTypingTimer invalidate];
  615. self.showTypingTimer = nil;
  616. if (self.conversation.type == Single_Type) {
  617. self.targetUser = self.targetUser;
  618. } else if(self.conversation.type == Group_Type) {
  619. self.targetGroup = self.targetGroup;
  620. } else if(self.conversation.type == Channel_Type) {
  621. self.targetChannel = self.targetChannel;
  622. } else if(self.conversation.type == Group_Type) {
  623. self.targetGroup = self.targetGroup;
  624. }
  625. }
  626. }
  627. - (void)onResetKeyboard:(id)sender {
  628. [self.chatInputBar resetInputBarStatue];
  629. }
  630. - (void)didReceiveMemoryWarning {
  631. [super didReceiveMemoryWarning];
  632. }
  633. - (void)viewWillAppear:(BOOL)animated {
  634. [super viewWillAppear:animated];
  635. [self.chatInputBar willAppear];
  636. if(self.conversation.type == Single_Type) {
  637. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.conversation.target refresh:YES];
  638. self.targetUser = userInfo;
  639. } else if(self.conversation.type == Group_Type) {
  640. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.conversation.target refresh:YES];
  641. self.targetGroup = groupInfo;
  642. } else if (self.conversation.type == Channel_Type) {
  643. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:YES];
  644. self.targetChannel = channelInfo;
  645. } else if(self.conversation.type == Chatroom_Type) {
  646. __weak typeof(self)ws = self;
  647. [[WFCCIMService sharedWFCIMService] getChatroomInfo:self.conversation.target upateDt:ws.targetChatroom.updateDt success:^(WFCCChatroomInfo *chatroomInfo) {
  648. ws.targetChatroom = chatroomInfo;
  649. } error:^(int error_code) {
  650. }];
  651. }
  652. self.tabBarController.tabBar.hidden = YES;
  653. [self.collectionView reloadData];
  654. if (self.navigationController.viewControllers.count > 1) { // 记录系统返回手势的代理
  655. _scrollBackDelegate = self.navigationController.interactivePopGestureRecognizer.delegate; // 设置系统返回手势的代理为当前控制器
  656. self.navigationController.interactivePopGestureRecognizer.delegate = self;
  657. }
  658. if (self.conversation.type == Group_Type) {
  659. self.showAlias = ![[WFCCIMService sharedWFCIMService] isHiddenGroupMemberName:self.targetGroup.target];
  660. }
  661. if (self.firstAppear) {
  662. self.firstAppear = NO;
  663. [self scrollToBottom:NO];
  664. }
  665. }
  666. - (void)viewDidAppear:(BOOL)animated {
  667. [super viewDidAppear:animated];
  668. }
  669. - (void)viewWillDisappear:(BOOL)animated {
  670. [super viewWillDisappear:animated];
  671. NSString *newDraft = self.chatInputBar.draft;
  672. if (![self.orignalDraft isEqualToString:newDraft]) {
  673. self.orignalDraft = newDraft;
  674. [[WFCCIMService sharedWFCIMService] setConversation:self.conversation draft:newDraft];
  675. }
  676. // 设置系统返回手势的代理为我们刚进入控制器的时候记录的系统的返回手势代理
  677. self.navigationController.interactivePopGestureRecognizer.delegate = _scrollBackDelegate;
  678. [self.chatInputBar resetInputBarStatue];
  679. }
  680. - (void)sendMessage:(WFCCMessageContent *)content {
  681. //发送消息时,client会发出"kSendingMessageStatusUpdated“的通知,消息界面收到通知后加入到列表中。
  682. __weak typeof(self) ws = self;
  683. NSMutableArray *tousers = nil;
  684. if (self.privateChatUser) {
  685. tousers = [[NSMutableArray alloc] init];
  686. [tousers addObject:self.privateChatUser];
  687. }
  688. [[WFCCIMService sharedWFCIMService] send:self.conversation content:content toUsers:tousers expireDuration:0 success:^(long long messageUid, long long timestamp) {
  689. NSLog(@"send message success");
  690. if ([content isKindOfClass:[WFCCStickerMessageContent class]]) {
  691. [ws saveStickerRemoteUrl:(WFCCStickerMessageContent *)content];
  692. }
  693. } error:^(int error_code) {
  694. NSLog(@"send message fail(%d)", error_code);
  695. }];
  696. }
  697. - (void)onReceiveMessages:(NSNotification *)notification {
  698. NSArray<WFCCMessage *> *messages = notification.object;
  699. [self appendMessages:messages newMessage:YES highlightId:0 forceButtom:NO];
  700. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:self.conversation];
  701. }
  702. - (void)onRecallMessages:(NSNotification *)notification {
  703. long long messageUid = [notification.object longLongValue];
  704. WFCCMessage *msg = [[WFCCIMService sharedWFCIMService] getMessageByUid:messageUid];
  705. if (msg != nil) {
  706. for (int i = 0; i < self.modelList.count; i++) {
  707. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  708. if (model.message.messageUid == messageUid) {
  709. model.message = msg;
  710. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  711. break;
  712. }
  713. }
  714. }
  715. }
  716. - (void)onDeleteMessages:(NSNotification *)notification {
  717. long long messageUid = [notification.object longLongValue];
  718. for (int i = 0; i < self.modelList.count; i++) {
  719. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  720. if (model.message.messageUid == messageUid) {
  721. [self.modelList removeObject:model];
  722. [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  723. break;
  724. }
  725. }
  726. }
  727. - (void)onMessageDelivered:(NSNotification *)notification {
  728. if (self.conversation.type != Single_Type && self.conversation.type != Group_Type) {
  729. return;
  730. }
  731. NSArray<WFCCGroupMember *> *members = nil;
  732. if (self.conversation.type == Group_Type) {
  733. members = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  734. }
  735. NSArray<WFCCDeliveryReport *> *delivereds = notification.object;
  736. __block BOOL refresh = NO;
  737. [delivereds enumerateObjectsUsingBlock:^(WFCCDeliveryReport * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  738. if (self.conversation.type == Single_Type) {
  739. if ([self.conversation.target isEqualToString:obj.userId]) {
  740. *stop = YES;
  741. refresh = YES;
  742. }
  743. }
  744. if (self.conversation.type == Group_Type) {
  745. for (WFCCGroupMember *member in members) {
  746. if ([member.memberId isEqualToString:obj.userId]) {
  747. *stop = YES;
  748. refresh = YES;
  749. }
  750. }
  751. }
  752. }];
  753. if (refresh) {
  754. self.deliveryDict = [[WFCCIMService sharedWFCIMService] getMessageDelivery:self.conversation];
  755. WFCCGroupInfo *groupInfo = nil;
  756. for (int i = 0; i < self.modelList.count; i++) {
  757. WFCUMessageModel *model = self.modelList[i];
  758. model.deliveryDict = self.deliveryDict;
  759. if (model.message.direction == MessageDirection_Receive || model.deliveryRate == 1.f) {
  760. continue;
  761. }
  762. if (self.conversation.type == Single_Type) {
  763. if (model.message.serverTime <= [[model.deliveryDict objectForKey:model.message.conversation.target] longLongValue]) {
  764. float rate = 1.f;
  765. if (rate != model.deliveryRate) {
  766. model.deliveryRate = rate;
  767. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  768. }
  769. }
  770. } else { //group
  771. long long messageTS = model.message.serverTime;
  772. __block int delieveriedCount = 0;
  773. [model.deliveryDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
  774. if ([obj longLongValue] >= messageTS) {
  775. delieveriedCount++;
  776. }
  777. }];
  778. if (!groupInfo) {
  779. groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:model.message.conversation.target refresh:NO];
  780. }
  781. float rate = (float)delieveriedCount/(groupInfo.memberCount - 1);
  782. if (rate != model.deliveryRate) {
  783. model.deliveryRate = rate;
  784. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  785. }
  786. }
  787. }
  788. }
  789. }
  790. - (void)onMessageReaded:(NSNotification *)notification {
  791. if (self.conversation.type != Single_Type && self.conversation.type != Group_Type) {
  792. return;
  793. }
  794. NSArray<WFCCReadReport *> *readeds = notification.object;
  795. __block BOOL refresh = NO;
  796. [readeds enumerateObjectsUsingBlock:^(WFCCReadReport * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  797. if ([obj.conversation isEqual:self.conversation]) {
  798. *stop = YES;
  799. refresh = YES;
  800. }
  801. }];
  802. if (refresh) {
  803. self.readDict = [[WFCCIMService sharedWFCIMService] getConversationRead:self.conversation];
  804. WFCCGroupInfo *groupInfo = nil;
  805. for (int i = 0; i < self.modelList.count; i++) {
  806. WFCUMessageModel *model = self.modelList[i];
  807. model.readDict = self.readDict;
  808. if (model.message.direction == MessageDirection_Receive || model.readRate == 1.f) {
  809. continue;
  810. }
  811. if (self.conversation.type == Single_Type) {
  812. if (model.message.serverTime <= [[model.readDict objectForKey:model.message.conversation.target] longLongValue]) {
  813. float rate = 1.f;
  814. if (rate != model.readRate) {
  815. model.readRate = rate;
  816. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  817. }
  818. }
  819. } else { //group
  820. long long messageTS = model.message.serverTime;
  821. __block int delieveriedCount = 0;
  822. [model.readDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
  823. if ([obj longLongValue] >= messageTS) {
  824. delieveriedCount++;
  825. }
  826. }];
  827. if (!groupInfo) {
  828. groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:model.message.conversation.target refresh:NO];
  829. }
  830. float rate = (float)delieveriedCount/(groupInfo.memberCount - 1);
  831. if (rate != model.readRate) {
  832. model.readRate = rate;
  833. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  834. }
  835. }
  836. }
  837. }
  838. }
  839. #if WFCU_SUPPORT_VOIP
  840. - (void)onCallStateChanged:(NSNotification *)notification {
  841. long long messageUid = [[notification.userInfo objectForKey:@"messageUid"] longLongValue];
  842. WFCCMessage *msg = [[WFCCIMService sharedWFCIMService] getMessageByUid:messageUid];
  843. for (int i = 0; i < self.modelList.count; i++) {
  844. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  845. if (model.message.messageUid == messageUid) {
  846. model.message.content = msg.content;
  847. [self.collectionView reloadData];
  848. break;
  849. }
  850. }
  851. if ([[notification.userInfo objectForKey:@"state"] intValue] == kWFAVEngineStateIncomming) {
  852. if ([[[UIDevice currentDevice] systemVersion] rangeOfString:@"10."].location == 0) {
  853. [self.chatInputBar resetInputBarStatue];
  854. }
  855. }
  856. }
  857. #endif
  858. - (void)onSendingMessage:(NSNotification *)notification {
  859. WFCCMessage *message = [notification.userInfo objectForKey:@"message"];
  860. WFCCMessageStatus status = [[notification.userInfo objectForKey:@"status"] integerValue];
  861. if (status == Message_Status_Sending) {
  862. if ([message.conversation isEqual:self.conversation]) {
  863. [self appendMessages:@[message] newMessage:YES highlightId:0 forceButtom:YES];
  864. }
  865. }
  866. }
  867. - (void)onMessageListChanged:(NSNotification *)notification {
  868. [self reloadMessageList];
  869. }
  870. - (void)onSettingUpdated:(NSNotification *)notification {
  871. [self reloadMessageList];
  872. }
  873. - (void)reloadMessageList {
  874. self.deliveryDict = [[WFCCIMService sharedWFCIMService] getMessageDelivery:self.conversation];
  875. self.readDict = [[WFCCIMService sharedWFCIMService] getConversationRead:self.conversation];
  876. NSArray *messageList;
  877. if (self.highlightMessageId > 0) {
  878. NSArray *messageListOld = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:self.highlightMessageId+1 count:15 withUser:self.privateChatUser];
  879. NSArray *messageListNew = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:self.highlightMessageId count:-15 withUser:self.privateChatUser];
  880. NSMutableArray *list = [[NSMutableArray alloc] init];
  881. [list addObjectsFromArray:messageListNew];
  882. [list addObjectsFromArray:messageListOld];
  883. messageList = [list copy];
  884. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:self.conversation];
  885. if (messageListNew.count == 15) {
  886. self.hasNewMessage = YES;
  887. }
  888. } else {
  889. int count = (int)self.modelList.count;
  890. if (count > 50) {
  891. count = 50;
  892. } else if(count == 0) {
  893. count = 15;
  894. }
  895. messageList = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:0 count:count withUser:self.privateChatUser];
  896. self.mentionedMsgs = [[[WFCCIMService sharedWFCIMService] getMessages:self.conversation messageStatus:@[@(Message_Status_Mentioned), @(Message_Status_AllMentioned)] from:0 count:100 withUser:self.privateChatUser] mutableCopy];
  897. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:self.conversation];
  898. }
  899. self.modelList = [[NSMutableArray alloc] init];
  900. [self appendMessages:messageList newMessage:NO highlightId:self.highlightMessageId forceButtom:NO];
  901. self.highlightMessageId = 0;
  902. }
  903. - (void)appendMessages:(NSArray<WFCCMessage *> *)messages newMessage:(BOOL)newMessage highlightId:(long)highlightId forceButtom:(BOOL)forceButtom {
  904. if (messages.count == 0) {
  905. return;
  906. }
  907. int count = 0;
  908. NSMutableArray *modifiedAliasUsers = [[NSMutableArray alloc] init];
  909. for (int i = 0; i < messages.count; i++) {
  910. WFCCMessage *message = [messages objectAtIndex:i];
  911. if (![message.conversation isEqual:self.conversation]) {
  912. continue;
  913. }
  914. if ([message.content isKindOfClass:[WFCCTypingMessageContent class]] && message.direction == MessageDirection_Receive) {
  915. double now = [[NSDate date] timeIntervalSince1970];
  916. if (now - message.serverTime + [WFCCNetworkService sharedInstance].serverDeltaTime < TYPING_INTERVAL) {
  917. WFCCTypingMessageContent *content = (WFCCTypingMessageContent *)message.content;
  918. [self showTyping:content.type];
  919. }
  920. continue;
  921. }
  922. if (!([message.content.class getContentFlags] & 0x1)) {
  923. continue;
  924. }
  925. BOOL duplcated = NO;
  926. for (WFCUMessageModel *model in self.modelList) {
  927. if (model.message.messageUid !=0 && model.message.messageUid == message.messageUid) {
  928. duplcated = YES;
  929. break;
  930. }
  931. }
  932. if (duplcated) {
  933. continue;
  934. }
  935. count++;
  936. if (newMessage) {
  937. BOOL showTime = YES;
  938. if (self.modelList.count > 0 && (message.serverTime - (self.modelList[self.modelList.count - 1]).message.serverTime < 60 * 1000)) {
  939. showTime = NO;
  940. }
  941. WFCUMessageModel *model = [WFCUMessageModel modelOf:message showName:message.direction == MessageDirection_Receive && self.showAlias showTime:showTime];
  942. model.selecting = self.multiSelecting;
  943. model.selected = [self.selectedMessageIds containsObject:@(message.messageId)];
  944. model.deliveryDict = self.deliveryDict;
  945. model.readDict = self.readDict;
  946. [self.modelList addObject:model];
  947. if (messages.count == 1) {
  948. [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.modelList.count - 1 inSection:0]]];
  949. }
  950. if (self.conversation.type == Group_Type && [message.content isKindOfClass:[WFCCModifyGroupAliasNotificationContent class]]) {
  951. [modifiedAliasUsers addObject:message.fromUser];
  952. }
  953. } else {
  954. if (self.modelList.count > 0 && (self.modelList[0].message.serverTime - message.serverTime < 60 * 1000) && i != 0) {
  955. self.modelList[0].showTimeLabel = NO;
  956. }
  957. WFCUMessageModel *model = [WFCUMessageModel modelOf:message showName:message.direction == MessageDirection_Receive&&self.showAlias showTime:YES];
  958. model.selecting = self.multiSelecting;
  959. model.selected = [self.selectedMessageIds containsObject:@(message.messageId)];
  960. model.deliveryDict = self.deliveryDict;
  961. model.readDict = self.readDict;
  962. [self.modelList insertObject:model atIndex:0];
  963. }
  964. }
  965. if (count > 0) {
  966. [self stopShowTyping];
  967. }
  968. BOOL isAtButtom = NO;
  969. if (newMessage && !self.hasNewMessage) {
  970. if (@available(iOS 12.0, *)) {
  971. CGPoint offset = self.collectionView.contentOffset;
  972. CGSize size = self.collectionView.contentSize;
  973. CGSize visiableSize = CGSizeZero;
  974. visiableSize = self.collectionView.visibleSize;
  975. isAtButtom = (offset.y + visiableSize.height - size.height) > -100;
  976. } else {
  977. isAtButtom = YES;
  978. }
  979. }
  980. if (newMessage && messages.count == 1) {
  981. NSLog(@"alread reload the message");
  982. } else {
  983. [self.collectionView reloadData];
  984. }
  985. if (newMessage || self.modelList.count == messages.count) {
  986. if(isAtButtom) {
  987. forceButtom = true;
  988. }
  989. } else {
  990. CGFloat offset = 0;
  991. for (int i = 0; i < count; i++) {
  992. CGSize size = [self collectionView:self.collectionView layout:self.collectionView.collectionViewLayout sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
  993. offset += size.height;
  994. }
  995. self.collectionView.contentOffset = CGPointMake(0, offset);
  996. [UIView animateWithDuration:0.2 animations:^{
  997. self.collectionView.contentOffset = CGPointMake(0, offset - 20);
  998. }];
  999. }
  1000. if (highlightId > 0) {
  1001. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1002. int row = 0;
  1003. for (int i = 0; i < self.modelList.count; i++) {
  1004. WFCUMessageModel *model = self.modelList[i];
  1005. if (model.message.messageId == highlightId) {
  1006. row = i;
  1007. model.highlighted = YES;
  1008. break;
  1009. }
  1010. }
  1011. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
  1012. });
  1013. } else if (forceButtom) {
  1014. [self scrollToBottom:YES];
  1015. }
  1016. if (modifiedAliasUsers.count) {
  1017. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1018. NSArray<NSIndexPath *> *visibleItems = self.collectionView.indexPathsForVisibleItems;
  1019. NSMutableArray *needUpdateItems = [[NSMutableArray alloc] init];
  1020. for (NSIndexPath *item in visibleItems) {
  1021. WFCUMessageModel *model = [self.modelList objectAtIndex:item.row];
  1022. if ([modifiedAliasUsers containsObject:model.message.fromUser]) {
  1023. [needUpdateItems addObject:item];
  1024. }
  1025. }
  1026. if (needUpdateItems.count) {
  1027. [self.collectionView reloadItemsAtIndexPaths:needUpdateItems];
  1028. }
  1029. });
  1030. }
  1031. }
  1032. - (WFCUMessageModel *)modelOfMessage:(long)messageId {
  1033. if (messageId <= 0) {
  1034. return nil;
  1035. }
  1036. for (WFCUMessageModel *model in self.modelList) {
  1037. if (model.message.messageId == messageId) {
  1038. return model;
  1039. }
  1040. }
  1041. return nil;
  1042. }
  1043. - (void)stopPlayer {
  1044. if (self.player && [self.player isPlaying]) {
  1045. [self.player stop];
  1046. if ([self.playTimer isValid]) {
  1047. [self.playTimer invalidate];
  1048. self.playTimer = nil;
  1049. }
  1050. }
  1051. [self modelOfMessage:self.playingMessageId].voicePlaying = NO;
  1052. self.playingMessageId = 0;
  1053. [[NSNotificationCenter defaultCenter] postNotificationName:kVoiceMessagePlayStoped object:nil];
  1054. }
  1055. -(void)prepardToPlay:(WFCUMessageModel *)model {
  1056. if (self.playingMessageId == model.message.messageId) {
  1057. [self stopPlayer];
  1058. } else {
  1059. [self stopPlayer];
  1060. self.playingMessageId = model.message.messageId;
  1061. WFCCSoundMessageContent *soundContent = (WFCCSoundMessageContent *)model.message.content;
  1062. if (soundContent.localPath.length == 0) {
  1063. __weak typeof(self) weakSelf = self;
  1064. BOOL isDownloading = [[WFCUMediaMessageDownloader sharedDownloader] tryDownload:model.message success:^(long long messageUid, NSString *localPath) {
  1065. model.mediaDownloading = NO;
  1066. [weakSelf startPlay:model];
  1067. } error:^(long long messageUid, int error_code) {
  1068. model.mediaDownloading = NO;
  1069. }];
  1070. if (isDownloading) {
  1071. model.mediaDownloading = YES;
  1072. }
  1073. } else {
  1074. [self startPlay:model];
  1075. }
  1076. }
  1077. }
  1078. -(void)startPlay:(WFCUMessageModel *)model {
  1079. if ([model.message.content isKindOfClass:[WFCCSoundMessageContent class]]) {
  1080. // Setup audio session
  1081. AVAudioSession *session = [AVAudioSession sharedInstance];
  1082. [session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
  1083. [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
  1084. error:nil];
  1085. WFCCSoundMessageContent *snc = (WFCCSoundMessageContent *)model.message.content;
  1086. NSError *error = nil;
  1087. self.player = [[AVAudioPlayer alloc] initWithData:[snc getWavData] error:&error];
  1088. [self.player setDelegate:self];
  1089. [self.player prepareToPlay];
  1090. [self.player play];
  1091. model.voicePlaying = YES;
  1092. [[NSNotificationCenter defaultCenter] postNotificationName:kVoiceMessageStartPlaying object:@(self.playingMessageId)];
  1093. } else if([model.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  1094. WFCCVideoMessageContent *videoMsg = (WFCCVideoMessageContent *)model.message.content;
  1095. NSURL *url = [NSURL fileURLWithPath:[videoMsg.localPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  1096. if (!url) {
  1097. [self.view makeToast:@"无法播放"];
  1098. return;
  1099. }
  1100. if (!self.videoPlayerViewController) {
  1101. self.videoPlayerViewController = [VideoPlayerKit videoPlayerWithContainingView:self.view optionalTopView:nil hideTopViewWithControls:YES];
  1102. self.videoPlayerViewController.allowPortraitFullscreen = YES;
  1103. } else {
  1104. [self.videoPlayerViewController.view removeFromSuperview];
  1105. }
  1106. [self.view addSubview:self.videoPlayerViewController.view];
  1107. [self.videoPlayerViewController playVideoWithTitle:@" " URL:url videoID:nil shareURL:nil isStreaming:NO playInFullScreen:YES];
  1108. }
  1109. }
  1110. #pragma mark - UICollectionViewDataSource
  1111. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  1112. return self.modelList.count;
  1113. }
  1114. // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
  1115. - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  1116. WFCUMessageModel *model = self.modelList[indexPath.row];
  1117. NSString *objName = [NSString stringWithFormat:@"%d", [model.message.content.class getContentType]];
  1118. if (self.mentionedMsgs.count) {
  1119. for (WFCCMessage *msg in self.mentionedMsgs) {
  1120. if (msg.messageId == model.message.messageId) {
  1121. [self.mentionedMsgs removeObject:msg];
  1122. break;
  1123. }
  1124. }
  1125. }
  1126. WFCUMessageCellBase *cell = nil;
  1127. if(![self.cellContentDict objectForKey:@([model.message.content.class getContentType])]) {
  1128. cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"%d", [WFCCUnknownMessageContent getContentType]] forIndexPath:indexPath];
  1129. } else {
  1130. cell = [collectionView dequeueReusableCellWithReuseIdentifier:objName forIndexPath:indexPath];
  1131. }
  1132. cell.delegate = self;
  1133. [[NSNotificationCenter defaultCenter] removeObserver:cell];
  1134. cell.model = model;
  1135. return cell;
  1136. }
  1137. - (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  1138. {
  1139. if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
  1140. if(!self.headerView) {
  1141. self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
  1142. self.headerActivityView.center = CGPointMake(self.headerView.bounds.size.width/2, self.headerView.bounds.size.height/2);
  1143. [self.headerView addSubview:self.headerActivityView];
  1144. }
  1145. return self.headerView;
  1146. } else {
  1147. if(!self.footerView) {
  1148. self.footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
  1149. self.footerActivityView.center = CGPointMake(self.footerView.bounds.size.width/2, self.footerView.bounds.size.height/2);
  1150. [self.footerView addSubview:self.footerActivityView];
  1151. }
  1152. return self.footerView;
  1153. }
  1154. return nil;
  1155. }
  1156. #pragma mark - UICollectionViewDelegateFlowLayout
  1157. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  1158. WFCUMessageModel *model = self.modelList[indexPath.row];
  1159. Class cellCls = self.cellContentDict[@([[model.message.content class] getContentType])];
  1160. if (!cellCls) {
  1161. cellCls = self.cellContentDict[@([[WFCCUnknownMessageContent class] getContentType])];
  1162. }
  1163. return [cellCls sizeForCell:model withViewWidth:self.collectionView.frame.size.width];
  1164. }
  1165. #pragma mark - MessageCellDelegate
  1166. - (void)didTapMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1167. if ([model.message.content isKindOfClass:[WFCCImageMessageContent class]]) {
  1168. if (self.conversation.type == Chatroom_Type) {
  1169. NSMutableArray *imageMsgs = [[NSMutableArray alloc] init];
  1170. for (WFCUMessageModel *msgModle in self.modelList) {
  1171. if ([msgModle.message.content isKindOfClass:[WFCCImageMessageContent class]]) {
  1172. [imageMsgs addObject:msgModle.message];
  1173. }
  1174. }
  1175. self.imageMsgs = imageMsgs;
  1176. } else {
  1177. self.imageMsgs = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:@[@(MESSAGE_CONTENT_TYPE_IMAGE)] from:0 count:100 withUser:self.privateChatUser];
  1178. }
  1179. SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
  1180. browser.sourceImagesContainerView = self.backgroundView;
  1181. browser.showAll = YES;
  1182. browser.imageCount = self.imageMsgs.count;
  1183. int i;
  1184. for (i = 0; i < self.imageMsgs.count; i++) {
  1185. if ([self.imageMsgs objectAtIndex:i].messageId == model.message.messageId) {
  1186. break;
  1187. }
  1188. }
  1189. if (i == self.imageMsgs.count) {
  1190. i = 0;
  1191. }
  1192. [self onResetKeyboard:nil];
  1193. browser.currentImageIndex = i;
  1194. browser.delegate = self;
  1195. [browser show]; // 展示图片浏览器
  1196. } else if([model.message.content isKindOfClass:[WFCCSoundMessageContent class]]) {
  1197. if (model.message.direction == MessageDirection_Receive && model.message.status != Message_Status_Played) {
  1198. [[WFCCIMService sharedWFCIMService] setMediaMessagePlayed:model.message.messageId];
  1199. model.message.status = Message_Status_Played;
  1200. [self.collectionView reloadItemsAtIndexPaths:@[[self.collectionView indexPathForCell:cell]]];
  1201. }
  1202. [self prepardToPlay:model];
  1203. } else if([model.message.content isKindOfClass:[WFCCLocationMessageContent class]]) {
  1204. WFCCLocationMessageContent *locContent = (WFCCLocationMessageContent *)model.message.content;
  1205. WFCULocationViewController *vc = [[WFCULocationViewController alloc] initWithLocationPoint:[[WFCULocationPoint alloc] initWithCoordinate:locContent.coordinate andTitle:locContent.title]];
  1206. [self.navigationController pushViewController:vc animated:YES];
  1207. } else if ([model.message.content isKindOfClass:[WFCCFileMessageContent class]]) {
  1208. WFCCFileMessageContent *fileContent = (WFCCFileMessageContent *)model.message.content;
  1209. __weak typeof(self)ws = self;
  1210. [[WFCCIMService sharedWFCIMService] getAuthorizedMediaUrl:model.message.messageUid mediaType:Media_Type_FILE mediaPath:fileContent.remoteUrl success:^(NSString *authorizedUrl) {
  1211. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  1212. bvc.url = authorizedUrl;
  1213. [ws.navigationController pushViewController:bvc animated:YES];
  1214. } error:^(int error_code) {
  1215. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  1216. bvc.url = fileContent.remoteUrl;
  1217. [ws.navigationController pushViewController:bvc animated:YES];
  1218. }];
  1219. } else if ([model.message.content isKindOfClass:[WFCCCallStartMessageContent class]]) {
  1220. WFCCCallStartMessageContent *callStartMsg = (WFCCCallStartMessageContent *)model.message.content;
  1221. #if WFCU_SUPPORT_VOIP
  1222. [self didTouchVideoBtn:callStartMsg.isAudioOnly];
  1223. #endif
  1224. } else if([model.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  1225. WFCCVideoMessageContent *videoMsg = (WFCCVideoMessageContent *)model.message.content;
  1226. if (model.message.direction == MessageDirection_Receive && model.message.status != Message_Status_Played) {
  1227. [[WFCCIMService sharedWFCIMService] setMediaMessagePlayed:model.message.messageId];
  1228. model.message.status = Message_Status_Played;
  1229. [self.collectionView reloadItemsAtIndexPaths:@[[self.collectionView indexPathForCell:cell]]];
  1230. }
  1231. if (videoMsg.localPath.length == 0) {
  1232. model.mediaDownloading = YES;
  1233. __weak typeof(self) weakSelf = self;
  1234. [[WFCUMediaMessageDownloader sharedDownloader] tryDownload:model.message success:^(long long messageUid, NSString *localPath) {
  1235. model.mediaDownloading = NO;
  1236. [weakSelf startPlay:model];
  1237. } error:^(long long messageUid, int error_code) {
  1238. model.mediaDownloading = NO;
  1239. }];
  1240. } else {
  1241. [self startPlay:model];
  1242. }
  1243. } else if([model.message.content isKindOfClass:[WFCCConferenceInviteMessageContent class]]) {
  1244. WFCCConferenceInviteMessageContent *invite = (WFCCConferenceInviteMessageContent *)model.message.content;
  1245. WFCUConferenceViewController *vc = [[WFCUConferenceViewController alloc] initWithInvite:invite];
  1246. [[WFAVEngineKit sharedEngineKit] presentViewController:vc];
  1247. } else if([model.message.content isKindOfClass:[WFCCCardMessageContent class]]) {
  1248. WFCCCardMessageContent *card = (WFCCCardMessageContent *)model.message.content;
  1249. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:card.userId refresh:NO];
  1250. if (!userInfo.deleted) {
  1251. WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
  1252. vc.userId = card.userId;
  1253. vc.hidesBottomBarWhenPushed = YES;
  1254. [self.navigationController pushViewController:vc animated:YES];
  1255. }
  1256. }
  1257. }
  1258. - (void)didDoubleTapMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1259. if ([model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  1260. WFCCTextMessageContent *txtMsgContent = (WFCCTextMessageContent *)model.message.content;
  1261. [self.chatInputBar resetInputBarStatue];
  1262. UIView *textContainer = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  1263. textContainer.backgroundColor = self.view.backgroundColor;
  1264. UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - kStatusBarAndNavigationBarHeight - kTabbarSafeBottomMargin)];
  1265. textView.text = txtMsgContent.text;
  1266. textView.textAlignment = NSTextAlignmentCenter;
  1267. textView.font = [UIFont systemFontOfSize:28];
  1268. textView.editable = NO;
  1269. textView.backgroundColor = self.view.backgroundColor;
  1270. [textContainer addSubview:textView];
  1271. [textView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapTextMessageDetailView:)]];
  1272. [[UIApplication sharedApplication].keyWindow addSubview:textContainer];
  1273. }
  1274. }
  1275. - (void)didTapTextMessageDetailView:(id)sender {
  1276. if ([sender isKindOfClass:[UIGestureRecognizer class]]) {
  1277. UIGestureRecognizer *gesture = (UIGestureRecognizer *)sender;
  1278. [gesture.view.superview removeFromSuperview];
  1279. }
  1280. NSLog(@"close windows");
  1281. }
  1282. - (void)didTapMessagePortrait:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1283. if(self.conversation.type == Group_Type) {
  1284. if (self.targetGroup.privateChat) {
  1285. if (![self.targetGroup.owner isEqualToString:model.message.fromUser] && ![self.targetGroup.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  1286. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:self.conversation.target memberId:[WFCCNetworkService sharedInstance].userId];
  1287. if (gm.type != Member_Type_Manager) {
  1288. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:self.conversation.target memberId:model.message.fromUser];
  1289. if (gm.type != Member_Type_Manager) {
  1290. [self.view makeToast:WFCString(@"NotAllowTemporarySession") duration:1 position:CSToastPositionCenter];
  1291. return;
  1292. }
  1293. }
  1294. }
  1295. }
  1296. }
  1297. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:model.message.fromUser refresh:NO];
  1298. if (!userInfo.deleted) {
  1299. WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
  1300. vc.userId = model.message.fromUser;
  1301. vc.fromConversation = self.conversation;
  1302. vc.hidesBottomBarWhenPushed = YES;
  1303. [self.navigationController pushViewController:vc animated:YES];
  1304. }
  1305. }
  1306. - (void)didLongPressMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1307. if ([cell isKindOfClass:[WFCUMessageCellBase class]]) {
  1308. // if (!self.isFirstResponder) {
  1309. // [self becomeFirstResponder];
  1310. // }
  1311. [self displayMenu:(WFCUMessageCellBase *)cell];
  1312. }
  1313. }
  1314. - (void)didLongPressMessagePortrait:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1315. if (self.conversation.type == Group_Type) {
  1316. if (model.message.direction == MessageDirection_Receive) {
  1317. WFCCUserInfo *sender = [[WFCCIMService sharedWFCIMService] getUserInfo:model.message.fromUser refresh:NO];
  1318. [self.chatInputBar appendMention:model.message.fromUser name:sender.displayName];
  1319. }
  1320. } else if(self.conversation.type == Channel_Type) {
  1321. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:NO];
  1322. if ([channelInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  1323. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1324. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
  1325. UIAlertAction *okAction = [UIAlertAction actionWithTitle:WFCString(@"ChatWithSubscriber") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1326. if (model.message.direction == MessageDirection_Receive) {
  1327. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:NO];
  1328. if ([channelInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  1329. WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
  1330. mvc.conversation = [WFCCConversation conversationWithType:self.conversation.type target:self.conversation.target line:self.conversation.line];
  1331. mvc.privateChatUser = model.message.fromUser;
  1332. [self.navigationController pushViewController:mvc animated:YES];
  1333. }
  1334. }
  1335. }];
  1336. [alertController addAction:cancelAction];
  1337. [alertController addAction:okAction];
  1338. [self presentViewController:alertController animated:YES completion:nil];
  1339. }
  1340. }
  1341. }
  1342. - (void)didTapResendBtn:(WFCUMessageModel *)model {
  1343. NSInteger index = [self.modelList indexOfObject:model];
  1344. if (index >= 0) {
  1345. NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:0];
  1346. [self.modelList removeObjectAtIndex:index];
  1347. [self.collectionView deleteItemsAtIndexPaths:@[path]];
  1348. [[WFCCIMService sharedWFCIMService] deleteMessage:model.message.messageId];
  1349. [self sendMessage:model.message.content];
  1350. }
  1351. }
  1352. - (void)didSelectUrl:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model withUrl:(NSString *)urlString {
  1353. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  1354. bvc.url = urlString;
  1355. [self.navigationController pushViewController:bvc animated:YES];
  1356. }
  1357. - (void)didSelectPhoneNumber:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model withPhoneNumber:(NSString *)phoneNumber {
  1358. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:WFCString(@"PhoneNumberHint"), phoneNumber] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1359. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
  1360. UIAlertAction *callAction = [UIAlertAction actionWithTitle:WFCString(@"Call") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1361. NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"telprompt:%@", phoneNumber]];
  1362. [[UIApplication sharedApplication] openURL:url];
  1363. }];
  1364. UIAlertAction *copyAction = [UIAlertAction actionWithTitle:WFCString(@"CopyNumber") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  1365. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1366. pasteboard.string = phoneNumber;
  1367. }];
  1368. [alertController addAction:cancelAction];
  1369. [alertController addAction:callAction];
  1370. [alertController addAction:copyAction];
  1371. // [alertController addAction:addContactAction];
  1372. [self presentViewController:alertController animated:YES completion:nil];
  1373. }
  1374. - (void)reeditRecalledMessage:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1375. WFCCRecallMessageContent *recall = (WFCCRecallMessageContent *)model.message.content;
  1376. [self.chatInputBar appendText:recall.originalSearchableContent];
  1377. }
  1378. - (void)didTapReceiptView:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  1379. WFCUReceiptViewController *receipt = [[WFCUReceiptViewController alloc] init];
  1380. receipt.message = model.message;
  1381. [self.navigationController pushViewController:receipt animated:YES];
  1382. }
  1383. #pragma mark - AVAudioPlayerDelegate
  1384. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
  1385. NSLog(@"player finished");
  1386. [self stopPlayer];
  1387. }
  1388. - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
  1389. NSLog(@"player decode error");
  1390. [[[UIAlertView alloc] initWithTitle:WFCString(@"Warning") message:WFCString(@"NetworkError") delegate:nil cancelButtonTitle:WFCString(@"Ok") otherButtonTitles:nil, nil] show];
  1391. [self stopPlayer];
  1392. }
  1393. #pragma mark - UIScrollViewDelegate
  1394. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  1395. }
  1396. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  1397. [self.chatInputBar resetInputBarStatue];
  1398. }
  1399. - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
  1400. if (self.hasNewMessage && ceil(targetContentOffset->y)+1 >= ceil(scrollView.contentSize.height - scrollView.bounds.size.height)) {
  1401. [self loadMoreMessage:NO];
  1402. }
  1403. if (targetContentOffset->y == 0 && self.hasMoreOld) {
  1404. [self loadMoreMessage:YES];
  1405. }
  1406. }
  1407. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  1408. }
  1409. #pragma mark - ChatInputBarDelegate
  1410. - (void)imageDidCapture:(UIImage *)capturedImage {
  1411. if (!capturedImage) {
  1412. return;
  1413. }
  1414. WFCCImageMessageContent *imgContent = [WFCCImageMessageContent contentFrom:capturedImage];
  1415. [self sendMessage:imgContent];
  1416. }
  1417. - (void)videoDidCapture:(NSString *)videoPath thumbnail:(UIImage *)image duration:(long)duration {
  1418. WFCCVideoMessageContent *videoContent = [WFCCVideoMessageContent contentPath:videoPath thumbnail:image];
  1419. [self sendMessage:videoContent];
  1420. }
  1421. - (void)imageDataDidSelect:(NSArray<UIImage *> *)selectedImages isFullImage:(BOOL)fullImage {
  1422. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1423. for (UIImage *image in selectedImages) {
  1424. WFCCImageMessageContent *imgContent = [WFCCImageMessageContent contentFrom:image];
  1425. dispatch_sync(dispatch_get_main_queue(), ^{
  1426. [self sendMessage:imgContent];
  1427. });
  1428. [NSThread sleepForTimeInterval:0.2];
  1429. }
  1430. });
  1431. }
  1432. - (void)didTouchSend:(NSString *)stringContent withMentionInfos:(NSMutableArray<WFCUMetionInfo *> *)mentionInfos {
  1433. if (stringContent.length == 0) {
  1434. return;
  1435. }
  1436. WFCCTextMessageContent *txtContent = [[WFCCTextMessageContent alloc] init];
  1437. txtContent.text = stringContent;
  1438. NSMutableArray *mentionTargets = [[NSMutableArray alloc] init];
  1439. for (WFCUMetionInfo *mentionInfo in mentionInfos) {
  1440. if (mentionInfo.mentionType == 2) {
  1441. txtContent.mentionedType = 2;
  1442. mentionTargets = nil;
  1443. break;
  1444. } else if(mentionInfo.mentionType == 1) {
  1445. txtContent.mentionedType = 1;
  1446. [mentionTargets addObject:mentionInfo.target];
  1447. }
  1448. }
  1449. if (txtContent.mentionedType == 1) {
  1450. txtContent.mentionedTargets = [mentionTargets copy];
  1451. }
  1452. [self sendMessage:txtContent];
  1453. }
  1454. - (void)recordDidEnd:(NSString *)dataUri duration:(long)duration error:(NSError *)error {
  1455. [self sendMessage:[WFCCSoundMessageContent soundMessageContentForWav:dataUri duration:duration]];
  1456. }
  1457. - (void)willChangeFrame:(CGRect)newFrame withDuration:(CGFloat)duration keyboardShowing:(BOOL)keyboardShowing {
  1458. if (!self.isShowingKeyboard) {
  1459. self.isShowingKeyboard = YES;
  1460. [UIView animateWithDuration:duration animations:^{
  1461. CGRect frame = self.collectionView.frame;
  1462. CGFloat diff = MIN(frame.size.height, self.collectionView.contentSize.height) - newFrame.origin.y;
  1463. if(diff > 0) {
  1464. frame.origin.y = -diff;
  1465. self.collectionView.frame = frame;
  1466. } else {
  1467. self.collectionView.frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  1468. }
  1469. } completion:^(BOOL finished) {
  1470. self.collectionView.frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  1471. if (keyboardShowing) {
  1472. [self scrollToBottom:NO];
  1473. }
  1474. self.isShowingKeyboard = NO;
  1475. }];
  1476. } else {
  1477. if (self.collectionView.frame.size.height != newFrame.origin.y) {
  1478. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1479. self.collectionView.frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  1480. [self scrollToBottom:YES];
  1481. });
  1482. }
  1483. }
  1484. }
  1485. - (UINavigationController *)requireNavi {
  1486. return self.navigationController;
  1487. }
  1488. - (void)locationDidSelect:(CLLocationCoordinate2D)location locationName:(NSString *)locationName mapScreenShot:(UIImage *)mapScreenShot {
  1489. WFCCLocationMessageContent *content = [WFCCLocationMessageContent contentWith:location title:locationName thumbnail:mapScreenShot];
  1490. [self sendMessage:content];
  1491. }
  1492. - (void)didSelectFiles:(NSArray *)files {
  1493. for (NSString *file in files) {
  1494. WFCCFileMessageContent *content = [WFCCFileMessageContent fileMessageContentFromPath:file];
  1495. [self sendMessage:content];
  1496. [NSThread sleepForTimeInterval:0.05];
  1497. }
  1498. }
  1499. - (void)saveStickerRemoteUrl:(WFCCStickerMessageContent *)stickerContent {
  1500. if (stickerContent.localPath.length && stickerContent.remoteUrl.length) {
  1501. [[NSUserDefaults standardUserDefaults] setObject:stickerContent.remoteUrl forKey:[NSString stringWithFormat:@"sticker_remote_for_%ld", stickerContent.localPath.hash]];
  1502. [[NSUserDefaults standardUserDefaults] synchronize];
  1503. }
  1504. }
  1505. - (void)didSelectSticker:(NSString *)stickerPath {
  1506. WFCCStickerMessageContent * content = [WFCCStickerMessageContent contentFrom:stickerPath];
  1507. NSString *remoteUrl = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"sticker_remote_for_%ld", stickerPath.hash]];
  1508. content.remoteUrl = remoteUrl;
  1509. [self sendMessage:content];
  1510. }
  1511. #if WFCU_SUPPORT_VOIP
  1512. - (void)didTouchVideoBtn:(BOOL)isAudioOnly {
  1513. if(self.conversation.type == Single_Type) {
  1514. WFCUVideoViewController *videoVC = [[WFCUVideoViewController alloc] initWithTargets:@[self.conversation.target] conversation:self.conversation audioOnly:isAudioOnly];
  1515. [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
  1516. } else {
  1517. // WFCUContactListViewController *pvc = [[WFCUContactListViewController alloc] init];
  1518. // pvc.selectContact = YES;
  1519. // pvc.multiSelect = [WFAVEngineKit sharedEngineKit].supportMultiCall;
  1520. // if (pvc.multiSelect) {
  1521. // pvc.maxSelectCount = isAudioOnly ? [WFAVEngineKit sharedEngineKit].maxAudioCallCount : [WFAVEngineKit sharedEngineKit].maxVideoCallCount;
  1522. // pvc.maxSelectCount -= 1;
  1523. // }
  1524. WFCUSeletedUserViewController *vc = [[WFCUSeletedUserViewController alloc] init];
  1525. NSMutableArray *disabledUser = [[NSMutableArray alloc] init];
  1526. [disabledUser addObject:[WFCCNetworkService sharedInstance].userId];
  1527. vc.disableUserIds = disabledUser;
  1528. vc.maxSelectCount = isAudioOnly ? [WFAVEngineKit sharedEngineKit].maxAudioCallCount : [WFAVEngineKit sharedEngineKit].maxVideoCallCount;
  1529. vc.groupId = self.targetGroup.target;
  1530. // vc.maxSelectCount -= 1;
  1531. NSMutableArray *candidateUser = [[NSMutableArray alloc] init];
  1532. NSArray<WFCCGroupMember *> *members = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  1533. for (WFCCGroupMember *member in members) {
  1534. [candidateUser addObject:member.memberId];
  1535. }
  1536. vc.candidateUsers = candidateUser;
  1537. vc.type = Vertical;
  1538. __weak typeof(self)ws = self;
  1539. vc.selectResult = ^(NSArray<NSString *> * _Nonnull contacts) {
  1540. UIViewController *videoVC;
  1541. if (ws.conversation.type == Group_Type && [WFAVEngineKit sharedEngineKit].supportMultiCall) {
  1542. videoVC = [[WFCUMultiVideoViewController alloc] initWithTargets:contacts conversation:ws.conversation audioOnly:isAudioOnly];
  1543. } else {
  1544. videoVC = [[WFCUVideoViewController alloc] initWithTargets:contacts conversation:ws.conversation audioOnly:isAudioOnly];
  1545. }
  1546. [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
  1547. };
  1548. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
  1549. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  1550. [self.navigationController presentViewController:navi animated:YES completion:nil];
  1551. }
  1552. }
  1553. #endif
  1554. - (void)onTyping:(WFCCTypingType)type {
  1555. if (self.conversation.type == Single_Type) {
  1556. [self sendMessage:[WFCCTypingMessageContent contentType:type]];
  1557. }
  1558. }
  1559. #pragma mark - SDPhotoBrowserDelegate
  1560. - (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
  1561. WFCCMessage *msg = [self.imageMsgs objectAtIndex:index];
  1562. if ([[msg.content class] getContentType] == MESSAGE_CONTENT_TYPE_IMAGE) {
  1563. WFCCImageMessageContent *imgContent = (WFCCImageMessageContent *)msg.content;
  1564. return imgContent.thumbnail;
  1565. }
  1566. return nil;
  1567. }
  1568. - (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
  1569. WFCCMessage *msg = [self.imageMsgs objectAtIndex:index];
  1570. if ([[msg.content class] getContentType] == MESSAGE_CONTENT_TYPE_IMAGE) {
  1571. WFCCImageMessageContent *imgContent = (WFCCImageMessageContent *)msg.content;
  1572. return [NSURL URLWithString:[imgContent.remoteUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  1573. }
  1574. return nil;
  1575. }
  1576. - (void)photoBrowserDidDismiss:(SDPhotoBrowser *)browser {
  1577. self.imageMsgs = nil;
  1578. }
  1579. - (void)photoBrowserShowAllView {
  1580. WFCUMediaMessageGridViewController *vc = [[WFCUMediaMessageGridViewController alloc] init];
  1581. vc.conversation = self.conversation;
  1582. [self.navigationController pushViewController:vc animated:YES];
  1583. }
  1584. #pragma mark - UIGestureRecognizerDelegate
  1585. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
  1586. return self.navigationController.childViewControllers.count > 1;
  1587. }
  1588. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
  1589. return self.navigationController.viewControllers.count > 1;
  1590. }
  1591. #pragma mark - menu
  1592. - (void)displayMenu:(WFCUMessageCellBase *)baseCell {
  1593. UIMenuController *menu = [UIMenuController sharedMenuController];
  1594. UIMenuItem *deleteItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Delete") action:@selector(performDelete:)];
  1595. UIMenuItem *copyItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Copy") action:@selector(performCopy:)];
  1596. UIMenuItem *forwardItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Forward") action:@selector(performForward:)];
  1597. UIMenuItem *recallItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Recall") action:@selector(performRecall:)];
  1598. UIMenuItem *complainItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Complain") action:@selector(performComplain:)];
  1599. UIMenuItem *multiSelectItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"MultiSelect") action:@selector(performMultiSelect:)];
  1600. CGRect menuPos;
  1601. if ([baseCell isKindOfClass:[WFCUMessageCell class]]) {
  1602. WFCUMessageCell *msgCell = (WFCUMessageCell *)baseCell;
  1603. menuPos = msgCell.bubbleView.frame;
  1604. } else {
  1605. menuPos = baseCell.frame;
  1606. }
  1607. [menu setTargetRect:menuPos inView:baseCell];
  1608. WFCCMessage *msg = baseCell.model.message;
  1609. NSMutableArray *items = [[NSMutableArray alloc] init];
  1610. [items addObject:deleteItem];
  1611. if ([msg.content isKindOfClass:[WFCCTextMessageContent class]]) {
  1612. [items addObject:copyItem];
  1613. }
  1614. if (baseCell.model.message.direction == MessageDirection_Receive) {
  1615. [items addObject:complainItem];
  1616. }
  1617. if ([msg.content isKindOfClass:[WFCCImageMessageContent class]] ||
  1618. [msg.content isKindOfClass:[WFCCTextMessageContent class]] ||
  1619. [msg.content isKindOfClass:[WFCCLocationMessageContent class]] ||
  1620. [msg.content isKindOfClass:[WFCCFileMessageContent class]] ||
  1621. [msg.content isKindOfClass:[WFCCVideoMessageContent class]] ||
  1622. [msg.content isKindOfClass:[WFCUConferenceInviteCell class]] ||
  1623. [msg.content isKindOfClass:[WFCUCardCell class]] ||
  1624. // [msg.content isKindOfClass:[WFCCSoundMessageContent class]] || //语音消息禁止转发,出于安全原因考虑,微信就禁止转发。如果您能确保安全,可以把这行注释打开
  1625. [msg.content isKindOfClass:[WFCCStickerMessageContent class]]) {
  1626. [items addObject:forwardItem];
  1627. }
  1628. BOOL canRecall = NO;
  1629. if ([baseCell isKindOfClass:[WFCUMessageCell class]] &&
  1630. msg.direction == MessageDirection_Send
  1631. ) {
  1632. NSDate *cur = [NSDate date];
  1633. if ([cur timeIntervalSince1970]*1000 - msg.serverTime < 60 * 1000) {
  1634. canRecall = YES;
  1635. }
  1636. }
  1637. if (!canRecall && self.conversation.type == Group_Type) {
  1638. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.conversation.target refresh:NO];
  1639. if([groupInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  1640. canRecall = YES;
  1641. if ([groupInfo.owner isEqualToString:msg.fromUser]) {
  1642. canRecall = NO;
  1643. }
  1644. } else {
  1645. __block BOOL isManager = false;
  1646. NSArray *memberList = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  1647. [memberList enumerateObjectsUsingBlock:^(WFCCGroupMember * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1648. if ([obj.memberId isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  1649. if ((obj.type == Member_Type_Manager || obj.type == Member_Type_Owner) && ![msg.fromUser isEqualToString:obj.memberId]) {
  1650. isManager = YES;
  1651. }
  1652. *stop = YES;
  1653. }
  1654. }];
  1655. if(isManager && ![msg.fromUser isEqualToString:groupInfo.owner]) {
  1656. canRecall = YES;
  1657. }
  1658. }
  1659. }
  1660. if (canRecall) {
  1661. [items addObject:recallItem];
  1662. }
  1663. if ([baseCell isKindOfClass:[WFCUMessageCell class]]) {
  1664. [items addObject:multiSelectItem];
  1665. }
  1666. [menu setMenuItems:items];
  1667. self.cell4Menu = baseCell;
  1668. [menu setMenuVisible:YES];
  1669. }
  1670. -(BOOL)canBecomeFirstResponder {
  1671. return YES;
  1672. }
  1673. -(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  1674. if(self.cell4Menu) {
  1675. if (action == @selector(performDelete:) || action == @selector(performCopy:) || action == @selector(performForward:) || action == @selector(performRecall:) || action == @selector(performComplain:) || action == @selector(performMultiSelect:)) {
  1676. return YES; //显示自定义的菜单项
  1677. } else {
  1678. return NO;
  1679. }
  1680. }
  1681. if (action == @selector(paste:)) {
  1682. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1683. return pasteboard.string != nil;
  1684. }
  1685. return NO;//[super canPerformAction:action withSender:sender];
  1686. }
  1687. - (void)paste:(id)sender {
  1688. [self.chatInputBar paste:sender];
  1689. }
  1690. - (void)deleteMessageUI:(WFCCMessage *)message {
  1691. for (int i = 0; i < self.modelList.count; i++) {
  1692. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1693. if (model.message.messageUid == message.messageUid) {
  1694. [self.modelList removeObject:model];
  1695. [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1696. break;
  1697. }
  1698. }
  1699. }
  1700. -(void)performDelete:(UIMenuController *)sender {
  1701. __weak typeof(self)ws = self;
  1702. WFCCMessage *message = self.cell4Menu.model.message;
  1703. [[WFCCIMService sharedWFCIMService] deleteMessage:message.messageId];
  1704. [ws deleteMessageUI:message];
  1705. }
  1706. -(void)performCopy:(UIMenuItem *)sender {
  1707. if (self.cell4Menu) {
  1708. if ([self.cell4Menu.model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  1709. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1710. pasteboard.string = ((WFCCTextMessageContent *)self.cell4Menu.model.message.content).text;
  1711. }
  1712. }
  1713. }
  1714. -(void)performForward:(UIMenuItem *)sender {
  1715. if (self.cell4Menu) {
  1716. WFCUForwardViewController *controller = [[WFCUForwardViewController alloc] init];
  1717. controller.message = self.cell4Menu.model.message;
  1718. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
  1719. [self.navigationController presentViewController:navi animated:YES completion:nil];
  1720. }
  1721. }
  1722. -(void)performRecall:(UIMenuItem *)sender {
  1723. if (self.cell4Menu.model.message) {
  1724. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  1725. hud.label.text = WFCString(@"Recalling");
  1726. [hud showAnimated:YES];
  1727. __weak typeof(self) ws = self;
  1728. long messageId = self.cell4Menu.model.message.messageId;
  1729. WFCUMessageCellBase *cell = self.cell4Menu;
  1730. [[WFCCIMService sharedWFCIMService] recall:self.cell4Menu.model.message success:^{
  1731. dispatch_async(dispatch_get_main_queue(), ^{
  1732. [hud hideAnimated:YES];
  1733. if (cell.model.message.messageId == messageId) {
  1734. cell.model.message = [[WFCCIMService sharedWFCIMService] getMessage:messageId];
  1735. [ws.collectionView reloadItemsAtIndexPaths:@[[ws.collectionView indexPathForCell:cell]]];
  1736. }
  1737. });
  1738. } error:^(int error_code) {
  1739. dispatch_async(dispatch_get_main_queue(), ^{
  1740. hud.mode = MBProgressHUDModeText;
  1741. hud.label.text = WFCString(@"RecallFailure");
  1742. [hud hideAnimated:YES afterDelay:1.f];
  1743. });
  1744. }];
  1745. }
  1746. }
  1747. - (void)performComplain:(UIMenuItem *)sender {
  1748. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:WFCString(@"Complain") message:@"如果您发现有违反法律和道德的内容,或者您的合法权益受到侵犯,请截图之后发送给我们。我们会在24小时之内处理。处理办法包括不限于删除内容,对作者进行警告,冻结账号,甚至报警处理。举报请到\"设置->设置->举报\"联系我们!" preferredStyle:UIAlertControllerStyleAlert];
  1749. UIAlertAction *action = [UIAlertAction actionWithTitle:WFCString(WFCString(@"Ok")) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1750. }];
  1751. [alertController addAction:action];
  1752. [self presentViewController:alertController animated:YES completion:nil];
  1753. }
  1754. - (void)performMultiSelect:(UIMenuItem *)sender {
  1755. self.multiSelecting = !self.multiSelecting;
  1756. }
  1757. - (void)onMenuHidden:(id)sender {
  1758. UIMenuController *menu = [UIMenuController sharedMenuController];
  1759. [menu setMenuItems:nil];
  1760. __weak typeof(self)ws = self;
  1761. dispatch_async(dispatch_get_main_queue(), ^{
  1762. ws.cell4Menu = nil;
  1763. });
  1764. }
  1765. - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
  1766. [super traitCollectionDidChange:previousTraitCollection];
  1767. if (@available(iOS 13.0, *)) {
  1768. if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
  1769. [self.navigationController popViewControllerAnimated:NO];
  1770. }
  1771. }
  1772. }
  1773. - (void)dealloc {
  1774. [[NSNotificationCenter defaultCenter] removeObserver:self];
  1775. }
  1776. @end