WFCUMessageListViewController.m 87 KB

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