TUIBaseMessageController.m 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. //
  2. // TUIBaseMessageController.m
  3. // UIKit
  4. //
  5. // Created by annidyfeng on 2019/7/1.
  6. // Copyright © 2022 Tencent. All rights reserved.
  7. //
  8. #import "TUIBaseMessageController.h"
  9. #import <TIMCommon/TIMConfig.h>
  10. #import <TIMCommon/TIMDefine.h>
  11. #import <TIMCommon/TIMPopActionProtocol.h>
  12. #import <TIMCommon/TUISystemMessageCell.h>
  13. #import <TUICore/TUICore.h>
  14. #import <TUICore/TUIThemeManager.h>
  15. #import <TUICore/TUITool.h>
  16. #import <TUICore/TUILogin.h>
  17. #import <UIKit/UIWindow.h>
  18. #import "TUIChatCallingDataProvider.h"
  19. #import "TUIChatConversationModel.h"
  20. #import "TUIChatDataProvider.h"
  21. #import "TUIChatPopMenu.h"
  22. #import "TUIFaceMessageCell.h"
  23. #import "TUIFaceView.h"
  24. #import "TUIFileMessageCell.h"
  25. #import "TUIFileViewController.h"
  26. #import "TUIImageMessageCell.h"
  27. #import "TUIJoinGroupMessageCell.h"
  28. #import "TUILinkCell.h"
  29. #import "TUIMediaView.h"
  30. #import "TUIMergeMessageCell.h"
  31. #import "TUIMergeMessageListController.h"
  32. #import "TUIMessageDataProvider.h"
  33. #import "TUIMessageProgressManager.h"
  34. #import "TUIMessageReadViewController.h"
  35. #import "TUIOrderCell.h"
  36. #import "TUIReferenceMessageCell.h"
  37. #import "TUIRepliesDetailViewController.h"
  38. #import "TUIReplyMessageCell.h"
  39. #import "TUIReplyMessageCellData.h"
  40. #import "TUITextMessageCell.h"
  41. #import "TUIVideoMessageCell.h"
  42. #import "TUIVoiceMessageCell.h"
  43. #import "TUIMessageCellConfig.h"
  44. #import "MOSystemNormalCellData.h"
  45. #import "MOSystemNormalCell.h"
  46. #import "MOUserLinkCellData.h"
  47. #import "MOUserNotificationCellData.h"
  48. @interface TUIBaseMessageController () <TUIMessageCellDelegate,
  49. TUIJoinGroupMessageCellDelegate,
  50. TUIMessageProgressManagerDelegate,
  51. TUIMessageDataProviderDataSource,
  52. TUINotificationProtocol,
  53. TIMPopActionProtocol,
  54. TUIMessageBaseDataProviderDataSource_Two>
  55. @property(nonatomic, strong) TUIMessageDataProvider *messageDataProvider;
  56. @property(nonatomic, strong) TUIMessageCellData *menuUIMsg;
  57. @property(nonatomic, strong) TUIMessageCellData *reSendUIMsg;
  58. @property(nonatomic, strong) TUIChatPopMenu *chatPopMenu;
  59. @property(nonatomic, strong) TUIChatConversationModel *conversationData;
  60. @property(nonatomic, strong) UIActivityIndicatorView *indicatorView;
  61. @property(nonatomic, assign) BOOL isActive;
  62. @property(nonatomic, assign) BOOL showCheckBox;
  63. @property(nonatomic, assign) BOOL scrollingTriggeredByUser;
  64. @property(nonatomic, assign) BOOL isAutoScrolledToBottom;
  65. @property(nonatomic, assign) BOOL hasCoverPage;
  66. @property(nonatomic, strong) TUIMessageCellConfig *messageCellConfig;
  67. @property(nonatomic, strong) TUIVoiceMessageCellData *currentVoiceMsg;
  68. @end
  69. @implementation TUIBaseMessageController
  70. + (void)initialize {
  71. [TUIMessageDataProvider setDataSourceClass:self];
  72. }
  73. + (void)asyncGetDisplayString:(NSArray<V2TIMMessage *> *)messageList callback:(void(^)(NSDictionary<NSString *, NSString *> *))callback {
  74. [TUIMessageDataProvider asyncGetDisplayString:messageList callback:callback];
  75. }
  76. + (nullable NSString *)getDisplayString:(V2TIMMessage *)message {
  77. return [TUIMessageDataProvider getDisplayString:message];
  78. }
  79. #pragma mark - Life Cycle
  80. - (void)viewDidLoad {
  81. [super viewDidLoad];
  82. [self setupViews];
  83. [self registerEvents];
  84. self.isActive = YES;
  85. [TUITool addUnsupportNotificationInVC:self];
  86. [TUIMessageProgressManager.shareManager addDelegate:self];
  87. CGFloat offset = Bottom_SafeHeight > 0 ? Bottom_SafeHeight : 20;
  88. self.tableView.contentInset = UIEdgeInsetsMake(0, 0, offset, 0);
  89. }
  90. - (void)dealloc {
  91. [[NSNotificationCenter defaultCenter] removeObserver:self];
  92. [TUIMessageProgressManager.shareManager removeDelegate:self];
  93. [TUICore unRegisterEventByObject:self];
  94. NSLog(@"%s dealloc", __FUNCTION__);
  95. }
  96. - (void)viewWillAppear:(BOOL)animated {
  97. self.isInVC = YES;
  98. [super viewWillAppear:animated];
  99. }
  100. - (void)viewDidAppear:(BOOL)animated {
  101. [super viewDidAppear:animated];
  102. [self sendVisibleReadGroupMessages];
  103. [self limitReadReport];
  104. }
  105. - (void)viewDidDisappear:(BOOL)animated {
  106. [super viewDidDisappear:animated];
  107. self.isInVC = NO;
  108. }
  109. - (void)viewWillDisappear:(BOOL)animated {
  110. [super viewWillDisappear:animated];
  111. if (_currentVoiceMsg) {
  112. [_currentVoiceMsg stopVoiceMessage];
  113. }
  114. }
  115. - (void)applicationBecomeActive {
  116. self.isActive = YES;
  117. [self sendVisibleReadGroupMessages];
  118. }
  119. - (void)applicationEnterBackground {
  120. self.isActive = NO;
  121. }
  122. - (void)setupViews {
  123. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapViewController)];
  124. /**
  125. * Solve the problem that the touch event is not passed down, causing the gesture to conflict with the collectionView didselect
  126. */
  127. tap.cancelsTouchesInView = NO;
  128. [self.view addGestureRecognizer:tap];
  129. self.tableView.scrollsToTop = NO;
  130. [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
  131. self.tableView.backgroundColor = TUIChatDynamicColor(@"chat_controller_bg_color", @"#FFFFFF");
  132. self.indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, TMessageController_Header_Height)];
  133. self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
  134. self.tableView.tableHeaderView = self.indicatorView;
  135. if (!self.indicatorView.isAnimating) {
  136. [self.indicatorView startAnimating];
  137. }
  138. [self.messageCellConfig bindTableView:self.tableView];
  139. }
  140. - (void)registerEvents {
  141. [TUICore registerEvent:TUICore_TUIPluginNotify
  142. subKey:TUICore_TUIPluginNotify_PluginViewSizeChangedSubKey
  143. object:self];
  144. [TUICore registerEvent:TUICore_TUIPluginNotify
  145. subKey:TUICore_TUIPluginNotify_WillForwardTextSubKey
  146. object:self];
  147. [TUICore registerEvent:TUICore_TUIPluginNotify
  148. subKey:TUICore_TUIPluginNotify_DidChangePluginViewSubKey
  149. object:self];
  150. [[NSNotificationCenter defaultCenter] addObserver:self
  151. selector:@selector(applicationBecomeActive)
  152. name:UIApplicationDidBecomeActiveNotification
  153. object:nil];
  154. [[NSNotificationCenter defaultCenter] addObserver:self
  155. selector:@selector(applicationBecomeActive)
  156. name:UIApplicationWillEnterForegroundNotification
  157. object:nil];
  158. [[NSNotificationCenter defaultCenter] addObserver:self
  159. selector:@selector(applicationEnterBackground)
  160. name:UIApplicationDidEnterBackgroundNotification
  161. object:nil];
  162. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceivedSendMessageRequest:) name:TUIChatSendMessageNotification object:nil];
  163. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceivedSendMessageWithoutUpdateUIRequest:) name:TUIChatSendMessageWithoutUpdateUINotification object:nil];
  164. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceivedInsertMessageWithoutUpdateUIRequest:) name:TUIChatInsertMessageWithoutUpdateUINotification object:nil];
  165. }
  166. - (TUIMessageCellConfig *)messageCellConfig {
  167. if (_messageCellConfig == nil) {
  168. _messageCellConfig = [[TUIMessageCellConfig alloc] init];
  169. }
  170. return _messageCellConfig;
  171. }
  172. #pragma mark - Data Provider
  173. - (void)setConversation:(TUIChatConversationModel *)conversationData {
  174. self.conversationData = conversationData;
  175. if (!self.messageDataProvider) {
  176. self.messageDataProvider = [[TUIMessageDataProvider alloc] initWithConversationModel:conversationData];
  177. self.messageDataProvider.dataSource = self;
  178. self.messageDataProvider.dataSource_Two = self;
  179. }
  180. [self loadMessage];
  181. [self loadGroupInfo];
  182. }
  183. - (void)loadMessage {
  184. if (self.messageDataProvider.isLoadingData || self.messageDataProvider.isNoMoreMsg) {
  185. return;
  186. }
  187. __weak typeof(self) weakSelf = self;
  188. [self.messageDataProvider
  189. loadMessageSucceedBlock:^(BOOL isFirstLoad, BOOL isNoMoreMsg, NSArray<TUIMessageCellData *> *_Nonnull newMsgs) {
  190. if (isNoMoreMsg) {
  191. weakSelf.indicatorView.mm_h = 0;
  192. }
  193. if (newMsgs.count != 0) {
  194. [weakSelf.tableView reloadData];
  195. [weakSelf.tableView layoutIfNeeded];
  196. if (isFirstLoad) {
  197. [weakSelf scrollToBottom:NO];
  198. } else {
  199. CGFloat visibleHeight = 0;
  200. for (NSInteger i = 0; i < newMsgs.count; ++i) {
  201. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
  202. visibleHeight += [weakSelf tableView:weakSelf.tableView heightForRowAtIndexPath:indexPath];
  203. }
  204. if (isNoMoreMsg) {
  205. visibleHeight -= TMessageController_Header_Height;
  206. }
  207. [weakSelf.tableView scrollRectToVisible:CGRectMake(0, weakSelf.tableView.contentOffset.y + visibleHeight, weakSelf.tableView.frame.size.width,
  208. weakSelf.tableView.frame.size.height)
  209. animated:NO];
  210. }
  211. }
  212. }
  213. FailBlock:^(int code, NSString *desc) {
  214. [TUITool makeToastError:code msg:desc];
  215. }];
  216. }
  217. - (void)loadGroupInfo {
  218. if (self.conversationData.groupID.length > 0) {
  219. __weak typeof(self) weakSelf = self;
  220. [self.messageDataProvider getPinMessageList];
  221. [self.messageDataProvider loadGroupInfo:^{
  222. [weakSelf.messageDataProvider getSelfInfoInGroup:^{}];
  223. }];
  224. self.messageDataProvider.groupRoleChanged = ^(V2TIMGroupMemberRole role) {
  225. if (weakSelf.groupRoleChanged) {
  226. weakSelf.groupRoleChanged(role);
  227. }
  228. };
  229. self.messageDataProvider.pinGroupMessageChanged = ^(NSArray * _Nonnull groupPinList) {
  230. if (weakSelf.pinGroupMessageChanged) {
  231. weakSelf.pinGroupMessageChanged(groupPinList);
  232. }
  233. };
  234. }
  235. }
  236. - (void)clearUImsg {
  237. [self.messageDataProvider clearUIMsgList];
  238. [self.tableView reloadData];
  239. [self.tableView layoutIfNeeded];
  240. if (self.indicatorView.isAnimating) {
  241. [self.indicatorView stopAnimating];
  242. }
  243. }
  244. - (void)reloadAndScrollToBottomOfMessage:(NSString *)messageID needScroll:(BOOL)isNeedScroll {
  245. // Dispatch the task to RunLoop to ensure that they are executed after the UITableView refresh is complete.
  246. dispatch_async(dispatch_get_main_queue(), ^{
  247. [self reloadCellOfMessage:messageID];
  248. dispatch_async(dispatch_get_main_queue(), ^{
  249. if (isNeedScroll) {
  250. [self scrollCellToBottomOfMessage:messageID];
  251. }
  252. });
  253. });
  254. }
  255. - (void)reloadAndScrollToBottomOfMessage:(NSString *)messageID {
  256. [self reloadAndScrollToBottomOfMessage:messageID needScroll:YES];
  257. }
  258. - (void)reloadCellOfMessage:(NSString *)messageID {
  259. NSIndexPath *indexPath = [self indexPathOfMessage:messageID];
  260. // Disable animation when loading to avoid cell jumping.
  261. if (indexPath == nil) {
  262. return;
  263. }
  264. [UIView performWithoutAnimation:^{
  265. [self.tableView reloadRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationNone];
  266. }];
  267. }
  268. - (void)scrollCellToBottomOfMessage:(NSString *)messageID {
  269. if (self.hasCoverPage) {
  270. return;
  271. }
  272. NSIndexPath *indexPath = [self indexPathOfMessage:messageID];
  273. // Scroll the tableView only if the bottom of the cell is invisible.
  274. CGRect cellRect = [self.tableView rectForRowAtIndexPath:indexPath];
  275. CGRect tableViewRect = self.tableView.bounds;
  276. BOOL isBottomInvisible = (cellRect.origin.y < CGRectGetMaxY(tableViewRect) && CGRectGetMaxY(cellRect) > CGRectGetMaxY(tableViewRect)) ||
  277. (cellRect.origin.y >= CGRectGetMaxY(tableViewRect));
  278. if (isBottomInvisible) {
  279. [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  280. }
  281. if (self.isAutoScrolledToBottom) {
  282. [self scrollToBottom:YES];
  283. }
  284. }
  285. - (NSIndexPath *)indexPathOfMessage:(NSString *)messageID {
  286. for (int i = 0; i < self.messageDataProvider.uiMsgs.count; i++) {
  287. TUIMessageCellData *data = self.messageDataProvider.uiMsgs[i];
  288. if ([data.innerMessage.msgID isEqualToString:messageID]) {
  289. return [NSIndexPath indexPathForRow:i inSection:0];
  290. }
  291. }
  292. return nil;
  293. }
  294. #pragma mark - Event Response
  295. - (void)scrollToBottom:(BOOL)animate {
  296. // Do not call this interface frequently in a short period of time, as it will affect the UI experience.
  297. if (self.messageDataProvider.uiMsgs.count > 0) {
  298. NSIndexPath *bottom = [NSIndexPath indexPathForRow:self.messageDataProvider.uiMsgs.count - 1 inSection:0];
  299. [self.tableView scrollToRowAtIndexPath:bottom atScrollPosition:UITableViewScrollPositionBottom animated:animate];
  300. self.isAutoScrolledToBottom = YES;
  301. }
  302. }
  303. - (void)didTapViewController {
  304. if (self.delegate && [self.delegate respondsToSelector:@selector(didTapInMessageController:)]) {
  305. [self.delegate didTapInMessageController:self];
  306. }
  307. }
  308. - (void)sendPlaceHolderUIMessage:(TUIMessageCellData *)cellData {
  309. [self.messageDataProvider sendPlaceHolderUIMessage:cellData];
  310. [self scrollToBottom:YES];
  311. }
  312. - (void)sendUIMessage:(TUIMessageCellData *)cellData {
  313. @weakify(self);
  314. cellData.innerMessage.needReadReceipt = self.isMsgNeedReadReceipt;
  315. [self.messageDataProvider sendUIMsg:cellData
  316. toConversation:self.conversationData
  317. willSendBlock:^(BOOL isReSend, TUIMessageCellData *_Nonnull dateUIMsg) {
  318. @strongify(self);
  319. if ([cellData isKindOfClass:[TUIVideoMessageCellData class]]||
  320. [cellData isKindOfClass:[TUIImageMessageCellData class]]) {
  321. dispatch_async(dispatch_get_main_queue(), ^{
  322. [self scrollToBottom:YES];
  323. });
  324. } else {
  325. [self scrollToBottom:YES];
  326. }
  327. [self setUIMessageStatus:cellData status:Msg_Status_Sending_2];
  328. }
  329. SuccBlock:^{
  330. @strongify(self);
  331. [self reloadUIMessage:cellData];
  332. [self setUIMessageStatus:cellData status:Msg_Status_Succ];
  333. NSDictionary *param = @{
  334. TUICore_TUIChatNotify_SendMessageSubKey_Code : @0,
  335. TUICore_TUIChatNotify_SendMessageSubKey_Desc : @"",
  336. TUICore_TUIChatNotify_SendMessageSubKey_Message : cellData.innerMessage
  337. };
  338. [TUICore notifyEvent:TUICore_TUIChatNotify subKey:TUICore_TUIChatNotify_SendMessageSubKey object:self param:param];
  339. }
  340. FailBlock:^(int code, NSString *desc) {
  341. @strongify(self);
  342. [self reloadUIMessage:cellData];
  343. [self setUIMessageStatus:cellData status:Msg_Status_Fail];
  344. [self makeSendErrorHud:code desc:desc];
  345. NSDictionary *param = @{TUICore_TUIChatNotify_SendMessageSubKey_Code : @(code),
  346. TUICore_TUIChatNotify_SendMessageSubKey_Desc : desc};
  347. [TUICore notifyEvent:TUICore_TUIChatNotify subKey:TUICore_TUIChatNotify_SendMessageSubKey object:self param:param];
  348. }];
  349. }
  350. - (void)setUIMessageStatus:(TUIMessageCellData *)cellData status:(TMsgStatus)status {
  351. switch (status) {
  352. case Msg_Status_Init:
  353. case Msg_Status_Succ:
  354. case Msg_Status_Fail:
  355. {
  356. [self changeMsg:cellData status:status];
  357. }
  358. break;
  359. case Msg_Status_Sending:
  360. case Msg_Status_Sending_2:
  361. {
  362. int delay = 1;
  363. if ([cellData isKindOfClass:[TUIImageMessageCellData class]] ||
  364. [cellData isKindOfClass:[TUIVideoMessageCellData class]]) {
  365. delay = 0;
  366. }
  367. if (0 == delay) {
  368. [self changeMsg:cellData status:Msg_Status_Sending_2];
  369. } else {
  370. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  371. if (cellData.innerMessage.status == V2TIM_MSG_STATUS_SENDING) {
  372. [self changeMsg:cellData status:Msg_Status_Sending_2];
  373. }
  374. });
  375. }
  376. }
  377. break;
  378. default:
  379. break;
  380. }
  381. }
  382. - (void)makeSendErrorHud:(int)code desc:(NSString *)desc {
  383. // The text or image msg is sensitive, the cell height may change.
  384. if (code == 80001 || code == 80004) {
  385. [self scrollToBottom:YES];
  386. return;
  387. }
  388. NSString *errorMsg = @"";
  389. if (self.isMsgNeedReadReceipt && code == ERR_SDK_INTERFACE_NOT_SUPPORT) {
  390. errorMsg = [NSString stringWithFormat:@"%@%@", TUIKitLocalizableString(TUIKitErrorUnsupportIntefaceMessageRead),
  391. TUIKitLocalizableString(TUIKitErrorUnsupporInterfaceSuffix)];
  392. } else {
  393. errorMsg = [TUITool convertIMError:code msg:desc];
  394. }
  395. UIAlertController *ac = [UIAlertController alertControllerWithTitle:errorMsg message:nil preferredStyle:UIAlertControllerStyleAlert];
  396. [ac tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Confirm) style:UIAlertActionStyleDefault handler:nil]];
  397. [self presentViewController:ac animated:YES completion:nil];
  398. }
  399. - (void)sendMessage:(V2TIMMessage *)message {
  400. [self sendMessage:message placeHolderCellData:nil];
  401. }
  402. - (void)sendMessage:(V2TIMMessage *)message placeHolderCellData:(TUIMessageCellData *)placeHolderCellData {
  403. TUIMessageCellData *cellData = nil;
  404. if (message.elemType == V2TIM_ELEM_TYPE_CUSTOM) {
  405. cellData = [self.delegate messageController:self onNewMessage:message];
  406. cellData.innerMessage = message;
  407. }
  408. if (!cellData) {
  409. cellData = [TUIMessageDataProvider getCellData:message];
  410. }
  411. if (cellData) {
  412. cellData.placeHolderCellData = placeHolderCellData;
  413. cellData.identifier = [TUILogin getUserID];
  414. NSString *faceUrl = [TUILogin getFaceUrl];
  415. if (faceUrl.length > 0) {
  416. cellData.avatarUrl = [NSURL URLWithString:faceUrl];
  417. }
  418. [self sendUIMessage:cellData];
  419. }
  420. }
  421. - (void)reloadUIMessage:(TUIMessageCellData *)msg {
  422. // innerMessage maybe changed, reload it
  423. NSInteger index = [self.messageDataProvider.uiMsgs indexOfObject:msg];
  424. NSMutableArray *newUIMsgs = [self.messageDataProvider transUIMsgFromIMMsg:@[ msg.innerMessage ]];
  425. if (newUIMsgs.count == 0) {
  426. return;
  427. }
  428. TUIMessageCellData *newUIMsg = newUIMsgs.firstObject;
  429. @weakify(self)
  430. [self.messageDataProvider preProcessMessage:@[ newUIMsg ]
  431. callback:^{
  432. @strongify(self)
  433. [UIView performWithoutAnimation:^{
  434. [self.messageDataProvider replaceUIMsg:newUIMsg atIndex:index];
  435. [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]
  436. withRowAnimation:UITableViewRowAnimationNone];
  437. }];
  438. }];
  439. }
  440. - (void)changeMsg:(TUIMessageCellData *)msg status:(TMsgStatus)status {
  441. msg.status = status;
  442. NSInteger index = [self.messageDataProvider.uiMsgs indexOfObject:msg];
  443. if ([self.tableView numberOfRowsInSection:0] > index) {
  444. TUIMessageCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
  445. [cell fillWithData:msg];
  446. } else {
  447. NSLog(@"lack of cell");
  448. }
  449. [[NSNotificationCenter defaultCenter] postNotificationName:@"kTUINotifyMessageStatusChanged"
  450. object:nil
  451. userInfo:@{
  452. @"msg" : msg,
  453. @"status" : [NSNumber numberWithUnsignedInteger:status],
  454. @"msgSender" : self,
  455. }];
  456. }
  457. - (void)onReceivedSendMessageRequest:(NSNotification *)notification {
  458. NSDictionary *userInfo = notification.userInfo;
  459. if (!userInfo) {
  460. return;
  461. }
  462. V2TIMMessage *message = [userInfo objectForKey:TUICore_TUIChatService_SendMessageMethod_MsgKey];
  463. TUIMessageCellData *cellData = [userInfo objectForKey:TUICore_TUIChatService_SendMessageMethod_PlaceHolderUIMsgKey];
  464. if (cellData && !message) {
  465. [self sendPlaceHolderUIMessage:cellData];
  466. } else if (message) {
  467. [self sendMessage:message placeHolderCellData:cellData];
  468. }
  469. }
  470. - (void)onReceivedSendMessageWithoutUpdateUIRequest:(NSNotification *)notification {
  471. NSDictionary *userInfo = notification.userInfo;
  472. if (userInfo == nil) {
  473. return;
  474. }
  475. V2TIMMessage *message = [userInfo objectForKey:TUICore_TUIChatService_SendMessageMethodWithoutUpdateUI_MsgKey];
  476. if (message == nil) {
  477. return;
  478. }
  479. TUISendMessageAppendParams *param = [TUISendMessageAppendParams new];
  480. param.isOnlineUserOnly = YES;
  481. [TUIMessageDataProvider sendMessage:message
  482. toConversation:self.conversationData
  483. appendParams:param
  484. Progress:nil
  485. SuccBlock:^{
  486. NSLog(@"send message without updating UI succeed");
  487. }
  488. FailBlock:^(int code, NSString *desc) {
  489. NSLog(@"send message without updating UI failed, code: %d, desc: %@", code, desc);
  490. }];
  491. }
  492. - (void)onReceivedInsertMessageWithoutUpdateUIRequest:(NSNotification *)notification {
  493. NSDictionary *userInfo = notification.userInfo;
  494. if (userInfo == nil) {
  495. return;
  496. }
  497. V2TIMMessage *message = [userInfo objectForKey:@"message"];
  498. BOOL isNeedScrollToBottom = [userInfo objectForKey:@"needScrollToBottom"];
  499. if (message == nil) {
  500. return;
  501. }
  502. NSMutableArray *newUIMsgs = [self.messageDataProvider transUIMsgFromIMMsg:@[ message ]];
  503. if (newUIMsgs.count == 0) {
  504. return;
  505. }
  506. TUIMessageCellData *newUIMsg = newUIMsgs.firstObject;
  507. @weakify(self)
  508. [self.messageDataProvider preProcessMessage:@[ newUIMsg ]
  509. callback:^{
  510. @strongify(self)
  511. [UIView performWithoutAnimation:^{
  512. [self.tableView beginUpdates];
  513. @autoreleasepool {
  514. for (TUIMessageCellData *uiMsg in newUIMsgs) {
  515. [self.messageDataProvider addUIMsg:uiMsg];
  516. [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messageDataProvider.uiMsgs.count -1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
  517. }
  518. }
  519. [self.tableView endUpdates];
  520. if (isNeedScrollToBottom) {
  521. [self scrollToBottom:YES];
  522. }
  523. }];
  524. }];
  525. }
  526. #pragma mark - TUINotificationProtocol
  527. - (void)onNotifyEvent:(NSString *)key subKey:(NSString *)subKey object:(id)anObject param:(NSDictionary *)param {
  528. if ([key isEqualToString:TUICore_TUIPluginNotify] && [subKey isEqualToString:TUICore_TUIPluginNotify_PluginViewSizeChangedSubKey]) {
  529. V2TIMMessage *message = param[TUICore_TUIPluginNotify_PluginViewSizeChangedSubKey_Message];
  530. for (TUIMessageCellData *data in self.messageDataProvider.uiMsgs) {
  531. if (data.innerMessage == message) {
  532. [self.messageCellConfig removeHeightCacheOfMessageCellData:data];
  533. [self reloadAndScrollToBottomOfMessage:data.innerMessage.msgID];
  534. NSIndexPath *indexPath = [self indexPathOfMessage:data.innerMessage.msgID];
  535. [self.tableView beginUpdates];
  536. [self tableView:self.tableView heightForRowAtIndexPath:indexPath];
  537. [self.tableView endUpdates];
  538. break;
  539. }
  540. }
  541. } else if ([key isEqualToString: TUICore_TUIPluginNotify] && [subKey isEqualToString:TUICore_TUIPluginNotify_DidChangePluginViewSubKey]) {
  542. // Plugin View is Shown or content changed.
  543. TUIMessageCellData *data = param[TUICore_TUIPluginNotify_DidChangePluginViewSubKey_Data];
  544. BOOL isAllowScroll2Bottom = YES;
  545. if ([param[TUICore_TUIPluginNotify_DidChangePluginViewSubKey_isAllowScroll2Bottom] isEqualToString:@"0"] ) {
  546. isAllowScroll2Bottom = NO ;
  547. TUIMessageCellData *lasData = [self.messageDataProvider.uiMsgs lastObject];
  548. BOOL isInBottomPage = (self.tableView.contentSize.height - self.tableView.contentOffset.y
  549. <= Screen_Height);
  550. if ([lasData.msgID isEqualToString:data.msgID] && isInBottomPage) {
  551. isAllowScroll2Bottom = YES;
  552. }
  553. }
  554. [self.messageCellConfig removeHeightCacheOfMessageCellData:data];
  555. [self reloadAndScrollToBottomOfMessage:data.innerMessage.msgID needScroll:isAllowScroll2Bottom];
  556. } else if ([key isEqualToString:TUICore_TUIPluginNotify] && [subKey isEqualToString:TUICore_TUIPluginNotify_WillForwardTextSubKey]) {
  557. // Text will be forwarded.
  558. NSString *text = param[TUICore_TUIPluginNotify_WillForwardTextSubKey_Text];
  559. if (self.delegate && [self.delegate respondsToSelector:@selector(messageController:onForwardText:)]) {
  560. [self.delegate messageController:self onForwardText:text];
  561. }
  562. }
  563. }
  564. #pragma mark - TUIMessageProgressManagerDelegate
  565. - (void)onMessageSendingResultChanged:(TUIMessageSendingResultType)type messageID:(NSString *)msgID {
  566. // async
  567. __weak typeof(self) weakSelf = self;
  568. dispatch_async(dispatch_get_main_queue(), ^{
  569. for (TUIMessageCellData *cellData in weakSelf.messageDataProvider.uiMsgs) {
  570. if ([cellData.msgID isEqual:msgID]) {
  571. [weakSelf changeMsg:cellData status:(type == TUIMessageSendingResultTypeSucc) ? Msg_Status_Succ : Msg_Status_Fail];
  572. }
  573. }
  574. });
  575. }
  576. #pragma mark - TUIMessageBaseDataProviderDataSource
  577. + (Class)onGetCustomMessageCellDataClass:(NSString *)businessID {
  578. return [TUIMessageCellConfig getCustomMessageCellDataClass:businessID];
  579. }
  580. - (BOOL)isDataSourceConsistent {
  581. NSInteger dataSourceCount = self.messageDataProvider.uiMsgs.count;
  582. NSInteger tableViewCount = [self.tableView numberOfRowsInSection:0];
  583. if (dataSourceCount != tableViewCount) {
  584. NSLog(@"Data source and UI are inconsistent: Data source count = %ld, Table view count = %ld", (long)dataSourceCount, (long)tableViewCount);
  585. return NO;
  586. }
  587. return YES;
  588. }
  589. - (void)dataProviderDataSourceWillChange:(TUIMessageDataProvider *)dataProvider {
  590. [self.tableView beginUpdates];
  591. }
  592. - (void)dataProviderDataSourceChange:(TUIMessageDataProvider *)dataProvider
  593. withType:(TUIMessageBaseDataProviderDataSourceChangeType)type
  594. atIndex:(NSUInteger)index
  595. animation:(BOOL)animation {
  596. switch (type) {
  597. case TUIMessageBaseDataProviderDataSourceChangeTypeInsert:
  598. [self.tableView insertRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
  599. withRowAnimation:animation ? UITableViewRowAnimationFade : UITableViewRowAnimationNone];
  600. break;
  601. case TUIMessageBaseDataProviderDataSourceChangeTypeDelete:
  602. [self.tableView deleteRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
  603. withRowAnimation:animation ? UITableViewRowAnimationFade : UITableViewRowAnimationNone];
  604. break;
  605. case TUIMessageBaseDataProviderDataSourceChangeTypeReload:
  606. [self.tableView reloadRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
  607. withRowAnimation:animation ? UITableViewRowAnimationFade : UITableViewRowAnimationNone];
  608. break;
  609. default:
  610. break;
  611. }
  612. }
  613. - (void)dataProviderDataSourceDidChange:(TUIMessageDataProvider *)dataProvider {
  614. [self.tableView endUpdates];
  615. }
  616. - (void)dataProvider:(TUIMessageBaseDataProvider *)dataProvider onRemoveHeightCache:(TUIMessageCellData *)cellData {
  617. if (cellData) {
  618. [self.messageCellConfig removeHeightCacheOfMessageCellData:cellData];
  619. }
  620. }
  621. - (nullable TUIMessageCellData *)dataProvider:(TUIMessageDataProvider *)dataProvider CustomCellDataFromNewIMMessage:(V2TIMMessage *)msg {
  622. if (![msg.userID isEqualToString:self.conversationData.userID] && ![msg.groupID isEqualToString:self.conversationData.groupID]) {
  623. return nil;
  624. }
  625. if (msg.status == V2TIM_MSG_STATUS_LOCAL_REVOKED) {
  626. return nil;
  627. }
  628. if(msg.elemType == V2TIM_ELEM_TYPE_CUSTOM){
  629. NSDictionary *param = [NSJSONSerialization JSONObjectWithData:msg.customElem.data options:NSJSONReadingAllowFragments error:nil];
  630. if (param) {
  631. NSInteger type = [[MOSystemNormalCellData objectOrNilForKey:@"type" fromDictionary:param] integerValue];
  632. if(type == 100){
  633. TUIMessageCellData *cellData = [MOUserLinkCellData getCellData:msg];
  634. if(cellData){
  635. return cellData;
  636. }
  637. }
  638. else if (type == 101){
  639. TUIMessageCellData *cellData = [MOUserNotificationCellData getCellData:msg];
  640. if(cellData){
  641. return cellData;
  642. }
  643. }
  644. if(type > 0){
  645. TUIMessageCellData *cellData = [MOSystemNormalCellData getCellData:msg];
  646. if(cellData){
  647. return cellData;
  648. }
  649. }
  650. }
  651. }
  652. if ([self.delegate respondsToSelector:@selector(messageController:onNewMessage:)]) {
  653. TUIMessageCellData *customCellData = [self.delegate messageController:self onNewMessage:msg];
  654. if (customCellData) {
  655. customCellData.innerMessage = msg;
  656. return customCellData;
  657. }
  658. }
  659. return nil;
  660. }
  661. - (nullable V2TIMMessage *)dataProvider_Two:(TUIMessageBaseDataProvider *)dataProvider CustomCellDataFromNewIMMessage:(V2TIMMessage *)msg{
  662. if([self.delegate_Two respondsToSelector:@selector(messageController_Two:onNewMessage:)]) {
  663. V2TIMMessage *newMessage = [self.delegate_Two messageController_Two:self onNewMessage:msg];
  664. if(newMessage){
  665. return newMessage;
  666. }
  667. }
  668. return nil;
  669. }
  670. - (void)dataProvider:(TUIMessageDataProvider *)dataProvider ReceiveReadMsgWithUserID:(NSString *)userId Time:(time_t)timestamp {
  671. if (userId.length > 0 && [userId isEqualToString:self.conversationData.userID]) {
  672. for (int i = 0; i < self.messageDataProvider.uiMsgs.count; i++) {
  673. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.messageDataProvider.uiMsgs.count - 1 - i inSection:0];
  674. TUIMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  675. /**
  676. *
  677. * Determine whether the current unread needs to be changed to read by the callback timestamp
  678. */
  679. time_t msgTime = [cell.messageData.innerMessage.timestamp timeIntervalSince1970];
  680. if (msgTime <= timestamp && ![cell.readReceiptLabel.text isEqualToString:TIMCommonLocalizableString(Read)]) {
  681. cell.readReceiptLabel.text = TIMCommonLocalizableString(Read);
  682. }
  683. }
  684. }
  685. }
  686. - (void)dataProvider:(TUIMessageDataProvider *)dataProvider
  687. ReceiveReadMsgWithGroupID:(NSString *)groupID
  688. msgID:(NSString *)msgID
  689. readCount:(NSUInteger)readCount
  690. unreadCount:(NSUInteger)unreadCount {
  691. if (groupID != nil && ![groupID isEqualToString:self.conversationData.groupID]) {
  692. return;
  693. }
  694. NSInteger row = [self.messageDataProvider getIndexOfMessage:msgID];
  695. if (row < 0 || row >= self.messageDataProvider.uiMsgs.count) {
  696. return;
  697. }
  698. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
  699. TUIMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  700. [cell updateReadLabelText];
  701. }
  702. - (void)dataProvider:(TUIMessageDataProvider *)dataProvider ReceiveNewUIMsg:(TUIMessageCellData *)uiMsg {
  703. /**
  704. * When viewing historical messages, judge whether you need to slide to the bottom according to the current contentOffset
  705. */
  706. if (self.tableView.contentSize.height - self.tableView.contentOffset.y < Screen_Height * 1.5) {
  707. [self scrollToBottom:YES];
  708. if (self.isInVC && self.isActive) {
  709. [self.messageDataProvider sendLatestMessageReadReceipt];
  710. }
  711. }
  712. [self limitReadReport];
  713. }
  714. - (void)dataProvider:(TUIMessageDataProvider *)dataProvider ReceiveRevokeUIMsg:(TUIMessageCellData *)uiMsg {
  715. return;
  716. }
  717. #pragma mark - Private
  718. - (void)limitReadReport {
  719. static uint64_t lastTs = 0;
  720. uint64_t curTs = [[NSDate date] timeIntervalSince1970];
  721. /**
  722. * More than 1s && Not the first time, report immediately
  723. */
  724. if (curTs - lastTs >= 1 && lastTs) {
  725. lastTs = curTs;
  726. [self readReport];
  727. } else {
  728. /**
  729. * Less than 1s || First time, delay 1s and merge report
  730. */
  731. static BOOL delayReport = NO;
  732. if (delayReport) {
  733. return;
  734. }
  735. delayReport = YES;
  736. __weak typeof(self) weakSelf = self;
  737. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  738. [weakSelf readReport];
  739. delayReport = NO;
  740. });
  741. }
  742. }
  743. - (void)readReport {
  744. if (self.isInVC && self.isActive) {
  745. NSString *userID = self.conversationData.userID;
  746. if (userID.length > 0) {
  747. [TUIMessageDataProvider markC2CMessageAsRead:userID succ:nil fail:nil];
  748. }
  749. NSString *groupID = self.conversationData.groupID;
  750. if (groupID.length > 0) {
  751. [TUIMessageDataProvider markGroupMessageAsRead:groupID succ:nil fail:nil];
  752. }
  753. NSString *conversationID = @"";
  754. if (IS_NOT_EMPTY_NSSTRING(userID)) {
  755. conversationID = [NSString stringWithFormat:@"c2c_%@", userID];
  756. }
  757. if (IS_NOT_EMPTY_NSSTRING(groupID)) {
  758. conversationID = [NSString stringWithFormat:@"group_%@", groupID];
  759. }
  760. if (IS_NOT_EMPTY_NSSTRING(self.conversationData.conversationID)) {
  761. conversationID = self.conversationData.conversationID;
  762. }
  763. if (conversationID.length > 0) {
  764. [TUIMessageDataProvider markConversationAsUndead:@[ conversationID ] enableMark:NO];
  765. }
  766. }
  767. }
  768. /**
  769. * When the receiver sends a visible message read receipt:
  770. * 1. The time when messageVC is visible. You will be notified when [self viewDidAppear:] is invoked
  771. * 2. The time when scrollview scrolled to bottom by called [self scrollToBottom:] (For example, click the "x new message" tips in the lower right corner). You
  772. * will be notified when [UIScrollViewDelegate scrollViewDidEndScrollingAnimation:] is invoked.
  773. * + Note that you need to use the state of the scrollView to accurately determine whether the scrollView has really stopped sliding.
  774. * 3. The time when the user drags the scrollView continuously to view the message. You will be notified when [UIScrollViewDelegate scrollViewDidScroll:] is
  775. * invoked.
  776. * + Note here to determine whether the scrolling of the scrollView is triggered by user gestures (rather than automatic code triggers). So use the
  777. * self.scrollingTriggeredByUser flag to distinguish.
  778. * + The update logic of self.scrollingTriggeredByUser is as follows:
  779. * - Set YES when the user's finger touches the screen and starts to drag (scrollViewWillBeginDragging:);
  780. * - When the user's finger drags at a certain acceleration and leaves the screen, when the screen automatically stops sliding
  781. * (scrollViewDidEndDecelerating:), set to NO;
  782. * - No acceleration is applied after the user's finger slides, and when the user lifts the finger directly (scrollViewDidEndDragging:), set NO.
  783. * 4. When the user stays in the latest message interface and receives a new message at this time. Get notified in [self dataProvider:ReceiveNewUIMsg:] .
  784. */
  785. - (void)sendVisibleReadGroupMessages {
  786. if (self.isInVC && self.isActive) {
  787. NSRange range = [self calcVisibleCellRange];
  788. [self.messageDataProvider sendMessageReadReceiptAtIndexes:[self transferIndexFromRange:range]];
  789. }
  790. }
  791. - (NSRange)calcVisibleCellRange {
  792. NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
  793. if (indexPaths.count == 0) {
  794. return NSMakeRange(0, 0);
  795. }
  796. NSIndexPath *topmost = indexPaths.firstObject;
  797. NSIndexPath *downmost = indexPaths.lastObject;
  798. return NSMakeRange(topmost.row, downmost.row - topmost.row + 1);
  799. }
  800. - (NSArray *)transferIndexFromRange:(NSRange)range {
  801. NSMutableArray *index = [NSMutableArray array];
  802. NSInteger start = range.location;
  803. for (int i = 0; i < range.length; i++) {
  804. [index addObject:@(start + i)];
  805. }
  806. return index;
  807. }
  808. - (void)hideKeyboardIfNeeded {
  809. [self.view endEditing:YES];
  810. [TUITool.applicationKeywindow endEditing:YES];
  811. }
  812. - (CGFloat)getHeightFromMessageCellData:(TUIMessageCellData *)cellData {
  813. return [self.messageCellConfig getHeightFromMessageCellData:cellData];
  814. }
  815. #pragma mark - UITableViewDelegate
  816. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  817. return self.messageDataProvider.uiMsgs.count;
  818. }
  819. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  820. if (indexPath.row < self.messageDataProvider.uiMsgs.count) {
  821. TUIMessageCellData *cellData = self.messageDataProvider.uiMsgs[indexPath.row];
  822. if([cellData isKindOfClass:[MOSystemNormalCellData class]]){
  823. MOSystemNormalCellData *tempCellData = (MOSystemNormalCellData *)cellData;
  824. CGSize size = [tempCellData contentSize];
  825. if(size.height <= 0){
  826. size.height = 80.0;
  827. }
  828. return size.height;
  829. }
  830. else if ([cellData isKindOfClass:[MOUserLinkCellData class]]){
  831. MOUserLinkCellData *tempCellData = (MOUserLinkCellData *)cellData;
  832. CGSize size = [tempCellData contentSize];
  833. if(size.height <= 0){
  834. size.height = 100.0;
  835. }
  836. return size.height;
  837. }
  838. else if ([cellData isKindOfClass:[MOUserNotificationCellData class]]){
  839. MOUserNotificationCellData *tempCellData = (MOUserNotificationCellData *)cellData;
  840. CGSize size = [tempCellData contentSize];
  841. if(size.height <= 0){
  842. size.height = 52.0;
  843. }
  844. return size.height;
  845. }
  846. return [self.messageCellConfig getHeightFromMessageCellData:cellData];
  847. } else {
  848. return 0;
  849. }
  850. }
  851. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
  852. if (indexPath.row < self.messageDataProvider.uiMsgs.count) {
  853. TUIMessageCellData *cellData = self.messageDataProvider.uiMsgs[indexPath.row];
  854. return [self.messageCellConfig getEstimatedHeightFromMessageCellData:cellData];
  855. } else {
  856. return UITableViewAutomaticDimension;
  857. }
  858. }
  859. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  860. TUIMessageCellData *data = self.messageDataProvider.uiMsgs[indexPath.row];
  861. data.showCheckBox = self.showCheckBox && [self supportCheckBox:data];
  862. TUIMessageCell *cell = nil;
  863. if ([self.delegate respondsToSelector:@selector(messageController:onShowMessageData:)]) {
  864. cell = [self.delegate messageController:self onShowMessageData:data];
  865. if (cell) {
  866. cell.delegate = self;
  867. return cell;
  868. }
  869. }
  870. if([data isKindOfClass:[MOSystemNormalCellData class]] ||
  871. [data isKindOfClass:[MOUserLinkCellData class]] ||
  872. [data isKindOfClass:[MOUserNotificationCellData class]] ){
  873. cell = [tableView dequeueReusableCellWithIdentifier:data.reuseId forIndexPath:indexPath];
  874. [cell fillWithData:data];
  875. return cell;
  876. }
  877. if (!data.reuseId) {
  878. NSAssert(NO, @"Unknow cell");
  879. return nil;
  880. }
  881. cell = [tableView dequeueReusableCellWithIdentifier:data.reuseId forIndexPath:indexPath];
  882. TUIMessageCellData *oldData = cell.messageData;
  883. cell.delegate = self;
  884. [cell fillWithData:data];
  885. [cell notifyBottomContainerReadyOfData:oldData];
  886. return cell;
  887. }
  888. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  889. TUIMessageCell *uiMsg = (TUIMessageCell *)cell;
  890. if ([uiMsg isKindOfClass:TUIMessageCell.class] && [self.delegate respondsToSelector:@selector(messageController:willDisplayCell:withData:)]) {
  891. [self.delegate messageController:self willDisplayCell:uiMsg withData:uiMsg.messageData];
  892. }
  893. }
  894. - (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
  895. if (indexPath.row < self.messageDataProvider.uiMsgs.count) {
  896. TUITextMessageCellData *cellData = (TUITextMessageCellData *)self.messageDataProvider.uiMsgs[indexPath.row];
  897. // It will be deleted after TUICallKit intervenes according to the standard process.
  898. if ([cellData isKindOfClass:TUITextMessageCellData.class]) {
  899. if ((cellData.isAudioCall || cellData.isVideoCall) && cellData.showUnreadPoint) {
  900. cellData.innerMessage.localCustomInt = 1;
  901. cellData.showUnreadPoint = NO;
  902. }
  903. }
  904. [TUICore notifyEvent:TUICore_TUIChatNotify
  905. subKey:TUICore_TUIChatNotify_MessageDisplayedSubKey
  906. object:cellData
  907. param:nil];
  908. }
  909. }
  910. #pragma mark - UIScrollViewDelegate
  911. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  912. if (self.scrollingTriggeredByUser) {
  913. // only if the scrollView is dragged by user's finger to scroll, we need to send read receipts.
  914. [self sendVisibleReadGroupMessages];
  915. self.isAutoScrolledToBottom = NO;
  916. }
  917. }
  918. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  919. self.scrollingTriggeredByUser = YES;
  920. [self didTapViewController];
  921. }
  922. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  923. if ([self isScrollViewEndDragging:scrollView]) {
  924. // user presses on the scrolling scrollView and forces it to stop scrolling immediately.
  925. self.scrollingTriggeredByUser = NO;
  926. }
  927. }
  928. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  929. if ([self isScrollViewEndDecelerating:scrollView]) {
  930. // user drags the scrollView with a certain acceleration and makes a flick gesture, and scrollView will stop scrolling after decelerating.
  931. self.scrollingTriggeredByUser = NO;
  932. }
  933. }
  934. - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
  935. if ([self isScrollViewEndDecelerating:scrollView]) {
  936. // UIScrollView automatically stops scrolling, for example triggered after calling scrollToBottom
  937. [self sendVisibleReadGroupMessages];
  938. }
  939. }
  940. - (BOOL)isScrollViewEndDecelerating:(UIScrollView *)scrollView {
  941. return scrollView.tracking == 0 && scrollView.dragging == 0 && scrollView.decelerating == 0;
  942. }
  943. - (BOOL)isScrollViewEndDragging:(UIScrollView *)scrollView {
  944. return scrollView.tracking == 1 && scrollView.dragging == 0 && scrollView.decelerating == 0;
  945. }
  946. #pragma mark - TUIMessageCellDelegate
  947. - (void)onSelectMessage:(TUIMessageCell *)cell {
  948. if (TUIChatConfig.defaultConfig.eventConfig.chatEventListener &&
  949. [TUIChatConfig.defaultConfig.eventConfig.chatEventListener respondsToSelector:@selector(onMessageClicked:messageCellData:)]) {
  950. BOOL result = [TUIChatConfig.defaultConfig.eventConfig.chatEventListener onMessageClicked:cell messageCellData:cell.messageData];
  951. if (result) {
  952. return;
  953. }
  954. }
  955. if (cell.messageData.innerMessage.hasRiskContent) {
  956. if (![cell isKindOfClass:[TUIReferenceMessageCell class]]) {
  957. return;
  958. }
  959. }
  960. if (self.showCheckBox && [self supportCheckBox:(TUIMessageCellData *)cell.data]) {
  961. TUIMessageCellData *data = (TUIMessageCellData *)cell.data;
  962. data.selected = !data.selected;
  963. [self.tableView reloadData];
  964. return;
  965. }
  966. //Hide the keyboard when tapping on the message.
  967. [self hideKeyboardIfNeeded];
  968. if ([TUIMessageCellConfig isPluginCustomMessageCellData:cell.messageData]) {
  969. NSMutableDictionary *param = [NSMutableDictionary dictionary];
  970. if (cell) {
  971. param[TUICore_TUIPluginNotify_PluginCustomCellClick_Cell] = cell;
  972. }
  973. if (self.navigationController) {
  974. param[TUICore_TUIPluginNotify_PluginCustomCellClick_PushVC] = self.navigationController;
  975. }
  976. if (cell.pluginMsgSelectCallback) {
  977. cell.pluginMsgSelectCallback(param);
  978. }
  979. } else if ([cell isKindOfClass:[TUITextMessageCell class]]) {
  980. [self clickTextMessage:(TUITextMessageCell *)cell];
  981. } else if ([cell isKindOfClass:[TUISystemMessageCell class]]) {
  982. [self clickSystemMessage:(TUISystemMessageCell *)cell];
  983. } else if ([cell isKindOfClass:[TUIVoiceMessageCell class]]) {
  984. [self playVoiceMessage:(TUIVoiceMessageCell *)cell];
  985. } else if ([cell isKindOfClass:[TUIImageMessageCell class]]) {
  986. [self showImageMessage:(TUIImageMessageCell *)cell];
  987. } else if ([cell isKindOfClass:[TUIVideoMessageCell class]]) {
  988. [self showVideoMessage:(TUIVideoMessageCell *)cell];
  989. } else if ([cell isKindOfClass:[TUIFileMessageCell class]]) {
  990. [self showFileMessage:(TUIFileMessageCell *)cell];
  991. } else if ([cell isKindOfClass:[TUIMergeMessageCell class]]) {
  992. [self showRelayMessage:(TUIMergeMessageCell *)cell];
  993. } else if ([cell isKindOfClass:[TUILinkCell class]]) {
  994. [self showLinkMessage:(TUILinkCell *)cell];
  995. } else if ([cell isKindOfClass:TUIReplyMessageCell.class]) {
  996. [self showReplyMessage:(TUIReplyMessageCell *)cell];
  997. } else if ([cell isKindOfClass:TUIReferenceMessageCell.class]) {
  998. [self showReplyMessage:(TUIReplyMessageCell *)cell];
  999. } else if ([cell isKindOfClass:TUIOrderCell.class]) {
  1000. [self showOrderMessage:(TUIOrderCell *)cell];
  1001. }
  1002. if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageContent:)]) {
  1003. [self.delegate messageController:self onSelectMessageContent:cell];
  1004. }
  1005. }
  1006. - (void)onLongPressMessage:(TUIMessageCell *)cell {
  1007. if (TUIChatConfig.defaultConfig.eventConfig.chatEventListener &&
  1008. [TUIChatConfig.defaultConfig.eventConfig.chatEventListener respondsToSelector:@selector(onMessageLongClicked:messageCellData:)]) {
  1009. BOOL result = [TUIChatConfig.defaultConfig.eventConfig.chatEventListener onMessageLongClicked:cell messageCellData:cell.messageData];
  1010. if (result) {
  1011. return;
  1012. }
  1013. }
  1014. [UIApplication.sharedApplication.keyWindow endEditing:NO];
  1015. TUIMessageCellData *data = cell.messageData;
  1016. if (![data canLongPress]) {
  1017. return;
  1018. }
  1019. if ([data isKindOfClass:[TUISystemMessageCellData class]]) {
  1020. return;
  1021. }
  1022. self.menuUIMsg = data;
  1023. if (self.chatPopMenu && self.chatPopMenu.superview) {
  1024. //The pop-up menu can only appear one at a time.
  1025. return;
  1026. }
  1027. TUIChatPopMenu *menu = [[TUIChatPopMenu alloc] initWithEmojiView:YES frame:CGRectZero];
  1028. self.chatPopMenu = menu;
  1029. menu.targetCellData = data;
  1030. menu.targetCell = cell;
  1031. __weak typeof(menu) weakMenu = menu;
  1032. BOOL isPluginCustomMessage = [TUIMessageCellConfig isPluginCustomMessageCellData:data];
  1033. BOOL isChatNoramlMessageOrCustomMessage = !isPluginCustomMessage;
  1034. // Insert Action
  1035. if (isChatNoramlMessageOrCustomMessage) {
  1036. // Chat common Action
  1037. [self addChatCommonActionToCell:cell ofMenu:menu];
  1038. } else {
  1039. // Plugin common Action
  1040. // MultiSelect/Quote/Reply/Pin/Delete
  1041. [self addChatPluginCommonActionToCell:cell ofMenu:menu];
  1042. }
  1043. // Actions from extension
  1044. [self addExtensionActionToCell:cell ofMenu:menu];
  1045. if ([data isKindOfClass:[TUITextMessageCellData class]]) {
  1046. /**
  1047. * becomeFirstResponder ,,。
  1048. * When the text message is selected, it will becomeFirstResponder by default, causing the keyboard to disappear and the interface to be chaotic. Here,
  1049. * the keyboard that has popped up is put away first.
  1050. */
  1051. TUITextMessageCell *textCell = (TUITextMessageCell *)cell;
  1052. [textCell.textView becomeFirstResponder];
  1053. [textCell.textView selectAll:self];
  1054. } else if ([data isKindOfClass:[TUIReferenceMessageCellData class]]) {
  1055. TUIReferenceMessageCell *referenceCell = (TUIReferenceMessageCell *)cell;
  1056. [referenceCell.textView becomeFirstResponder];
  1057. [referenceCell.textView selectAll:self];
  1058. }
  1059. BOOL isFirstResponder = NO;
  1060. if (_delegate && [_delegate respondsToSelector:@selector(messageController:willShowMenuInCell:)]) {
  1061. isFirstResponder = [_delegate messageController:self willShowMenuInCell:cell];
  1062. }
  1063. if (isFirstResponder) {
  1064. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidHide:) name:UIMenuControllerDidHideMenuNotification object:nil];
  1065. } else {
  1066. [self becomeFirstResponder];
  1067. }
  1068. CGRect frame = [UIApplication.sharedApplication.keyWindow convertRect:cell.container.frame fromView:cell];
  1069. CGFloat topMarginiByCustomView = 0;
  1070. if (_delegate && [_delegate respondsToSelector:@selector(getTopMarginByCustomView)]) {
  1071. topMarginiByCustomView = [_delegate getTopMarginByCustomView];
  1072. }
  1073. [menu setArrawPosition:CGPointMake(frame.origin.x + frame.size.width * 0.5, frame.origin.y - 5 - topMarginiByCustomView)
  1074. adjustHeight:frame.size.height + 5];
  1075. [menu showInView:self.tableView];
  1076. [self configSelectActionToCell:cell ofMenu:menu];
  1077. }
  1078. - (void)addChatCommonActionToCell:(TUIMessageCell *)cell ofMenu:(TUIChatPopMenu *)menu {
  1079. // Setup popAction
  1080. TUIChatPopMenuAction *copyAction = [self setupCopyAction:cell];
  1081. TUIChatPopMenuAction *deleteAction = [self setupDeleteAction:cell];
  1082. TUIChatPopMenuAction *recallAction = [self setupRecallAction:cell];
  1083. TUIChatPopMenuAction *multiAction = [self setupMulitSelectAction:cell];
  1084. TUIChatPopMenuAction *forwardAction = [self setupForwardAction:cell];
  1085. TUIChatPopMenuAction *replyAction = [self setupReplyAction:cell];
  1086. TUIChatPopMenuAction *quoteAction = [self setupQuoteAction:cell];
  1087. TUIChatPopMenuAction *audioPlaybackStyleAction = [self setupAudioPlaybackStyleAction:cell];
  1088. TUIChatPopMenuAction *groupPinAction = [self setupGroupPinAction:cell];
  1089. TUIMessageCellData *data = cell.messageData;
  1090. V2TIMMessage *imMsg = data.innerMessage;
  1091. BOOL isMsgSendSucceed = imMsg.status == V2TIM_MSG_STATUS_SEND_SUCC;
  1092. BOOL isContentModerated = imMsg.hasRiskContent;
  1093. if (imMsg.soundElem) {
  1094. [menu addAction:audioPlaybackStyleAction];
  1095. }
  1096. if (([data isKindOfClass:[TUITextMessageCellData class]] || [data isKindOfClass:TUIReplyMessageCellData.class] ||
  1097. [data isKindOfClass:TUIReferenceMessageCellData.class]) && !isContentModerated) {
  1098. [menu addAction:copyAction];
  1099. }
  1100. [menu addAction:deleteAction];
  1101. if (!isContentModerated) {
  1102. [menu addAction:multiAction];
  1103. }
  1104. if (imMsg && [imMsg isSelf] && [[NSDate date] timeIntervalSinceDate:imMsg.timestamp] < TUIChatConfig.defaultConfig.timeIntervalForMessageRecall && isMsgSendSucceed) {
  1105. [menu addAction:recallAction];
  1106. }
  1107. if ([self canForward:data] && isMsgSendSucceed && !isContentModerated) {
  1108. [menu addAction:forwardAction];
  1109. }
  1110. if (isMsgSendSucceed && !isContentModerated) {
  1111. [menu addAction:replyAction];
  1112. }
  1113. if (isMsgSendSucceed && !isContentModerated) {
  1114. [menu addAction:quoteAction];
  1115. }
  1116. BOOL isGroup = (data.innerMessage.groupID.length > 0);
  1117. if (isGroup && [self.messageDataProvider isCurrentUserRoleSuperAdminInGroup] && isMsgSendSucceed && !isContentModerated) {
  1118. [menu addAction:groupPinAction];
  1119. }
  1120. }
  1121. - (void)addChatPluginCommonActionToCell:(TUIMessageCell *)cell ofMenu:(TUIChatPopMenu *)menu {
  1122. // Setup popAction
  1123. TUIChatPopMenuAction *deleteAction = [self setupDeleteAction:cell];
  1124. TUIChatPopMenuAction *recallAction = [self setupRecallAction:cell];
  1125. TUIChatPopMenuAction *multiAction = [self setupMulitSelectAction:cell];
  1126. TUIChatPopMenuAction *replyAction = [self setupReplyAction:cell];
  1127. TUIChatPopMenuAction *quoteAction = [self setupQuoteAction:cell];
  1128. TUIChatPopMenuAction *pinAction = [self setupGroupPinAction:cell];
  1129. TUIMessageCellData *data = cell.messageData;
  1130. V2TIMMessage *imMsg = data.innerMessage;
  1131. BOOL isContentModerated = imMsg.hasRiskContent;
  1132. BOOL isMsgSendSucceed = imMsg.status == V2TIM_MSG_STATUS_SEND_SUCC;
  1133. [menu addAction:multiAction];
  1134. if (isMsgSendSucceed) {
  1135. [menu addAction:replyAction];
  1136. [menu addAction:quoteAction];
  1137. }
  1138. BOOL isGroup = (data.innerMessage.groupID.length > 0);
  1139. if (isGroup && [self.messageDataProvider isCurrentUserRoleSuperAdminInGroup] && isMsgSendSucceed && !isContentModerated) {
  1140. [menu addAction:pinAction];
  1141. }
  1142. [menu addAction:deleteAction];
  1143. if (imMsg && [imMsg isSelf] && [[NSDate date] timeIntervalSinceDate:imMsg.timestamp] < TUIChatConfig.defaultConfig.timeIntervalForMessageRecall && isMsgSendSucceed) {
  1144. [menu addAction:recallAction];
  1145. }
  1146. }
  1147. - (void)addExtensionActionToCell:(TUIMessageCell *)cell ofMenu:(TUIChatPopMenu *)menu {
  1148. // extra
  1149. NSArray<TUIExtensionInfo *> *infoArray =
  1150. [TUICore getExtensionList:TUICore_TUIChatExtension_PopMenuActionItem_ClassicExtensionID
  1151. param:@{TUICore_TUIChatExtension_PopMenuActionItem_TargetVC : self, TUICore_TUIChatExtension_PopMenuActionItem_ClickCell : cell}];
  1152. for (TUIExtensionInfo *info in infoArray) {
  1153. if (info.text && info.icon && info.onClicked) {
  1154. TUIChatPopMenuAction *extension = [[TUIChatPopMenuAction alloc] initWithTitle:info.text
  1155. image:info.icon
  1156. weight:info.weight
  1157. callback:^{
  1158. info.onClicked(@{});
  1159. }];
  1160. [menu addAction:extension];
  1161. }
  1162. }
  1163. }
  1164. - (void)configSelectActionToCell:(TUIMessageCell *)cell ofMenu:(TUIChatPopMenu *)menu {
  1165. // Setup popAction
  1166. TUIChatPopMenuAction *copyAction = [self setupCopyAction:cell];
  1167. TUIChatPopMenuAction *deleteAction = [self setupDeleteAction:cell];
  1168. TUIChatPopMenuAction *multiAction = [self setupMulitSelectAction:cell];
  1169. TUIChatPopMenuAction *forwardAction = [self setupForwardAction:cell];
  1170. TUIChatPopMenuAction *replyAction = [self setupReplyAction:cell];
  1171. TUIChatPopMenuAction *quoteAction = [self setupQuoteAction:cell];
  1172. TUIChatPopMenuAction *groupPinAction = [self setupGroupPinAction:cell];
  1173. TUIMessageCellData *data = cell.messageData;
  1174. BOOL isGroup = (data.innerMessage.groupID.length > 0);
  1175. //Chat common Action special operator
  1176. @weakify(self);
  1177. @weakify(cell);
  1178. @weakify(menu);
  1179. __block BOOL isSelectAll = YES;
  1180. void (^selectAllContentCallback)(BOOL) = ^(BOOL selectAll) {
  1181. @strongify(self);
  1182. @strongify(cell);
  1183. @strongify(menu);
  1184. if (isSelectAll == selectAll) {
  1185. return;
  1186. }
  1187. isSelectAll = selectAll;
  1188. [menu removeAllAction];
  1189. if (isSelectAll) {
  1190. [menu addAction:copyAction];
  1191. [menu addAction:deleteAction];
  1192. [menu addAction:multiAction];
  1193. if ([self canForward:data]) {
  1194. [menu addAction:forwardAction];
  1195. }
  1196. [menu addAction:replyAction];
  1197. [menu addAction:quoteAction];
  1198. if (isGroup && [self.messageDataProvider isCurrentUserRoleSuperAdminInGroup]) {
  1199. [menu addAction:groupPinAction];
  1200. }
  1201. } else {
  1202. [menu addAction:copyAction];
  1203. if ([self canForward:data]) {
  1204. [menu addAction:forwardAction];
  1205. }
  1206. }
  1207. // Select all or not may affect the action menu
  1208. [self addExtensionActionToCell:cell ofMenu:menu];
  1209. [menu layoutSubview];
  1210. };
  1211. /**
  1212. * If it is a text type message, set the text message cursor selected state, if the text is not all selected state, only keep copy and forward
  1213. */
  1214. if ([data isKindOfClass:[TUITextMessageCellData class]]) {
  1215. TUITextMessageCell *textCell = (TUITextMessageCell *)cell;
  1216. [textCell.textView selectAll:self];
  1217. textCell.selectAllContentContent = selectAllContentCallback;
  1218. menu.hideCallback = ^{
  1219. [textCell.textView setSelectedTextRange:nil];
  1220. };
  1221. }
  1222. if ([data isKindOfClass:[TUIReferenceMessageCellData class]] || [data isKindOfClass:[TUIReplyMessageCellData class]]) {
  1223. TUIReplyMessageCell *textCell = (TUIReplyMessageCell *)cell;
  1224. [textCell.textView selectAll:self];
  1225. textCell.selectAllContentContent = selectAllContentCallback;
  1226. menu.hideCallback = ^{
  1227. [textCell.textView setSelectedTextRange:nil];
  1228. };
  1229. };
  1230. }
  1231. - (TUIChatPopMenuAction *)setupCopyAction:(TUIMessageCell *)cell {
  1232. BOOL isCopyShown = [TUIChatConfig defaultConfig].enablePopMenuCopyAction;
  1233. TUIChatPopMenuAction *copyAction = nil;
  1234. @weakify(self);
  1235. @weakify(cell);
  1236. copyAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Copy)
  1237. image:TUIChatBundleThemeImage(@"chat_icon_copy_img", @"icon_copy")
  1238. weight:10000
  1239. callback:^{
  1240. @strongify(self);
  1241. @strongify(cell);
  1242. [self onCopyMsg:cell];
  1243. }];
  1244. return isCopyShown ? copyAction : nil;
  1245. }
  1246. - (TUIChatPopMenuAction *)setupDeleteAction:(TUIMessageCell *)cell {
  1247. BOOL isDeleteShown = [TUIChatConfig defaultConfig].enablePopMenuDeleteAction;
  1248. @weakify(self);
  1249. TUIChatPopMenuAction *deleteAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Delete)
  1250. image:TUIChatBundleThemeImage(@"chat_icon_delete_img", @"icon_delete")
  1251. weight:3000
  1252. callback:^{
  1253. @strongify(self);
  1254. [self onDelete:nil];
  1255. }];
  1256. return isDeleteShown ? deleteAction : nil;
  1257. }
  1258. - (TUIChatPopMenuAction *)setupRecallAction:(TUIMessageCell *)cell {
  1259. BOOL isRecallShown = [TUIChatConfig defaultConfig].enablePopMenuRecallAction;
  1260. TUIChatPopMenuAction *recallAction = nil;
  1261. TUIMessageCellData *data = cell.messageData;
  1262. V2TIMMessage *imMsg = data.innerMessage;
  1263. @weakify(self);
  1264. recallAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Revoke)
  1265. image:TUIChatBundleThemeImage(@"chat_icon_recall_img", @"icon_recall")
  1266. weight:4000
  1267. callback:^{
  1268. @strongify(self);
  1269. [self onRevoke:nil];
  1270. }];
  1271. return isRecallShown ? recallAction : nil;
  1272. }
  1273. - (TUIChatPopMenuAction *)setupMulitSelectAction:(TUIMessageCell *)cell {
  1274. BOOL isSelectShown = [TUIChatConfig defaultConfig].enablePopMenuSelectAction;
  1275. @weakify(self);
  1276. TUIChatPopMenuAction *multiAction = nil;
  1277. multiAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Multiple)
  1278. image:TUIChatBundleThemeImage(@"chat_icon_multi_img", @"icon_multi")
  1279. weight:8000
  1280. callback:^{
  1281. @strongify(self);
  1282. [self onMulitSelect:nil];
  1283. }];
  1284. return isSelectShown ? multiAction : nil;
  1285. }
  1286. - (TUIChatPopMenuAction *)setupForwardAction:(TUIMessageCell *)cell {
  1287. BOOL isForwardShown = [TUIChatConfig defaultConfig].enablePopMenuForwardAction;
  1288. @weakify(self);
  1289. TUIChatPopMenuAction *forwardAction = nil;
  1290. forwardAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Forward)
  1291. image:TUIChatBundleThemeImage(@"chat_icon_forward_img", @"icon_forward")
  1292. weight:9000
  1293. callback:^{
  1294. @strongify(self);
  1295. [self onForward:nil];
  1296. }];
  1297. return isForwardShown ? forwardAction : nil;
  1298. }
  1299. - (TUIChatPopMenuAction *)setupReplyAction:(TUIMessageCell *)cell {
  1300. BOOL isReplyShown = [TUIChatConfig defaultConfig].enablePopMenuReplyAction;
  1301. @weakify(self);
  1302. TUIChatPopMenuAction *replyAction = nil;
  1303. replyAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(Reply)
  1304. image:TUIChatBundleThemeImage(@"chat_icon_reply_img", @"icon_reply")
  1305. weight:5000
  1306. callback:^{
  1307. @strongify(self);
  1308. [self onReply:nil];
  1309. }];
  1310. return isReplyShown ? replyAction : nil;
  1311. }
  1312. - (TUIChatPopMenuAction *)setupQuoteAction:(TUIMessageCell *)cell {
  1313. BOOL isQuoteShown = [TUIChatConfig defaultConfig].enablePopMenuReferenceAction;
  1314. @weakify(self);
  1315. TUIChatPopMenuAction *quoteAction = nil;
  1316. quoteAction = [[TUIChatPopMenuAction alloc] initWithTitle:TIMCommonLocalizableString(TUIKitReference)
  1317. image:TUIChatBundleThemeImage(@"chat_icon_reference_img", @"icon_reference")
  1318. weight:7000
  1319. callback:^{
  1320. @strongify(self);
  1321. [self onReference:nil];
  1322. }];
  1323. return isQuoteShown ? quoteAction : nil;
  1324. }
  1325. - (TUIChatPopMenuAction *)setupAudioPlaybackStyleAction:(TUIMessageCell *)cell {
  1326. BOOL isPlaybackShown = [TUIChatConfig defaultConfig].enablePopMenuAudioPlaybackAction;
  1327. @weakify(self);
  1328. TUIChatPopMenuAction *audioPlaybackStyleAction = nil;
  1329. __weak typeof(audioPlaybackStyleAction) weakAction = audioPlaybackStyleAction;
  1330. TUIVoiceAudioPlaybackStyle originStyle = [TUIVoiceMessageCellData getAudioplaybackStyle];
  1331. NSString *title = @"";
  1332. UIImage *img = nil;
  1333. if (originStyle == TUIVoiceAudioPlaybackStyleLoudspeaker) {
  1334. title = TIMCommonLocalizableString(TUIKitAudioPlaybackStyleHandset);
  1335. img = TUIChatBundleThemeImage(@"chat_icon_audio_handset_img", @"icon_handset");
  1336. }
  1337. else {
  1338. title = TIMCommonLocalizableString(TUIKitAudioPlaybackStyleLoudspeaker);
  1339. img = TUIChatBundleThemeImage(@"chat_icon_audio_loudspeaker_img", @"icon_loudspeaker");
  1340. }
  1341. audioPlaybackStyleAction = [[TUIChatPopMenuAction alloc] initWithTitle:title
  1342. image:img
  1343. weight:11000
  1344. callback:^{
  1345. if (originStyle == TUIVoiceAudioPlaybackStyleLoudspeaker) {
  1346. //Change To Handset
  1347. weakAction.title = TIMCommonLocalizableString(TUIKitAudioPlaybackStyleLoudspeaker);
  1348. [TUITool hideToast];
  1349. [TUITool makeToast:TIMCommonLocalizableString(TUIKitAudioPlaybackStyleChange2Handset) duration:2];
  1350. }
  1351. else {
  1352. weakAction.title = TIMCommonLocalizableString(TUIKitAudioPlaybackStyleHandset);
  1353. [TUITool hideToast];
  1354. [TUITool makeToast:TIMCommonLocalizableString(TUIKitAudioPlaybackStyleChange2Loudspeaker) duration:2];
  1355. }
  1356. [TUIVoiceMessageCellData changeAudioPlaybackStyle];
  1357. }];
  1358. return isPlaybackShown ? audioPlaybackStyleAction : nil;
  1359. }
  1360. - (TUIChatPopMenuAction *)setupGroupPinAction:(TUIMessageCell *)cell {
  1361. BOOL isPinShown = [TUIChatConfig defaultConfig].enablePopMenuPinAction;
  1362. @weakify(self);
  1363. BOOL isPinned = [self.messageDataProvider isCurrentMessagePin:self.menuUIMsg.innerMessage.msgID];
  1364. TUIChatPopMenuAction *groupPinAction = nil;
  1365. UIImage* img =
  1366. isPinned ? TUIChatBundleThemeImage(@"chat_icon_group_unpin_img", @"icon_unpin") : TUIChatBundleThemeImage(@"chat_icon_group_pin_img", @"icon_pin");
  1367. groupPinAction = [[TUIChatPopMenuAction alloc] initWithTitle:isPinned?
  1368. TIMCommonLocalizableString(TUIKitGroupMessageUnPin) : TIMCommonLocalizableString(TUIKitGroupMessagePin)
  1369. image:img
  1370. weight:2900
  1371. callback:^{
  1372. @strongify(self);
  1373. [self onGroupPin:nil currentStatus:isPinned];
  1374. }];
  1375. return isPinShown ? groupPinAction : nil;
  1376. }
  1377. - (BOOL)canForward:(TUIMessageCellData *)data {
  1378. return ![TUIMessageCellConfig isPluginCustomMessageCellData:data];
  1379. }
  1380. - (void)onLongSelectMessageAvatar:(TUIMessageCell *)cell {
  1381. if (TUIChatConfig.defaultConfig.eventConfig.chatEventListener &&
  1382. [TUIChatConfig.defaultConfig.eventConfig.chatEventListener respondsToSelector:@selector(onUserIconLongClicked:messageCellData:)]) {
  1383. BOOL result = [TUIChatConfig.defaultConfig.eventConfig.chatEventListener onUserIconLongClicked:cell messageCellData:cell.messageData];
  1384. if (result) {
  1385. return;
  1386. }
  1387. }
  1388. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onLongSelectMessageAvatar:)]) {
  1389. [_delegate messageController:self onLongSelectMessageAvatar:cell];
  1390. }
  1391. }
  1392. - (void)onRetryMessage:(TUIMessageCell *)cell {
  1393. BOOL hasRiskContent = cell.messageData.innerMessage.hasRiskContent;
  1394. if (hasRiskContent) {
  1395. return;
  1396. }
  1397. _reSendUIMsg = cell.messageData;
  1398. __weak typeof(self) weakSelf = self;
  1399. UIAlertController *alert = [UIAlertController alertControllerWithTitle:TIMCommonLocalizableString(TUIKitTipsConfirmResendMessage)
  1400. message:nil
  1401. preferredStyle:UIAlertControllerStyleAlert];
  1402. [alert tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Re_send)
  1403. style:UIAlertActionStyleDefault
  1404. handler:^(UIAlertAction *_Nonnull action) {
  1405. [weakSelf sendUIMessage:weakSelf.reSendUIMsg];
  1406. }]];
  1407. [alert tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Cancel)
  1408. style:UIAlertActionStyleCancel
  1409. handler:^(UIAlertAction *_Nonnull action){
  1410. }]];
  1411. [self.navigationController presentViewController:alert animated:YES completion:nil];
  1412. }
  1413. - (void)onSelectMessageAvatar:(TUIMessageCell *)cell {
  1414. if (TUIChatConfig.defaultConfig.eventConfig.chatEventListener &&
  1415. [TUIChatConfig.defaultConfig.eventConfig.chatEventListener respondsToSelector:@selector(onUserIconClicked:messageCellData:)]) {
  1416. BOOL result = [TUIChatConfig.defaultConfig.eventConfig.chatEventListener onUserIconClicked:cell messageCellData:cell.messageData];
  1417. if (result) {
  1418. return;
  1419. }
  1420. }
  1421. if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageAvatar:)]) {
  1422. [self.delegate messageController:self onSelectMessageAvatar:cell];
  1423. }
  1424. }
  1425. - (void)onSelectReadReceipt:(TUIMessageCellData *)data {
  1426. @weakify(self);
  1427. if (data.innerMessage.groupID.length > 0) {
  1428. // Navigate to group message read VC. Should get members first.
  1429. [TUIMessageDataProvider getMessageReadReceipt:@[ data.innerMessage ]
  1430. succ:^(NSArray<V2TIMMessageReceipt *> *receiptList) {
  1431. @strongify(self);
  1432. if (receiptList.count == 0) {
  1433. return;
  1434. }
  1435. // To avoid the labels in messageReadVC displaying all 0 which is not accurate, try to get message read count before navigation.
  1436. V2TIMMessageReceipt *receipt = receiptList.firstObject;
  1437. data.messageReceipt = receipt;
  1438. [self pushMessageReadViewController:data];
  1439. }
  1440. fail:^(int code, NSString *desc) {
  1441. @strongify(self);
  1442. [self pushMessageReadViewController:data];
  1443. }];
  1444. } else {
  1445. // navigate to c2c message read VC. No need to get member.
  1446. [self pushMessageReadViewController:data];
  1447. }
  1448. }
  1449. - (void)pushMessageReadViewController:(TUIMessageCellData *)data {
  1450. self.hasCoverPage = YES;
  1451. TUIMessageReadViewController *controller = [[TUIMessageReadViewController alloc] initWithCellData:data
  1452. dataProvider:self.messageDataProvider
  1453. showReadStatusDisable:NO
  1454. c2cReceiverName:self.conversationData.title
  1455. c2cReceiverAvatar:self.conversationData.faceUrl];
  1456. [self.navigationController pushViewController:controller animated:YES];
  1457. __weak typeof(self) weakSelf = self;
  1458. controller.viewWillDismissHandler = ^{
  1459. weakSelf.hasCoverPage = NO;
  1460. };
  1461. }
  1462. - (void)onJumpToRepliesDetailPage:(TUIMessageCellData *)data {
  1463. self.hasCoverPage = YES;
  1464. TUIRepliesDetailViewController *repliesDetailVC = [[TUIRepliesDetailViewController alloc] initWithCellData:data conversationData:self.conversationData];
  1465. repliesDetailVC.delegate = self.delegate;
  1466. [self.navigationController pushViewController:repliesDetailVC animated:YES];
  1467. repliesDetailVC.parentPageDataProvider = self.messageDataProvider;
  1468. __weak typeof(self) weakSelf = self;
  1469. repliesDetailVC.willCloseCallback = ^() {
  1470. [weakSelf.tableView reloadData];
  1471. weakSelf.hasCoverPage = NO;
  1472. };
  1473. }
  1474. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  1475. if (action == @selector(onDelete:) || action == @selector(onRevoke:) || action == @selector(onReSend:) || action == @selector(onCopyMsg:) ||
  1476. action == @selector(onMulitSelect:) || action == @selector(onForward:) || action == @selector(onReply:)) {
  1477. return YES;
  1478. }
  1479. return NO;
  1480. }
  1481. - (BOOL)canBecomeFirstResponder {
  1482. return YES;
  1483. }
  1484. - (void)buildMenuWithBuilder:(id<UIMenuBuilder>)builder API_AVAILABLE(ios(13.0)) {
  1485. if (@available(iOS 16.0, *)) {
  1486. [builder removeMenuForIdentifier:UIMenuLookup];
  1487. }
  1488. [super buildMenuWithBuilder:builder];
  1489. }
  1490. - (void)onDelete:(id)sender {
  1491. @weakify(self);
  1492. UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil
  1493. message:TIMCommonLocalizableString(ConfirmDeleteMessage)
  1494. preferredStyle:UIAlertControllerStyleActionSheet];
  1495. [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Delete)
  1496. style:UIAlertActionStyleDestructive
  1497. handler:^(UIAlertAction *_Nonnull action) {
  1498. @strongify(self);
  1499. [self.messageDataProvider deleteUIMsgs:@[ self.menuUIMsg ]
  1500. SuccBlock:nil
  1501. FailBlock:^(int code, NSString *desc) {
  1502. NSLog(@"remove msg failed!");
  1503. NSAssert(NO, desc);
  1504. }];
  1505. }]];
  1506. [vc tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Cancel) style:UIAlertActionStyleCancel handler:nil]];
  1507. [self presentViewController:vc animated:YES completion:nil];
  1508. }
  1509. - (void)menuDidHide:(NSNotification *)notification {
  1510. if (_delegate && [_delegate respondsToSelector:@selector(didHideMenuInMessageController:)]) {
  1511. [_delegate didHideMenuInMessageController:self];
  1512. }
  1513. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidHideMenuNotification object:nil];
  1514. }
  1515. - (void)onCopyMsg:(id)sender {
  1516. NSString *content = @"";
  1517. /**
  1518. *
  1519. * The text message should be based on the content of the message actually selected by the cursor
  1520. */
  1521. if ([sender isKindOfClass:[TUITextMessageCell class]]) {
  1522. TUITextMessageCell *txtCell = (TUITextMessageCell *)sender;
  1523. content = txtCell.selectContent;
  1524. }
  1525. if ([sender isKindOfClass:TUIReplyMessageCell.class] || [sender isKindOfClass:TUIReferenceMessageCell.class]) {
  1526. TUIReplyMessageCellData *replyMsg = (TUIReplyMessageCellData *)sender;
  1527. content = replyMsg.selectContent;
  1528. }
  1529. if (content.length > 0) {
  1530. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1531. pasteboard.string = content;
  1532. [TUITool makeToast:TIMCommonLocalizableString(Copied)];
  1533. }
  1534. }
  1535. - (void)onRevoke:(id)sender {
  1536. @weakify(self);
  1537. [self.messageDataProvider revokeUIMsg:self.menuUIMsg
  1538. SuccBlock:^{
  1539. @strongify(self);
  1540. if (self.delegate && [self.delegate respondsToSelector:@selector(didHideMenuInMessageController:)]) {
  1541. [self.delegate didHideMenuInMessageController:self];
  1542. }
  1543. }
  1544. FailBlock:^(int code, NSString *desc) {
  1545. NSAssert(NO, desc);
  1546. }];
  1547. }
  1548. - (void)onReSend:(id)sender {
  1549. [self sendUIMessage:_menuUIMsg];
  1550. }
  1551. - (void)onMulitSelect:(id)sender {
  1552. [self enableMultiSelectedMode:YES];
  1553. if (self.menuUIMsg.innerMessage.hasRiskContent) {
  1554. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onSelectMessageMenu:withData:)]) {
  1555. [_delegate messageController:self onSelectMessageMenu:0 withData:nil];
  1556. }
  1557. return;
  1558. }
  1559. self.menuUIMsg.selected = YES;
  1560. [self.tableView beginUpdates];
  1561. NSInteger index = [self.messageDataProvider.uiMsgs indexOfObject:self.menuUIMsg];
  1562. [self.tableView reloadRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ] withRowAnimation:UITableViewRowAnimationNone];
  1563. [self.tableView endUpdates];
  1564. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onSelectMessageMenu:withData:)]) {
  1565. [_delegate messageController:self onSelectMessageMenu:0 withData:_menuUIMsg];
  1566. }
  1567. }
  1568. - (void)onForward:(id)sender {
  1569. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onSelectMessageMenu:withData:)]) {
  1570. [_delegate messageController:self onSelectMessageMenu:1 withData:_menuUIMsg];
  1571. }
  1572. }
  1573. - (void)onReply:(id)sender {
  1574. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onRelyMessage:)]) {
  1575. [_delegate messageController:self onRelyMessage:self.menuUIMsg];
  1576. }
  1577. }
  1578. - (void)onReference:(id)sender {
  1579. if (_delegate && [_delegate respondsToSelector:@selector(messageController:onReferenceMessage:)]) {
  1580. [_delegate messageController:self onReferenceMessage:self.menuUIMsg];
  1581. }
  1582. }
  1583. - (void)onGroupPin:(id)sender currentStatus:(BOOL)currentStatus {
  1584. NSString *groupId = self.conversationData.groupID;
  1585. BOOL isPinned = currentStatus;
  1586. BOOL pinOrUnpin = !isPinned;
  1587. [self.messageDataProvider pinGroupMessage:groupId message:self.menuUIMsg.innerMessage isPinned:pinOrUnpin succ:^{
  1588. } fail:^(int code, NSString *desc) {
  1589. if (code == 10070) {
  1590. [TUITool makeToast:TIMCommonLocalizableString(TUIKitGroupMessagePinOverLimit)];
  1591. }
  1592. else if (code == 10004) {
  1593. if (pinOrUnpin) {
  1594. [TUITool makeToast:TIMCommonLocalizableString(TUIKitGroupMessagePinRepeatedly)];
  1595. }
  1596. else {
  1597. [TUITool makeToast:TIMCommonLocalizableString(TUIKitGroupMessageUnPinRepeatedly)];
  1598. }
  1599. }
  1600. }];
  1601. }
  1602. - (BOOL)supportCheckBox:(TUIMessageCellData *)data {
  1603. if ([data isKindOfClass:TUISystemMessageCellData.class]) {
  1604. return NO;
  1605. }
  1606. return YES;
  1607. }
  1608. - (BOOL)supportRelay:(TUIMessageCellData *)data {
  1609. if ([data isKindOfClass:TUIVoiceMessageCellData.class]) {
  1610. return NO;
  1611. }
  1612. return YES;
  1613. }
  1614. - (void)enableMultiSelectedMode:(BOOL)enable {
  1615. self.showCheckBox = enable;
  1616. if (!enable) {
  1617. for (TUIMessageCellData *cellData in self.messageDataProvider.uiMsgs) {
  1618. cellData.selected = NO;
  1619. }
  1620. }
  1621. [self.tableView reloadData];
  1622. }
  1623. - (NSArray<TUIMessageCellData *> *)multiSelectedResult:(TUIMultiResultOption)option {
  1624. NSMutableArray *arrayM = [NSMutableArray array];
  1625. if (!self.showCheckBox) {
  1626. return [NSArray arrayWithArray:arrayM];
  1627. }
  1628. BOOL filterUnsupported = option & TUIMultiResultOptionFiterUnsupportRelay;
  1629. for (TUIMessageCellData *data in self.messageDataProvider.uiMsgs) {
  1630. if (data.selected) {
  1631. if (filterUnsupported && ![self supportRelay:data]) {
  1632. continue;
  1633. }
  1634. [arrayM addObject:data];
  1635. }
  1636. }
  1637. return [NSArray arrayWithArray:arrayM];
  1638. }
  1639. - (void)deleteMessages:(NSArray<TUIMessageCellData *> *)uiMsgs {
  1640. if (uiMsgs.count == 0 || uiMsgs.count > 30) {
  1641. NSLog(@"The size of messages must be between 0 and 30");
  1642. return;
  1643. }
  1644. [self.messageDataProvider deleteUIMsgs:uiMsgs
  1645. SuccBlock:nil
  1646. FailBlock:^(int code, NSString *desc) {
  1647. NSLog(@"deleteMessages failed!");
  1648. NSAssert(NO, desc);
  1649. }];
  1650. }
  1651. - (void)clickTextMessage:(TUITextMessageCell *)cell {
  1652. V2TIMMessage *message = cell.messageData.innerMessage;
  1653. if (0 == message.userID.length) {
  1654. return;
  1655. }
  1656. [TUIMessageDataProvider.callingDataProvider redialFromMessage:message];
  1657. }
  1658. - (void)clickSystemMessage:(TUISystemMessageCell *)cell {
  1659. TUISystemMessageCellData *data = (TUISystemMessageCellData *)cell.messageData;
  1660. if (data.supportReEdit) {
  1661. if (self.delegate && [self.delegate respondsToSelector:@selector(messageController:onReEditMessage:)]) {
  1662. [self.delegate messageController:self onReEditMessage:cell.messageData];
  1663. }
  1664. }
  1665. }
  1666. - (void)playVoiceMessage:(TUIVoiceMessageCell *)cell {
  1667. for (TUIMessageCellData *cellData in self.messageDataProvider.uiMsgs) {
  1668. if (![cellData isKindOfClass:[TUIVoiceMessageCellData class]]) {
  1669. continue;
  1670. }
  1671. TUIVoiceMessageCellData *voiceMsg = (TUIVoiceMessageCellData *)cellData;
  1672. if (voiceMsg == cell.voiceData) {
  1673. [voiceMsg playVoiceMessage];
  1674. self.currentVoiceMsg = voiceMsg;
  1675. cell.voiceReadPoint.hidden = YES;
  1676. NSMutableArray *unPlayVoiceMessageAfterSelectVoiceMessage = [self getCurrentUnPlayVoiceMessageAfterSelectVoiceMessage:voiceMsg];
  1677. @weakify(self);
  1678. voiceMsg.audioPlayerDidFinishPlayingBlock = ^{
  1679. @strongify(self);
  1680. if (unPlayVoiceMessageAfterSelectVoiceMessage.count > 0) {
  1681. TUIVoiceMessageCellData *nextVoiceCellData = [unPlayVoiceMessageAfterSelectVoiceMessage firstObject];
  1682. NSIndexPath *nextIndex = [self indexPathOfMessage:nextVoiceCellData.msgID];
  1683. [self scrollCellToBottomOfMessage:nextVoiceCellData.msgID];
  1684. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1685. TUIVoiceMessageCell *nextCell = [self.tableView cellForRowAtIndexPath:nextIndex];
  1686. if (nextCell) {
  1687. [self playVoiceMessage:nextCell];
  1688. [unPlayVoiceMessageAfterSelectVoiceMessage removeObject:nextVoiceCellData];
  1689. } else {
  1690. // rerty: avoid nextCell is nil
  1691. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1692. TUIVoiceMessageCell *retryNextCell = [self.tableView cellForRowAtIndexPath:nextIndex];
  1693. if (retryNextCell) {
  1694. [self playVoiceMessage:retryNextCell];
  1695. [unPlayVoiceMessageAfterSelectVoiceMessage removeObject:nextVoiceCellData];
  1696. }
  1697. });
  1698. }
  1699. });
  1700. }
  1701. };
  1702. } else {
  1703. [voiceMsg stopVoiceMessage];
  1704. }
  1705. }
  1706. }
  1707. - (NSMutableArray *)getCurrentUnPlayVoiceMessageAfterSelectVoiceMessage:(TUIVoiceMessageCellData *)playingCellData {
  1708. NSMutableArray *neverHitsPlayVoiceQueue = [NSMutableArray array];
  1709. for (TUIMessageCellData *cellData in self.messageDataProvider.uiMsgs) {
  1710. if ([cellData isKindOfClass:[TUIVoiceMessageCellData class]]) {
  1711. TUIVoiceMessageCellData *voiceMsg = (TUIVoiceMessageCellData *)cellData;
  1712. if ((voiceMsg.innerMessage.localCustomInt == 0 && voiceMsg.direction == MsgDirectionIncoming &&
  1713. [voiceMsg.innerMessage.timestamp timeIntervalSince1970] >= [playingCellData.innerMessage.timestamp timeIntervalSince1970])) {
  1714. if (voiceMsg != playingCellData) {
  1715. [neverHitsPlayVoiceQueue addObject:voiceMsg];
  1716. }
  1717. }
  1718. }
  1719. }
  1720. return neverHitsPlayVoiceQueue;
  1721. }
  1722. - (void)showImageMessage:(TUIImageMessageCell *)cell {
  1723. [self hideKeyboardIfNeeded];
  1724. CGRect frame = [cell.thumb convertRect:cell.thumb.bounds toView:[UIApplication sharedApplication].delegate.window];
  1725. TUIMediaView *mediaView = [[TUIMediaView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
  1726. [mediaView setThumb:cell.thumb frame:frame];
  1727. [mediaView setCurMessage:cell.messageData.innerMessage];
  1728. __weak typeof(self) weakSelf = self;
  1729. mediaView.onClose = ^{
  1730. [weakSelf didCloseMediaMessage:cell];
  1731. };
  1732. [self willShowMediaMessage:cell];
  1733. [[UIApplication sharedApplication].keyWindow addSubview:mediaView];
  1734. }
  1735. - (void)showVideoMessage:(TUIVideoMessageCell *)cell {
  1736. if (![cell.videoData isVideoExist]) {
  1737. [cell.videoData downloadVideo];
  1738. } else {
  1739. [self hideKeyboardIfNeeded];
  1740. CGRect frame = [cell.thumb convertRect:cell.thumb.bounds toView:[UIApplication sharedApplication].delegate.window];
  1741. TUIMediaView *mediaView = [[TUIMediaView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
  1742. [mediaView setThumb:cell.thumb frame:frame];
  1743. [mediaView setCurMessage:cell.messageData.innerMessage];
  1744. __weak typeof(self) weakSelf = self;
  1745. mediaView.onClose = ^{
  1746. [weakSelf didCloseMediaMessage:cell];
  1747. };
  1748. [self willShowMediaMessage:cell];
  1749. [[UIApplication sharedApplication].keyWindow addSubview:mediaView];
  1750. }
  1751. }
  1752. - (void)showFileMessage:(TUIFileMessageCell *)cell {
  1753. [self hideKeyboardIfNeeded];
  1754. TUIFileMessageCellData *fileData = cell.fileData;
  1755. if (![fileData isLocalExist]) {
  1756. [fileData downloadFile];
  1757. return;
  1758. }
  1759. TUIFileViewController *file = [[TUIFileViewController alloc] init];
  1760. file.data = [cell fileData];
  1761. [self.navigationController pushViewController:file animated:YES];
  1762. }
  1763. - (void)showRelayMessage:(TUIMergeMessageCell *)cell {
  1764. TUIMergeMessageListController *mergeVc = [[TUIMergeMessageListController alloc] init];
  1765. mergeVc.delegate = self.delegate;
  1766. mergeVc.mergerElem = cell.mergeData.mergerElem;
  1767. mergeVc.conversationData = self.conversationData;
  1768. mergeVc.parentPageDataProvider = self.messageDataProvider;
  1769. __weak typeof(self) weakSelf = self;
  1770. mergeVc.willCloseCallback = ^() {
  1771. [weakSelf.tableView reloadData];
  1772. };
  1773. [self.navigationController pushViewController:mergeVc animated:YES];
  1774. }
  1775. - (void)showLinkMessage:(TUILinkCell *)cell {
  1776. TUILinkCellData *cellData = cell.customData;
  1777. if (cellData.link) {
  1778. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:cellData.link]];
  1779. }
  1780. }
  1781. - (void)showOrderMessage:(TUIOrderCell *)cell {
  1782. TUIOrderCellData *cellData = cell.customData;
  1783. if (cellData.link) {
  1784. [TUITool openLinkWithURL:[NSURL URLWithString:cellData.link]];
  1785. }
  1786. }
  1787. - (void)showReplyMessage:(TUIReplyMessageCell *)cell {
  1788. }
  1789. - (void)willShowMediaMessage:(TUIMessageCell *)cell {
  1790. }
  1791. - (void)didCloseMediaMessage:(TUIMessageCell *)cell {
  1792. }
  1793. - (BOOL)isCurrentUserRoleSuperAdminInGroup {
  1794. return [self.messageDataProvider isCurrentUserRoleSuperAdminInGroup];
  1795. }
  1796. - (BOOL)isCurrentMessagePin:(NSString *)msgID {
  1797. return [self.messageDataProvider isCurrentMessagePin:msgID];
  1798. }
  1799. - (void)unPinGroupMessage:(V2TIMMessage *)innerMessage {
  1800. NSString *groupId = self.conversationData.groupID;
  1801. BOOL isPinned = [self.messageDataProvider isCurrentMessagePin:innerMessage.msgID];
  1802. BOOL pinOrUnpin = !isPinned;
  1803. [self.messageDataProvider pinGroupMessage:groupId message:innerMessage isPinned:pinOrUnpin succ:^{
  1804. } fail:^(int code, NSString *desc) {
  1805. }];
  1806. }
  1807. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
  1808. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  1809. if (@available(iOS 16.0, *)) {
  1810. // send reloadview
  1811. [[NSNotificationCenter defaultCenter] postNotificationName:TUIMessageMediaViewDeviceOrientationChangeNotification object:nil];
  1812. } else {
  1813. // Fallback on earlier versions
  1814. }
  1815. }
  1816. @end