EMChatViewController.m 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. //
  2. // EMChatViewController.m
  3. // ChatDemo-UI3.0
  4. //
  5. // Created by XieYajie on 2019/1/18.
  6. // Copyright © 2019 XieYajie. All rights reserved.
  7. //
  8. #import <AVKit/AVKit.h>
  9. #import <Photos/Photos.h>
  10. #import <AVFoundation/AVFoundation.h>
  11. #import <AssetsLibrary/AssetsLibrary.h>
  12. #import <MobileCoreServices/MobileCoreServices.h>
  13. #import "EMChatViewController.h"
  14. #import "EMImageBrowser.h"
  15. #import "EMDateHelper.h"
  16. #import "EMAudioPlayerHelper.h"
  17. #import "EMConversationHelper.h"
  18. #import "EMMessageModel.h"
  19. #import "EMReadReceiptMemberModel.h"
  20. #import "EMChatBar.h"
  21. #import "EMMessageCell.h"
  22. #import "EMMessageTimeCell.h"
  23. #import "EMLocationViewController.h"
  24. #import "EMMsgTranspondViewController.h"
  25. #import "EMAtGroupMembersViewController.h"
  26. @interface EMChatViewController ()<UIScrollViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, EMMultiDevicesDelegate, EMChatManagerDelegate, EMGroupManagerDelegate, EMChatroomManagerDelegate, EMChatBarDelegate, EMMessageCellDelegate, EMChatBarEmoticonViewDelegate, EMChatBarRecordAudioViewDelegate,EMMoreFunctionViewDelegate,EMReadReceiptMsgDelegate>
  27. @property (nonatomic, strong) dispatch_queue_t msgQueue;
  28. @property (nonatomic) BOOL isFirstLoadMsg;
  29. @property (nonatomic) BOOL isViewDidAppear;
  30. @property (nonatomic, strong) EMConversationModel *conversationModel;
  31. @property (nonatomic, strong) NSString *moreMsgId; //第一条消息的消息id
  32. @property (nonatomic, strong) UILabel *titleLabel;
  33. @property (nonatomic, strong) UILabel *titleDetailLabel;
  34. @property (nonatomic, strong) EMChatBar *chatBar;
  35. @property (nonatomic, strong) UIImagePickerController *imagePicker;
  36. @property (nonatomic, strong) EMGroup *group;
  37. //阅读回执
  38. @property (nonatomic, strong) EMReadReceiptMsgViewController *readReceiptControl;
  39. //长按操作栏
  40. @property (strong, nonatomic) NSIndexPath *menuIndexPath;
  41. @property (nonatomic, strong) UIMenuController *menuController;
  42. @property (nonatomic, strong) UIMenuItem *deleteMenuItem;
  43. @property (nonatomic, strong) UIMenuItem *copyMenuItem;
  44. @property (nonatomic, strong) UIMenuItem *recallMenuItem;
  45. @property (nonatomic, strong) UIMenuItem *transpondMenuItem;
  46. //消息格式化
  47. @property (nonatomic) NSTimeInterval msgTimelTag;
  48. //@
  49. @property (nonatomic) BOOL isWillInputAt;
  50. //Typing
  51. @property (nonatomic) BOOL isTyping;
  52. @property (nonatomic) BOOL enableTyping;
  53. @end
  54. @implementation EMChatViewController
  55. - (instancetype)initWithConversationId:(NSString *)aId
  56. type:(EMConversationType)aType
  57. createIfNotExist:(BOOL)aIsCreate
  58. {
  59. self = [super init];
  60. if (self) {
  61. EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:aId type:aType createIfNotExist:aIsCreate];
  62. _conversationModel = [[EMConversationModel alloc] initWithEMModel:conversation];
  63. }
  64. return self;
  65. }
  66. - (instancetype)initWithCoversationModel:(EMConversationModel *)aConversationModel
  67. {
  68. self = [super init];
  69. if (self) {
  70. _conversationModel = aConversationModel;
  71. }
  72. return self;
  73. }
  74. - (void)viewDidLoad {
  75. [super viewDidLoad];
  76. // Do any additional setup after loading the view.
  77. self.msgQueue = dispatch_queue_create("emmessage.com", NULL);
  78. self.msgTimelTag = -1;
  79. [self _setupChatSubviews];
  80. [[EMClient sharedClient] addMultiDevicesDelegate:self delegateQueue:nil];
  81. [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
  82. [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
  83. [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
  84. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWillPushCallController:) name:CALL_PUSH_VIEWCONTROLLER object:nil];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCleanMessages:) name:CHAT_CLEANMESSAGES object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleGroupSubjectUpdated:) name:GROUP_SUBJECT_UPDATED object:nil];
  87. self.isTyping = NO;
  88. self.enableTyping = NO;
  89. if ([EMDemoOptions sharedOptions].isChatTyping && self.conversationModel.emModel.type == EMConversationTypeChat) {
  90. self.enableTyping = YES;
  91. }
  92. if (self.conversationModel.emModel.type == EMConversationTypeChatRoom) {
  93. [self _joinChatroom];
  94. } else {
  95. self.isFirstLoadMsg = YES;
  96. [self tableViewDidTriggerHeaderRefresh];
  97. }
  98. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapTableViewAction:)];
  99. [self.tableView addGestureRecognizer:tap];
  100. }
  101. - (void)viewWillAppear:(BOOL)animated
  102. {
  103. [super viewWillAppear:animated];
  104. self.isViewDidAppear = YES;
  105. [EMConversationHelper markAllAsRead:self.conversationModel];
  106. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  107. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  108. }
  109. - (void)viewWillDisappear:(BOOL)animated
  110. {
  111. [super viewWillDisappear:animated];
  112. self.isViewDidAppear = NO;
  113. if (self.enableTyping && self.isTyping) {
  114. [self _sendEndTyping];
  115. }
  116. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  117. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
  118. }
  119. - (void)dealloc
  120. {
  121. self.isViewDidAppear = NO;
  122. [[EMClient sharedClient] removeMultiDevicesDelegate:self];
  123. [[EMClient sharedClient].chatManager removeDelegate:self];
  124. [[EMClient sharedClient].groupManager removeDelegate:self];
  125. [[EMClient sharedClient].roomManager removeDelegate:self];
  126. [[NSNotificationCenter defaultCenter] removeObserver:self];
  127. }
  128. - (BOOL)canBecomeFirstResponder
  129. {
  130. return YES;
  131. }
  132. #pragma mark - Subviews
  133. - (void)_setupChatSubviews
  134. {
  135. [self addPopBackLeftItemWithTarget:self action:@selector(backAction)];
  136. [self _setupNavigationBarTitle];
  137. [self _setupNavigationBarRightItem];
  138. self.view.backgroundColor = [UIColor whiteColor];
  139. self.showRefreshHeader = YES;
  140. self.chatBar = [[EMChatBar alloc] init];
  141. self.chatBar.delegate = self;
  142. [self.view addSubview:self.chatBar];
  143. [self.chatBar mas_makeConstraints:^(MASConstraintMaker *make) {
  144. make.left.equalTo(self.view);
  145. make.right.equalTo(self.view);
  146. make.bottom.equalTo(self.view);
  147. }];
  148. [self _setupChatBarMoreViews];
  149. self.tableView.backgroundColor = kColor_LightGray;
  150. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  151. self.tableView.rowHeight = UITableViewAutomaticDimension;
  152. self.tableView.estimatedRowHeight = 130;
  153. [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
  154. make.top.equalTo(self.view);
  155. make.left.equalTo(self.view);
  156. make.right.equalTo(self.view);
  157. make.bottom.equalTo(self.chatBar.mas_top);
  158. }];
  159. }
  160. - (void)_setupNavigationBarTitle
  161. {
  162. UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width * 06, 40)];
  163. self.titleLabel = [[UILabel alloc] init];
  164. self.titleLabel.font = [UIFont systemFontOfSize:18];
  165. self.titleLabel.textColor = [UIColor blackColor];
  166. self.titleLabel.textAlignment = NSTextAlignmentCenter;
  167. self.titleLabel.text = self.conversationModel.name;
  168. [titleView addSubview:self.titleLabel];
  169. [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  170. make.top.equalTo(titleView);
  171. make.left.equalTo(titleView).offset(5);
  172. make.right.equalTo(titleView).offset(-5);
  173. }];
  174. self.titleDetailLabel = [[UILabel alloc] init];
  175. self.titleDetailLabel.font = [UIFont systemFontOfSize:15];
  176. self.titleDetailLabel.textColor = [UIColor grayColor];
  177. self.titleDetailLabel.textAlignment = NSTextAlignmentCenter;
  178. [titleView addSubview:self.titleDetailLabel];
  179. [self.titleDetailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  180. make.top.equalTo(self.titleLabel.mas_bottom);
  181. make.left.equalTo(self.titleLabel);
  182. make.right.equalTo(self.titleLabel);
  183. make.bottom.equalTo(titleView);
  184. }];
  185. self.navigationItem.titleView = titleView;
  186. if (self.conversationModel.emModel.type != EMConversationTypeChat) {
  187. self.titleDetailLabel.text = self.conversationModel.emModel.conversationId;
  188. }
  189. }
  190. - (void)_setupNavigationBarRightItem
  191. {
  192. if (self.conversationModel.emModel.type == EMConversationTypeChat) {
  193. UIImage *image = [[UIImage imageNamed:@"chat_clear"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  194. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(deleteAllMessageAction)];
  195. } else {
  196. if (self.conversationModel.emModel.type == EMConversationTypeGroupChat && (NSClassFromString(@"EMGroupInfoViewController")) == nil) {
  197. return;
  198. }
  199. if (self.conversationModel.emModel.type == EMConversationTypeChatRoom && (NSClassFromString(@"EMChatroomInfoViewController")) == nil) {
  200. return;
  201. }
  202. UIImage *image = [[UIImage imageNamed:@"chat_info"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  203. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(groupOrChatroomInfoAction)];
  204. }
  205. }
  206. - (void)_setupChatBarMoreViews
  207. {
  208. //语音
  209. NSString *path = [self _getAudioOrVideoPath];
  210. EMChatBarRecordAudioView *recordView = [[EMChatBarRecordAudioView alloc] initWithRecordPath:path];
  211. recordView.delegate = self;
  212. self.chatBar.recordAudioView = recordView;
  213. //表情
  214. EMChatBarEmoticonView *moreEmoticonView = [[EMChatBarEmoticonView alloc] init];
  215. moreEmoticonView.delegate = self;
  216. self.chatBar.moreEmoticonView = moreEmoticonView;
  217. //更多
  218. if (self.conversationModel.emModel.type == EMConversationTypeGroupChat) {
  219. EMMoreFunctionView *moreFunction = [[EMMoreFunctionView alloc]init];
  220. moreFunction.delegate = self;
  221. self.chatBar.moreFunctionView = moreFunction;
  222. }
  223. }
  224. - (NSString *)_getAudioOrVideoPath
  225. {
  226. NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  227. path = [path stringByAppendingPathComponent:@"EMDemoRecord"];
  228. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  229. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  230. }
  231. return path;
  232. }
  233. #pragma mark - Getter
  234. - (UIImagePickerController *)imagePicker
  235. {
  236. if (_imagePicker == nil) {
  237. _imagePicker = [[UIImagePickerController alloc] init];
  238. _imagePicker.modalPresentationStyle = UIModalPresentationOverFullScreen;
  239. _imagePicker.delegate = self;
  240. }
  241. return _imagePicker;
  242. }
  243. #pragma mark - Table view data source
  244. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  245. return 1;
  246. }
  247. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  248. return [self.dataArray count];
  249. }
  250. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  251. id obj = [self.dataArray objectAtIndex:indexPath.row];
  252. NSString *cellString = nil;
  253. if ([obj isKindOfClass:[NSString class]]) {
  254. cellString = (NSString *)obj;
  255. } else if ([obj isKindOfClass:[EMMessageModel class]]) {
  256. EMMessageModel *model = (EMMessageModel *)obj;
  257. if (model.type == EMMessageTypeExtRecall) {
  258. cellString = @"您撤回一条消息";
  259. }
  260. }
  261. if ([cellString length] > 0) {
  262. EMMessageTimeCell *cell = (EMMessageTimeCell *)[tableView dequeueReusableCellWithIdentifier:@"EMMessageTimeCell"];
  263. // Configure the cell...
  264. if (cell == nil) {
  265. cell = [[EMMessageTimeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"EMMessageTimeCell"];
  266. }
  267. cell.timeLabel.text = cellString;
  268. return cell;
  269. } else {
  270. EMMessageModel *model = (EMMessageModel *)obj;
  271. NSString *identifier = [EMMessageCell cellIdentifierWithDirection:model.direction type:model.type];
  272. EMMessageCell *cell = (EMMessageCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
  273. // Configure the cell...
  274. if (cell == nil) {
  275. cell = [[EMMessageCell alloc] initWithDirection:model.direction type:model.type];
  276. cell.delegate = self;
  277. }
  278. cell.model = model;
  279. return cell;
  280. }
  281. }
  282. #pragma mark - UIScrollViewDelegate
  283. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  284. {
  285. [self.view endEditing:YES];
  286. [self.chatBar clearMoreViewAndSelectedButton];
  287. }
  288. #pragma mark - UIImagePickerControllerDelegate
  289. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  290. {
  291. NSString *mediaType = info[UIImagePickerControllerMediaType];
  292. if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
  293. NSURL *videoURL = info[UIImagePickerControllerMediaURL];
  294. // we will convert it to mp4 format
  295. NSURL *mp4 = [self _videoConvert2Mp4:videoURL];
  296. NSFileManager *fileman = [NSFileManager defaultManager];
  297. if ([fileman fileExistsAtPath:videoURL.path]) {
  298. NSError *error = nil;
  299. [fileman removeItemAtURL:videoURL error:&error];
  300. if (error) {
  301. NSLog(@"failed to remove file, error:%@.", error);
  302. }
  303. }
  304. [self _sendVideoAction:mp4];
  305. } else {
  306. NSURL *url = info[UIImagePickerControllerReferenceURL];
  307. if (url == nil) {
  308. UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
  309. NSData *data = UIImageJPEGRepresentation(orgImage, 1);
  310. [self _sendImageDataAction:data];
  311. } else {
  312. if ([[UIDevice currentDevice].systemVersion doubleValue] >= 9.0f) {
  313. PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
  314. [result enumerateObjectsUsingBlock:^(PHAsset *asset , NSUInteger idx, BOOL *stop){
  315. if (asset) {
  316. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData *data, NSString *uti, UIImageOrientation orientation, NSDictionary *dic){
  317. if (data != nil) {
  318. [self _sendImageDataAction:data];
  319. } else {
  320. [EMAlertController showErrorAlert:@"图片太大,请选择其他图片"];
  321. }
  322. }];
  323. }
  324. }];
  325. } else {
  326. ALAssetsLibrary *alasset = [[ALAssetsLibrary alloc] init];
  327. [alasset assetForURL:url resultBlock:^(ALAsset *asset) {
  328. if (asset) {
  329. ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
  330. Byte *buffer = (Byte*)malloc((size_t)[assetRepresentation size]);
  331. NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:0.0 length:(NSUInteger)[assetRepresentation size] error:nil];
  332. NSData *fileData = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
  333. [self _sendImageDataAction:fileData];
  334. }
  335. } failureBlock:NULL];
  336. }
  337. }
  338. }
  339. [picker dismissViewControllerAnimated:YES completion:nil];
  340. //TODO: 当弹出call页面时,与imagePicker冲突
  341. // self.isViewDidAppear = YES;
  342. // [[EaseSDKHelper shareHelper] setIsShowingimagePicker:NO];
  343. }
  344. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
  345. {
  346. [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
  347. // self.isViewDidAppear = YES;
  348. // [[EaseSDKHelper shareHelper] setIsShowingimagePicker:NO];
  349. }
  350. #pragma mark - EMChatBarDelegate
  351. - (void)_willInputAt:(EMTextView *)aInputView
  352. {
  353. do {
  354. if (self.conversationModel.emModel.type != EMConversationTypeGroupChat) {
  355. break;
  356. }
  357. NSString *text = aInputView.text;
  358. // if (![text hasSuffix:@"@"]) {
  359. // break;
  360. // }
  361. EMGroup *group = [EMGroup groupWithId:self.conversationModel.emModel.conversationId];
  362. if (!group) {
  363. break;
  364. }
  365. [self.view endEditing:YES];
  366. EMAtGroupMembersViewController *controller = [[EMAtGroupMembersViewController alloc] initWithGroup:group];
  367. [self.navigationController pushViewController:controller animated:YES];
  368. [controller setSelectedCompletion:^(NSString * _Nonnull aName) {
  369. NSString *newStr = [NSString stringWithFormat:@"%@%@ ", text, aName];
  370. aInputView.text = newStr;
  371. aInputView.selectedRange = NSMakeRange(newStr.length, 0);
  372. [aInputView becomeFirstResponder];
  373. }];
  374. } while (0);
  375. }
  376. - (BOOL)inputView:(EMTextView *)aInputView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  377. {
  378. self.isWillInputAt = NO;
  379. if ([text isEqualToString:@"\n"]) {
  380. [self _sendTextAction:aInputView.text ext:nil];
  381. return NO;
  382. } else if ([text isEqualToString:@"@"]) {
  383. self.isWillInputAt = YES;
  384. } else if ([text length] == 0) {
  385. }
  386. return YES;
  387. }
  388. - (void)inputViewDidChange:(EMTextView *)aInputView
  389. {
  390. if (self.isWillInputAt && self.conversationModel.emModel.type == EMConversationTypeGroupChat) {
  391. NSString *text = aInputView.text;
  392. if ([text hasSuffix:@"@"]) {
  393. self.isWillInputAt = NO;
  394. [self _willInputAt:aInputView];
  395. }
  396. }
  397. if (self.enableTyping) {
  398. if (!self.isTyping) {
  399. self.isTyping = YES;
  400. [self _sendBeginTyping];
  401. }
  402. }
  403. }
  404. - (void)chatBarDidCameraAction
  405. {
  406. [self.view endEditing:YES];
  407. #if TARGET_IPHONE_SIMULATOR
  408. [EMAlertController showErrorAlert:@"模拟器不支持照相机"];
  409. #elif TARGET_OS_IPHONE
  410. self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  411. self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie];
  412. [self presentViewController:self.imagePicker animated:YES completion:nil];
  413. #endif
  414. }
  415. - (void)chatBarDidPhotoAction
  416. {
  417. [self.view endEditing:YES];
  418. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  419. dispatch_async(dispatch_get_main_queue(), ^{
  420. switch (status) {
  421. case PHAuthorizationStatusAuthorized: //已获取权限
  422. {
  423. self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  424. self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
  425. [self presentViewController:self.imagePicker animated:YES completion:nil];
  426. }
  427. break;
  428. case PHAuthorizationStatusDenied: //用户已经明确否认了这一照片数据的应用程序访问
  429. [EMAlertController showErrorAlert:@"不允许访问相册"];
  430. break;
  431. case PHAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限
  432. [EMAlertController showErrorAlert:@"没有授权访问相册"];
  433. break;
  434. default:
  435. [EMAlertController showErrorAlert:@"访问相册失败"];
  436. break;
  437. }
  438. });
  439. }];
  440. }
  441. - (void)chatBarDidLocationAction
  442. {
  443. EMLocationViewController *controller = [[EMLocationViewController alloc] init];
  444. [controller setSendCompletion:^(CLLocationCoordinate2D aCoordinate, NSString * _Nonnull aAddress) {
  445. [self _sendLocationAction:aCoordinate address:aAddress];
  446. }];
  447. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
  448. [self.navigationController presentViewController:navController animated:YES completion:nil];
  449. }
  450. - (void)chatBarDidCallAction
  451. {
  452. self.alertController = [UIAlertController alertControllerWithTitle:@"实时通话类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  453. __weak typeof(self) weakself = self;
  454. if (self.conversationModel.emModel.type == EMConversationTypeChat) {
  455. [self.alertController addAction:[UIAlertAction actionWithTitle:@"语音通话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  456. [weakself.chatBar clearMoreViewAndSelectedButton];
  457. [[NSNotificationCenter defaultCenter] postNotificationName:CALL_MAKE1V1 object:@{CALL_CHATTER:weakself.conversationModel.emModel.conversationId, CALL_TYPE:@(EMCallTypeVoice)}];
  458. }]];
  459. [self.alertController addAction:[UIAlertAction actionWithTitle:@"视频通话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  460. [weakself.chatBar clearMoreViewAndSelectedButton];
  461. [[NSNotificationCenter defaultCenter] postNotificationName:CALL_MAKE1V1 object:@{CALL_CHATTER:weakself.conversationModel.emModel.conversationId, CALL_TYPE:@(EMCallTypeVideo)}];
  462. }]];
  463. } else {
  464. [self.alertController addAction:[UIAlertAction actionWithTitle:@"会议模式" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  465. [weakself.chatBar clearMoreViewAndSelectedButton];
  466. [[NSNotificationCenter defaultCenter] postNotificationName:CALL_MAKECONFERENCE object:@{CALL_TYPE:@(EMConferenceTypeLargeCommunication), CALL_MODEL:weakself.conversationModel, NOTIF_NAVICONTROLLER:self.navigationController}];
  467. }]];
  468. [self.alertController addAction:[UIAlertAction actionWithTitle:@"互动模式" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  469. [weakself.chatBar clearMoreViewAndSelectedButton];
  470. [[NSNotificationCenter defaultCenter] postNotificationName:CALL_MAKECONFERENCE object:@{CALL_TYPE:@(EMConferenceTypeLive), CALL_MODEL:weakself.conversationModel, NOTIF_NAVICONTROLLER:self.navigationController}];
  471. }]];
  472. }
  473. [self.alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  474. }]];
  475. [[NSNotificationCenter defaultCenter] postNotificationName:@"didAlert" object:@{@"alert":self.alertController}];
  476. [self presentViewController:self.alertController animated:YES completion:nil];
  477. }
  478. //阅读回执跳转
  479. - (void)chatBarMoreFunctionReadReceipt
  480. {
  481. self.readReceiptControl = [[EMReadReceiptMsgViewController alloc]init];
  482. self.readReceiptControl.delegate = self;
  483. self.readReceiptControl.modalPresentationStyle = 0;
  484. //[self.navigationController pushViewController:readReceipt animated:NO];
  485. [self presentViewController:self.readReceiptControl animated:NO completion:nil];
  486. }
  487. //阅读回执发送信息
  488. - (void)sendReadReceiptMsg:(NSString *)msg
  489. {
  490. NSString *str = msg;
  491. NSLog(@"\n%@",str);
  492. if (self.conversationModel.emModel.type == EMConversationTypeGroupChat) {
  493. [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:self.conversationModel.emModel.conversationId completion:^(EMGroup *aGroup, EMError *aError) {
  494. NSLog(@"\n -------- sendError: %@",aError);
  495. if (!aError) {
  496. self.group = aGroup;
  497. //是群主才可以发送阅读回执信息
  498. [self _sendTextAction:str ext:@{MSG_EXT_READ_RECEIPT:@"receipt"}];
  499. } else {
  500. [EMAlertController showErrorAlert:@"获取群组失败"];
  501. }
  502. }];
  503. }else {
  504. [self _sendTextAction:str ext:nil];
  505. }
  506. }
  507. - (void)chatBarDidShowMoreViewAction
  508. {
  509. [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
  510. make.bottom.equalTo(self.chatBar.mas_top);
  511. }];
  512. [self performSelector:@selector(_scrollToBottomRow) withObject:nil afterDelay:0.1];
  513. }
  514. #pragma mark - EMChatBarRecordAudioViewDelegate
  515. - (void)chatBarRecordAudioViewStartRecord
  516. {
  517. }
  518. - (void)chatBarRecordAudioViewStopRecord:(NSString *)aPath
  519. timeLength:(NSInteger)aTimeLength
  520. {
  521. EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:aPath displayName:@"audio"];
  522. body.duration = (int)aTimeLength;
  523. if(body.duration < 1){
  524. [self showHint:@"按键时间太短."];
  525. return;
  526. }
  527. [self _sendMessageWithBody:body ext:nil isUpload:YES];
  528. }
  529. - (void)chatBarRecordAudioViewCancelRecord
  530. {
  531. }
  532. #pragma mark - EMChatBarEmoticonViewDelegate
  533. - (void)didSelectedEmoticonModel:(EMEmoticonModel *)aModel
  534. {
  535. if (aModel.type == EMEmotionTypeEmoji) {
  536. [self.chatBar inputViewAppendText:aModel.name];
  537. } if (aModel.type == EMEmotionTypeGif) {
  538. NSDictionary *ext = @{MSG_EXT_GIF:@(YES), MSG_EXT_GIF_ID:aModel.eId};
  539. [self _sendTextAction:aModel.name ext:ext];
  540. }
  541. }
  542. - (void)didChatBarEmoticonViewSendAction
  543. {
  544. [self _sendTextAction:self.chatBar.textView.text ext:nil];
  545. }
  546. #pragma mark - EMMessageCellDelegate
  547. //阅读回执详情
  548. - (void)messageReadReceiptDetil:(EMMessageCell *)aCell
  549. {
  550. self.readReceiptControl = [[EMReadReceiptMsgViewController alloc] initWithMessageCell:aCell groupId:self.conversationModel.emModel.conversationId];
  551. self.readReceiptControl.modalPresentationStyle = 0;
  552. //[self.navigationController pushViewController:readReceiptControl animated:NO];
  553. [self presentViewController:self.readReceiptControl animated:NO completion:nil];
  554. }
  555. - (void)messageCellDidSelected:(EMMessageCell *)aCell
  556. {
  557. if (aCell.model.type == EMMessageTypeImage) {
  558. [self _imageMessageCellDidSelected:aCell];
  559. } else if (aCell.model.type == EMMessageTypeLocation) {
  560. [self _locationMessageCellDidSelected:aCell];
  561. } else if (aCell.model.type == EMMessageTypeVoice) {
  562. [self _audioMessageCellDidSelected:aCell];
  563. } else if (aCell.model.type == EMMessageTypeVideo) {
  564. [self _videoMessageCellDidSelected:aCell];
  565. } else if (aCell.model.type == EMMessageTypeFile) {
  566. [self _fileMessageCellDidSelected:aCell];
  567. } else if (aCell.model.type == EMMessageTypeExtCall) {
  568. [self _callMessageCellDidSelected:aCell];
  569. } else if (aCell.model.type == EMMessageTypeText) {
  570. }
  571. }
  572. - (void)_imageMessageCellDidSelected:(EMMessageCell *)aCell
  573. {
  574. __weak typeof(self) weakself = self;
  575. void (^downloadThumbBlock)(EMMessageModel *aModel) = ^(EMMessageModel *aModel) {
  576. [weakself showHint:@"获取缩略图..."];
  577. [[EMClient sharedClient].chatManager downloadMessageThumbnail:aModel.emModel progress:nil completion:^(EMMessage *message, EMError *error) {
  578. if (!error) {
  579. [weakself.tableView reloadData];
  580. }
  581. }];
  582. };
  583. EMImageMessageBody *body = (EMImageMessageBody*)aCell.model.emModel.body;
  584. BOOL isCustomDownload = !([EMClient sharedClient].options.isAutoTransferMessageAttachments);
  585. if (body.thumbnailDownloadStatus == EMDownloadStatusFailed) {
  586. if (isCustomDownload) {
  587. [self _showCustomTransferFileAlertView];
  588. } else {
  589. downloadThumbBlock(aCell.model);
  590. }
  591. return;
  592. }
  593. BOOL isAutoDownloadThumbnail = [EMClient sharedClient].options.isAutoDownloadThumbnail;
  594. if (body.thumbnailDownloadStatus == EMDownloadStatusPending && !isAutoDownloadThumbnail) {
  595. downloadThumbBlock(aCell.model);
  596. return;
  597. }
  598. if (body.downloadStatus == EMDownloadStatusSucceed) {
  599. UIImage *image = [UIImage imageWithContentsOfFile:body.localPath];
  600. if (image) {
  601. [[EMImageBrowser sharedBrowser] showImages:@[image] fromController:self];
  602. return;
  603. }
  604. }
  605. if (isCustomDownload) {
  606. [self _showCustomTransferFileAlertView];
  607. return;
  608. }
  609. [self showHudInView:self.view hint:@"下载原图..."];
  610. [[EMClient sharedClient].chatManager downloadMessageAttachment:aCell.model.emModel progress:nil completion:^(EMMessage *message, EMError *error) {
  611. [weakself hideHud];
  612. if (error) {
  613. [EMAlertController showErrorAlert:@"下载原图失败"];
  614. } else {
  615. if (message.direction == EMMessageDirectionReceive && !message.isReadAcked) {
  616. [[EMClient sharedClient].chatManager sendMessageReadAck:message.messageId toUser:message.conversationId completion:nil];
  617. }
  618. NSString *localPath = [(EMImageMessageBody *)message.body localPath];
  619. UIImage *image = [UIImage imageWithContentsOfFile:localPath];
  620. if (image) {
  621. [[EMImageBrowser sharedBrowser] showImages:@[image] fromController:self];
  622. } else {
  623. [EMAlertController showErrorAlert:@"获取原图失败"];
  624. }
  625. }
  626. }];
  627. }
  628. - (void)_locationMessageCellDidSelected:(EMMessageCell *)aCell
  629. {
  630. EMLocationMessageBody *body = (EMLocationMessageBody *)aCell.model.emModel.body;
  631. EMLocationViewController *controller = [[EMLocationViewController alloc] initWithLocation:CLLocationCoordinate2DMake(body.latitude, body.longitude)];
  632. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
  633. [self.navigationController presentViewController:navController animated:YES completion:nil];
  634. }
  635. - (void)_audioMessageCellDidSelected:(EMMessageCell *)aCell
  636. {
  637. if (aCell.model.isPlaying) {
  638. [[EMAudioPlayerHelper sharedHelper] stopPlayer];
  639. aCell.model.isPlaying = NO;
  640. [self.tableView reloadData];
  641. return;
  642. }
  643. EMVoiceMessageBody *body = (EMVoiceMessageBody*)aCell.model.emModel.body;
  644. if (body.downloadStatus == EMDownloadStatusDownloading) {
  645. [EMAlertController showInfoAlert:@"正在下载语音,稍后点击"];
  646. return;
  647. }
  648. __weak typeof(self) weakself = self;
  649. void (^playBlock)(EMMessageModel *aModel) = ^(EMMessageModel *aModel) {
  650. id model = [EMAudioPlayerHelper sharedHelper].model;
  651. if (model && [model isKindOfClass:[EMMessageModel class]]) {
  652. EMMessageModel *oldModel = (EMMessageModel *)model;
  653. if (oldModel.isPlaying) {
  654. oldModel.isPlaying = NO;
  655. }
  656. }
  657. if (!aModel.emModel.isReadAcked) {
  658. [[EMClient sharedClient].chatManager sendMessageReadAck:aModel.emModel.messageId toUser:aModel.emModel.conversationId completion:nil];
  659. }
  660. aModel.isPlaying = YES;
  661. if (!aModel.emModel.isRead) {
  662. aModel.emModel.isRead = YES;
  663. }
  664. [weakself.tableView reloadData];
  665. [[EMAudioPlayerHelper sharedHelper] startPlayerWithPath:body.localPath model:aModel completion:^(NSError * _Nonnull error) {
  666. aModel.isPlaying = NO;
  667. [weakself.tableView reloadData];
  668. }];
  669. };
  670. if (body.downloadStatus == EMDownloadStatusSucceed) {
  671. playBlock(aCell.model);
  672. return;
  673. }
  674. if (![EMClient sharedClient].options.isAutoTransferMessageAttachments) {
  675. [self _showCustomTransferFileAlertView];
  676. return;
  677. }
  678. [self showHudInView:self.view hint:@"下载语音..."];
  679. [[EMClient sharedClient].chatManager downloadMessageAttachment:aCell.model.emModel progress:nil completion:^(EMMessage *message, EMError *error) {
  680. [weakself hideHud];
  681. if (error) {
  682. [EMAlertController showErrorAlert:@"下载语音失败"];
  683. } else {
  684. playBlock(aCell.model);
  685. }
  686. }];
  687. }
  688. - (void)_videoMessageCellDidSelected:(EMMessageCell *)aCell
  689. {
  690. EMVideoMessageBody *body = (EMVideoMessageBody*)aCell.model.emModel.body;
  691. NSFileManager *fileManager = [NSFileManager defaultManager];
  692. BOOL isCustomDownload = !([EMClient sharedClient].options.isAutoTransferMessageAttachments);
  693. if (body.thumbnailDownloadStatus == EMDownloadStatusFailed || ![fileManager fileExistsAtPath:body.thumbnailLocalPath]) {
  694. [self showHint:@"下载缩略图"];
  695. if (!isCustomDownload) {
  696. [[EMClient sharedClient].chatManager downloadMessageThumbnail:aCell.model.emModel progress:nil completion:nil];
  697. }
  698. }
  699. if (body.downloadStatus == EMDownloadStatusDownloading) {
  700. [EMAlertController showInfoAlert:@"正在下载视频,稍后点击"];
  701. return;
  702. }
  703. void (^playBlock)(NSString *aPath) = ^(NSString *aPathe) {
  704. NSURL *videoURL = [NSURL fileURLWithPath:aPathe];
  705. AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
  706. playerViewController.player = [AVPlayer playerWithURL:videoURL];
  707. playerViewController.videoGravity = AVLayerVideoGravityResizeAspect;
  708. playerViewController.showsPlaybackControls = YES;
  709. [self presentViewController:playerViewController animated:YES completion:^{
  710. [playerViewController.player play];
  711. }];
  712. };
  713. if (body.downloadStatus == EMDownloadStatusSuccessed && [fileManager fileExistsAtPath:body.localPath]) {
  714. playBlock(body.localPath);
  715. return;
  716. }
  717. if (isCustomDownload) {
  718. [self _showCustomTransferFileAlertView];
  719. } else {
  720. [self showHudInView:self.view hint:@"下载视频..."];
  721. __weak typeof(self) weakself = self;
  722. [[EMClient sharedClient].chatManager downloadMessageAttachment:aCell.model.emModel progress:nil completion:^(EMMessage *message, EMError *error) {
  723. [weakself hideHud];
  724. if (error) {
  725. [EMAlertController showErrorAlert:@"下载视频失败"];
  726. } else {
  727. if (!message.isReadAcked) {
  728. [[EMClient sharedClient].chatManager sendMessageReadAck:message.messageId toUser:message.conversationId completion:nil];
  729. }
  730. playBlock([(EMVideoMessageBody*)message.body localPath]);
  731. }
  732. }];
  733. }
  734. }
  735. - (void)_fileMessageCellDidSelected:(EMMessageCell *)aCell
  736. {
  737. }
  738. - (void)_callMessageCellDidSelected:(EMMessageCell *)aCell
  739. {
  740. [[NSNotificationCenter defaultCenter] postNotificationName:CALL_SELECTCONFERENCECELL object:aCell.model.emModel];
  741. }
  742. - (void)messageCellDidLongPress:(EMMessageCell *)aCell
  743. {
  744. self.menuIndexPath = [self.tableView indexPathForCell:aCell];
  745. [self _showMenuViewController:aCell model:aCell.model];
  746. }
  747. - (void)messageCellDidResend:(EMMessageModel *)aModel
  748. {
  749. if (aModel.emModel.status != EMMessageStatusFailed && aModel.emModel.status != EMMessageStatusPending) {
  750. return;
  751. }
  752. __weak typeof(self) weakself = self;
  753. [[[EMClient sharedClient] chatManager] resendMessage:aModel.emModel progress:nil completion:^(EMMessage *message, EMError *error) {
  754. [weakself.tableView reloadData];
  755. }];
  756. [self.tableView reloadData];
  757. }
  758. #pragma mark - EMMultiDevicesDelegate
  759. - (void)multiDevicesGroupEventDidReceive:(EMMultiDevicesEvent)aEvent
  760. groupId:(NSString *)aGroupId
  761. ext:(id)aExt
  762. {
  763. if (aEvent == EMMultiDevicesEventGroupDestroy || aEvent == EMMultiDevicesEventGroupLeave) {
  764. if ([self.conversationModel.emModel.conversationId isEqualToString:aGroupId]) {
  765. [self.navigationController popToViewController:self animated:YES];
  766. [self.navigationController popViewControllerAnimated:YES];
  767. }
  768. }
  769. }
  770. #pragma mark - EMChatManagerDelegate
  771. - (BOOL)_isNeedSendReadAckForMessage:(EMMessage *)aMessage
  772. isMarkRead:(BOOL)aIsMarkRead
  773. {
  774. if (!self.isViewDidAppear || aMessage.direction == EMMessageDirectionSend || aMessage.isReadAcked || aMessage.chatType != EMChatTypeChat) {
  775. return NO;
  776. }
  777. EMMessageBody *body = aMessage.body;
  778. if (!aIsMarkRead && (body.type == EMMessageBodyTypeVideo || body.type == EMMessageBodyTypeVoice || body.type == EMMessageBodyTypeImage)) {
  779. return NO;
  780. }
  781. return YES;
  782. }
  783. - (void)messagesDidReceive:(NSArray *)aMessages
  784. {
  785. __weak typeof(self) weakself = self;
  786. dispatch_async(self.msgQueue, ^{
  787. NSString *conId = weakself.conversationModel.emModel.conversationId;
  788. NSMutableArray *msgArray = [[NSMutableArray alloc] init];
  789. for (int i = 0; i < [aMessages count]; i++) {
  790. EMMessage *msg = aMessages[i];
  791. if (![msg.conversationId isEqualToString:conId]) {
  792. continue;
  793. }
  794. if (msg.isNeedGroupAck && !msg.isReadAcked) {
  795. [[EMClient sharedClient].chatManager sendGroupMessageReadAck:msg.messageId toGroup:msg.conversationId content:@"123" completion:^(EMError *error) {
  796. if (error) {
  797. NSLog(@"\n ------ error %@",error.errorDescription);
  798. }
  799. }];
  800. }
  801. if ([weakself _isNeedSendReadAckForMessage:msg isMarkRead:NO]) {
  802. [[EMClient sharedClient].chatManager sendMessageReadAck:msg.messageId toUser:msg.conversationId completion:nil];
  803. }
  804. [weakself.conversationModel.emModel markMessageAsReadWithId:msg.messageId error:nil];
  805. [msgArray addObject:msg];
  806. }
  807. NSArray *formated = [weakself _formatMessages:msgArray];
  808. [weakself.dataArray addObjectsFromArray:formated];
  809. dispatch_async(dispatch_get_main_queue(), ^{
  810. [weakself.tableView reloadData];
  811. [weakself _scrollToBottomRow];
  812. });
  813. });
  814. }
  815. - (void)messagesDidRecall:(NSArray *)aMessages {
  816. __block NSMutableArray *sameObject = [NSMutableArray array];
  817. [aMessages enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  818. EMMessage *msg = (EMMessage *)obj;
  819. [self.dataArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  820. if ([obj isKindOfClass:[EMMessageModel class]]) {
  821. EMMessageModel *model = (EMMessageModel *)obj;
  822. if ([model.emModel.messageId isEqualToString:msg.messageId]) {
  823. // 如果上一行是时间,且下一行也是时间
  824. if (idx - 1 >= 0) {
  825. id nextMessage = nil;
  826. id prevMessage = [self.dataArray objectAtIndex:(idx - 1)];
  827. if (idx + 1 < [self.dataArray count]) {
  828. nextMessage = [self.dataArray objectAtIndex:(idx + 1)];
  829. }
  830. if ((!nextMessage
  831. || [nextMessage isKindOfClass:[NSString class]])
  832. && [prevMessage isKindOfClass:[NSString class]]) {
  833. [sameObject addObject:prevMessage];
  834. }
  835. }
  836. [sameObject addObject:model];
  837. *stop = YES;
  838. }
  839. }
  840. }];
  841. }];
  842. if (sameObject.count > 0) {
  843. for (id obj in sameObject) {
  844. [self.dataArray removeObject:obj];
  845. }
  846. [self.tableView reloadData];
  847. }
  848. }
  849. //为了从home会话列表切进来触发 群组阅读回执 和 消息已读回执
  850. - (void)sendDidReadReceipt
  851. {
  852. __weak typeof(self) weakself = self;
  853. NSString *conId = weakself.conversationModel.emModel.conversationId;
  854. void (^block)(NSArray *aMessages, EMError *aError) = ^(NSArray *aMessages, EMError *aError) {
  855. NSLog(@"\n-------unread: %d messageCount: %lu msgid: %@",self.conversationModel.emModel.unreadMessagesCount,(unsigned long)[aMessages count],self.moreMsgId);
  856. if (!aError && [aMessages count]) {
  857. for (int i = 0; i < [aMessages count]; i++) {
  858. EMMessage *msg = aMessages[i];
  859. if (![msg.conversationId isEqualToString:conId]) {
  860. continue;
  861. }
  862. if (msg.isNeedGroupAck && !msg.isReadAcked) {
  863. [[EMClient sharedClient].chatManager sendGroupMessageReadAck:msg.messageId toGroup:msg.conversationId content:@"123" completion:^(EMError *error) {
  864. if (error) {
  865. NSLog(@"\n ------ error %@",error.errorDescription);
  866. }
  867. }];
  868. }
  869. if ([weakself _isNeedSendReadAckForMessage:msg isMarkRead:NO] && (weakself.conversationModel.emModel.type == EMConversationTypeChat)) {
  870. [[EMClient sharedClient].chatManager sendMessageReadAck:msg.messageId toUser:msg.conversationId completion:nil];
  871. [weakself.conversationModel.emModel markMessageAsReadWithId:msg.messageId error:nil];
  872. }
  873. }
  874. }
  875. };
  876. [self.conversationModel.emModel loadMessagesStartFromId:self.moreMsgId count:self.conversationModel.emModel.unreadMessagesCount searchDirection:EMMessageSearchDirectionUp completion:block];
  877. }
  878. //收到群消息已读回执
  879. - (void)groupMessageDidRead:(EMMessage *)aMessage groupAcks:(NSArray *)aGroupAcks
  880. {
  881. EMMessageModel *msgModel;
  882. EMGroupMessageAck *msgAck = aGroupAcks[0];
  883. for (int i=0; i<[self.dataArray count]; i++) {
  884. if([self.dataArray[i] isKindOfClass:[EMMessageModel class]]){
  885. msgModel = (EMMessageModel *)self.dataArray[i];
  886. }else{
  887. continue;
  888. }
  889. if([msgModel.emModel.messageId isEqualToString:msgAck.messageId]){
  890. msgModel.readReceiptCount = [NSString stringWithFormat:@"阅读回执,已读用户(%d)",msgModel.emModel.groupAckCount];
  891. msgModel.emModel.isReadAcked = YES;
  892. [[EMClient sharedClient].chatManager sendMessageReadAck:msgModel.emModel.messageId toUser:msgModel.emModel.conversationId completion:nil];
  893. [self.dataArray setObject:msgModel atIndexedSubscript:i];
  894. __weak typeof(self) weakself = self;
  895. dispatch_async(dispatch_get_main_queue(), ^{
  896. [weakself.tableView reloadData];
  897. [weakself _scrollToBottomRow];
  898. });
  899. break;
  900. }
  901. }
  902. }
  903. // 收到已读回执
  904. - (void)messagesDidRead:(NSArray *)aMessages
  905. {
  906. __weak typeof(self) weakself = self;
  907. dispatch_async(self.msgQueue, ^{
  908. NSString *conId = weakself.conversationModel.emModel.conversationId;
  909. __block BOOL isReladView = NO;
  910. for (EMMessage *message in aMessages) {
  911. if (![conId isEqualToString:message.conversationId]){
  912. continue;
  913. }
  914. [weakself.dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  915. if ([obj isKindOfClass:[EMMessageModel class]]) {
  916. EMMessageModel *model = (EMMessageModel *)obj;
  917. if ([model.emModel.messageId isEqualToString:message.messageId]) {
  918. model.emModel.isReadAcked = YES;
  919. isReladView = YES;
  920. *stop = YES;
  921. }
  922. }
  923. }];
  924. }
  925. if (isReladView) {
  926. dispatch_async(dispatch_get_main_queue(), ^{
  927. [weakself.tableView reloadData];
  928. });
  929. }
  930. });
  931. }
  932. - (void)messageStatusDidChange:(EMMessage *)aMessage
  933. error:(EMError *)aError
  934. {
  935. __weak typeof(self) weakself = self;
  936. dispatch_async(self.msgQueue, ^{
  937. NSString *conId = weakself.conversationModel.emModel.conversationId;
  938. if (![conId isEqualToString:aMessage.conversationId]){
  939. return ;
  940. }
  941. __block NSUInteger index = NSNotFound;
  942. __block EMMessageModel *reloadModel = nil;
  943. [self.dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  944. if ([obj isKindOfClass:[EMMessageModel class]]) {
  945. EMMessageModel *model = (EMMessageModel *)obj;
  946. if ([model.emModel.messageId isEqualToString:aMessage.messageId]) {
  947. reloadModel = model;
  948. index = idx;
  949. *stop = YES;
  950. }
  951. }
  952. }];
  953. if (index != NSNotFound) {
  954. dispatch_async(dispatch_get_main_queue(), ^{
  955. [weakself.dataArray replaceObjectAtIndex:index withObject:reloadModel];
  956. [weakself.tableView beginUpdates];
  957. [weakself.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
  958. [weakself.tableView endUpdates];
  959. });
  960. }
  961. });
  962. }
  963. - (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages
  964. {
  965. __weak typeof(self) weakself = self;
  966. dispatch_async(self.msgQueue, ^{
  967. NSString *conId = weakself.conversationModel.emModel.conversationId;
  968. for (EMMessage *message in aCmdMessages) {
  969. if (![conId isEqualToString:message.conversationId]) {
  970. continue;
  971. }
  972. EMCmdMessageBody *body = (EMCmdMessageBody *)message.body;
  973. NSString *str = @"";
  974. if ([body.action isEqualToString:MSG_TYPING_BEGIN]) {
  975. str = @"正在输入...";
  976. }
  977. dispatch_async(dispatch_get_main_queue(), ^{
  978. self.titleDetailLabel.text = str;
  979. });
  980. }
  981. });
  982. }
  983. #pragma mark - EMGroupManagerDelegate
  984. - (void)didLeaveGroup:(EMGroup *)aGroup
  985. reason:(EMGroupLeaveReason)aReason
  986. {
  987. EMConversation *conversation = self.conversationModel.emModel;
  988. if (conversation.type == EMChatTypeGroupChat && [aGroup.groupId isEqualToString:conversation.conversationId]) {
  989. [self.navigationController popToViewController:self animated:YES];
  990. [self.navigationController popViewControllerAnimated:YES];
  991. }
  992. }
  993. #pragma mark - EMChatroomManagerDelegate
  994. //有用户加入聊天室
  995. - (void)userDidJoinChatroom:(EMChatroom *)aChatroom
  996. user:(NSString *)aUsername
  997. {
  998. EMConversation *conversation = self.conversationModel.emModel;
  999. if (conversation.type == EMChatTypeChatRoom && [aChatroom.chatroomId isEqualToString:conversation.conversationId]) {
  1000. NSString *str = [NSString stringWithFormat:@"%@ 进入聊天室", aUsername];
  1001. [self showHint:str];
  1002. }
  1003. }
  1004. - (void)userDidLeaveChatroom:(EMChatroom *)aChatroom
  1005. user:(NSString *)aUsername
  1006. {
  1007. EMConversation *conversation = self.conversationModel.emModel;
  1008. if (conversation.type == EMChatTypeChatRoom && [aChatroom.chatroomId isEqualToString:conversation.conversationId]) {
  1009. NSString *str = [NSString stringWithFormat:@"%@ 离开聊天室", aUsername];
  1010. [self showHint:str];
  1011. }
  1012. }
  1013. - (void)didDismissFromChatroom:(EMChatroom *)aChatroom
  1014. reason:(EMChatroomBeKickedReason)aReason
  1015. {
  1016. EMConversation *conversation = self.conversationModel.emModel;
  1017. if (conversation.type == EMChatTypeChatRoom && [aChatroom.chatroomId isEqualToString:conversation.conversationId]) {
  1018. [self.navigationController popToViewController:self animated:YES];
  1019. [self.navigationController popViewControllerAnimated:YES];
  1020. }
  1021. }
  1022. #pragma mark - KeyBoard
  1023. - (void)keyBoardWillShow:(NSNotification *)note
  1024. {
  1025. // 获取用户信息
  1026. NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
  1027. // 获取键盘高度
  1028. CGRect keyBoardBounds = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  1029. CGFloat keyBoardHeight = keyBoardBounds.size.height;
  1030. // 获取键盘动画时间
  1031. CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1032. // 定义好动作
  1033. void (^animation)(void) = ^void(void) {
  1034. [self.chatBar mas_updateConstraints:^(MASConstraintMaker *make) {
  1035. make.bottom.equalTo(self.view).offset(-keyBoardHeight);
  1036. }];
  1037. };
  1038. if (animationTime > 0) {
  1039. [UIView animateWithDuration:animationTime animations:animation completion:^(BOOL finished) {
  1040. [self _scrollToBottomRow];
  1041. }];
  1042. } else {
  1043. animation();
  1044. }
  1045. }
  1046. - (void)keyBoardWillHide:(NSNotification *)note
  1047. {
  1048. // 获取用户信息
  1049. NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
  1050. // 获取键盘动画时间
  1051. CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1052. // 定义好动作
  1053. void (^animation)(void) = ^void(void) {
  1054. [self.chatBar mas_updateConstraints:^(MASConstraintMaker *make) {
  1055. make.bottom.equalTo(self.view);
  1056. }];
  1057. };
  1058. if (animationTime > 0) {
  1059. [UIView animateWithDuration:animationTime animations:animation];
  1060. } else {
  1061. animation();
  1062. }
  1063. if (self.enableTyping) {
  1064. [self _sendEndTyping];
  1065. }
  1066. }
  1067. #pragma mark - NSNotification
  1068. - (void)handleWillPushCallController:(NSNotification *)aNotif
  1069. {
  1070. [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
  1071. [[EMImageBrowser sharedBrowser] dismissViewController];
  1072. [[EMAudioPlayerHelper sharedHelper] stopPlayer];
  1073. }
  1074. - (void)handleCleanMessages:(NSNotification *)aNotif
  1075. {
  1076. NSString *chatId = aNotif.object;
  1077. if (chatId && [chatId isEqualToString:self.conversationModel.emModel.conversationId]) {
  1078. [self.conversationModel.emModel deleteAllMessages:nil];
  1079. [self.dataArray removeAllObjects];
  1080. [self.tableView reloadData];
  1081. }
  1082. }
  1083. - (void)handleGroupSubjectUpdated:(NSNotification *)aNotif
  1084. {
  1085. EMGroup *group = aNotif.object;
  1086. if (!group) {
  1087. return;
  1088. }
  1089. NSString *groupId = group.groupId;
  1090. if ([groupId isEqualToString:self.conversationModel.emModel.conversationId]) {
  1091. self.conversationModel.name = group.subject;
  1092. self.titleLabel.text = group.subject;
  1093. }
  1094. }
  1095. #pragma mark - Gesture Recognizer
  1096. - (void)handleTapTableViewAction:(UITapGestureRecognizer *)aTap
  1097. {
  1098. if (aTap.state == UIGestureRecognizerStateEnded) {
  1099. [self.view endEditing:YES];
  1100. [self.chatBar clearMoreViewAndSelectedButton];
  1101. }
  1102. }
  1103. #pragma mark - Private
  1104. - (void)_joinChatroom
  1105. {
  1106. __weak typeof(self) weakself = self;
  1107. [self showHudInView:self.view hint:@"加入聊天室..."];
  1108. [[EMClient sharedClient].roomManager joinChatroom:self.conversationModel.emModel.conversationId completion:^(EMChatroom *aChatroom, EMError *aError) {
  1109. [weakself hideHud];
  1110. if (aError) {
  1111. [EMAlertController showErrorAlert:@"加入聊天室失败"];
  1112. [weakself.navigationController popViewControllerAnimated:YES];
  1113. } else {
  1114. weakself.isFirstLoadMsg = YES;
  1115. [weakself tableViewDidTriggerHeaderRefresh];
  1116. }
  1117. }];
  1118. }
  1119. - (void)_scrollToBottomRow
  1120. {
  1121. if ([self.dataArray count] > 0) {
  1122. NSInteger toRow = self.dataArray.count - 1;
  1123. NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:toRow inSection:0];
  1124. [self.tableView scrollToRowAtIndexPath:toIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  1125. }
  1126. }
  1127. - (void)_showCustomTransferFileAlertView
  1128. {
  1129. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"(づ。◕‿‿◕。)づ" message:@"需要自定义实现上传附件方法" preferredStyle:UIAlertControllerStyleAlert];
  1130. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
  1131. [alertController addAction:okAction];
  1132. [self presentViewController:alertController animated:YES completion:nil];
  1133. }
  1134. - (NSURL *)_videoConvert2Mp4:(NSURL *)movUrl
  1135. {
  1136. NSURL *mp4Url = nil;
  1137. AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
  1138. NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
  1139. if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
  1140. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
  1141. NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", [self _getAudioOrVideoPath], (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
  1142. mp4Url = [NSURL fileURLWithPath:mp4Path];
  1143. exportSession.outputURL = mp4Url;
  1144. exportSession.shouldOptimizeForNetworkUse = YES;
  1145. exportSession.outputFileType = AVFileTypeMPEG4;
  1146. dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
  1147. [exportSession exportAsynchronouslyWithCompletionHandler:^{
  1148. switch ([exportSession status]) {
  1149. case AVAssetExportSessionStatusFailed: {
  1150. NSLog(@"failed, error:%@.", exportSession.error);
  1151. } break;
  1152. case AVAssetExportSessionStatusCancelled: {
  1153. NSLog(@"cancelled.");
  1154. } break;
  1155. case AVAssetExportSessionStatusCompleted: {
  1156. NSLog(@"completed.");
  1157. } break;
  1158. default: {
  1159. NSLog(@"others.");
  1160. } break;
  1161. }
  1162. dispatch_semaphore_signal(wait);
  1163. }];
  1164. long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
  1165. if (timeout) {
  1166. NSLog(@"timeout.");
  1167. }
  1168. if (wait) {
  1169. //dispatch_release(wait);
  1170. wait = nil;
  1171. }
  1172. }
  1173. return mp4Url;
  1174. }
  1175. #pragma mark - Menu Controller
  1176. - (UIMenuController *)menuController
  1177. {
  1178. if (_menuController == nil) {
  1179. _menuController = [UIMenuController sharedMenuController];
  1180. }
  1181. return _menuController;
  1182. }
  1183. - (UIMenuItem *)deleteMenuItem
  1184. {
  1185. if (_deleteMenuItem == nil) {
  1186. _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMenuItemAction:)];
  1187. }
  1188. return _deleteMenuItem;
  1189. }
  1190. - (UIMenuItem *)copyMenuItem
  1191. {
  1192. if (_copyMenuItem == nil) {
  1193. _copyMenuItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMenuItemAction:)];
  1194. }
  1195. return _copyMenuItem;
  1196. }
  1197. - (UIMenuItem *)transpondMenuItem
  1198. {
  1199. if (_transpondMenuItem == nil) {
  1200. _transpondMenuItem = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(transpondMenuItemAction:)];
  1201. }
  1202. return _transpondMenuItem;
  1203. }
  1204. - (UIMenuItem *)recallMenuItem
  1205. {
  1206. if (_recallMenuItem == nil) {
  1207. _recallMenuItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(recallMenuItemAction:)];
  1208. }
  1209. return _recallMenuItem;
  1210. }
  1211. //删除消息
  1212. - (void)deleteMenuItemAction:(UIMenuItem *)aItem
  1213. {
  1214. if (self.menuIndexPath == nil) {
  1215. return;
  1216. }
  1217. EMMessageModel *model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
  1218. [self.conversationModel.emModel deleteMessageWithId:model.emModel.messageId error:nil];
  1219. NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:self.menuIndexPath.row];
  1220. NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:self.menuIndexPath, nil];
  1221. if (self.menuIndexPath.row - 1 >= 0) {
  1222. id nextMessage = nil;
  1223. id prevMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row - 1)];
  1224. if (self.menuIndexPath.row + 1 < [self.dataArray count]) {
  1225. nextMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row + 1)];
  1226. }
  1227. if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
  1228. [indexs addIndex:self.menuIndexPath.row - 1];
  1229. [indexPaths addObject:[NSIndexPath indexPathForRow:(self.menuIndexPath.row - 1) inSection:0]];
  1230. }
  1231. }
  1232. [self.dataArray removeObjectsAtIndexes:indexs];
  1233. [self.tableView beginUpdates];
  1234. [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
  1235. [self.tableView endUpdates];
  1236. if ([self.dataArray count] == 0) {
  1237. self.msgTimelTag = -1;
  1238. }
  1239. self.menuIndexPath = nil;
  1240. }
  1241. - (void)copyMenuItemAction:(UIMenuItem *)aItem
  1242. {
  1243. if (self.menuIndexPath == nil) {
  1244. return;
  1245. }
  1246. EMMessageModel *model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
  1247. EMTextMessageBody *body = (EMTextMessageBody *)model.emModel.body;
  1248. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1249. pasteboard.string = body.text;
  1250. self.menuIndexPath = nil;
  1251. }
  1252. - (void)transpondMenuItemAction:(UIMenuItem *)aItem
  1253. {
  1254. if (self.menuIndexPath == nil) {
  1255. return;
  1256. }
  1257. EMMessageModel *model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
  1258. EMMsgTranspondViewController *controller = [[EMMsgTranspondViewController alloc] initWithModel:model];
  1259. [self.navigationController pushViewController:controller animated:YES];
  1260. __weak typeof(self) weakself = self;
  1261. [controller setDoneCompletion:^(EMMessageModel * _Nonnull aModel, NSString * _Nonnull aUsername) {
  1262. [weakself _transpondMsg:aModel toUser:aUsername];
  1263. }];
  1264. self.menuIndexPath = nil;
  1265. }
  1266. - (void)recallMenuItemAction:(UIMenuItem *)aItem
  1267. {
  1268. if (self.menuIndexPath == nil) {
  1269. return;
  1270. }
  1271. NSIndexPath *indexPath = self.menuIndexPath;
  1272. __weak typeof(self) weakself = self;
  1273. EMMessageModel *model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
  1274. [[EMClient sharedClient].chatManager recallMessage:model.emModel completion:^(EMMessage *aMessage, EMError *aError) {
  1275. if (aError) {
  1276. [EMAlertController showErrorAlert:aError.errorDescription];
  1277. } else {
  1278. EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:@"您撤回一条消息"];
  1279. NSString *from = [[EMClient sharedClient] currentUsername];
  1280. NSString *to = self.conversationModel.emModel.conversationId;
  1281. EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:@{MSG_EXT_RECALL:@(YES)}];
  1282. message.chatType = (EMChatType)self.conversationModel.emModel.type;
  1283. message.isRead = YES;
  1284. message.timestamp = model.emModel.timestamp;
  1285. message.localTime = model.emModel.localTime;
  1286. [weakself.conversationModel.emModel insertMessage:message error:nil];
  1287. EMMessageModel *model = [[EMMessageModel alloc] initWithEMMessage:message];
  1288. [weakself.dataArray replaceObjectAtIndex:indexPath.row withObject:model];
  1289. [weakself.tableView reloadData];
  1290. }
  1291. }];
  1292. self.menuIndexPath = nil;
  1293. }
  1294. - (void)_showMenuViewController:(EMMessageCell *)aCell
  1295. model:(EMMessageModel *)aModel
  1296. {
  1297. [self becomeFirstResponder];
  1298. NSMutableArray *items = [[NSMutableArray alloc] init];
  1299. if (aModel.type == EMMessageTypeText) {
  1300. [items addObject:self.copyMenuItem];
  1301. [items addObject:self.transpondMenuItem];
  1302. } else if (aModel.type == EMMessageTypeLocation || aModel.type == EMMessageTypeImage || aModel.type == EMMessageTypeVideo) {
  1303. [items addObject:self.transpondMenuItem];
  1304. }
  1305. [items addObject:self.deleteMenuItem];
  1306. if (aModel.emModel.direction == EMMessageDirectionSend) {
  1307. [items addObject:self.recallMenuItem];
  1308. }
  1309. [self.menuController setMenuItems:items];
  1310. [self.menuController setTargetRect:aCell.bubbleView.frame inView:aCell];
  1311. [self.menuController setMenuVisible:YES animated:NO];
  1312. }
  1313. #pragma mark - Transpond Message
  1314. - (void)_forwardMsgWithBody:(EMMessageBody *)aBody
  1315. to:(NSString *)aTo
  1316. ext:(NSDictionary *)aExt
  1317. completion:(void (^)(EMMessage *message))aCompletionBlock
  1318. {
  1319. NSString *from = [[EMClient sharedClient] currentUsername];
  1320. EMMessage *message = [[EMMessage alloc] initWithConversationID:aTo from:from to:aTo body:aBody ext:aExt];
  1321. message.chatType = EMChatTypeChat;
  1322. __weak typeof(self) weakself = self;
  1323. [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
  1324. if (error) {
  1325. [weakself.conversationModel.emModel deleteMessageWithId:message.messageId error:nil];
  1326. [EMAlertController showErrorAlert:@"转发消息失败"];
  1327. } else {
  1328. if (aCompletionBlock) {
  1329. aCompletionBlock(message);
  1330. }
  1331. [EMAlertController showSuccessAlert:@"转发消息成功"];
  1332. }
  1333. }];
  1334. }
  1335. - (void)_forwardImageMsg:(EMMessage *)aMsg
  1336. toUser:(NSString *)aUsername
  1337. {
  1338. NSString *thumbnailLocalPath = [(EMImageMessageBody *)aMsg.body thumbnailLocalPath];
  1339. __weak typeof(self) weakself = self;
  1340. void (^block)(EMMessage *aMessage) = ^(EMMessage *aMessage) {
  1341. EMImageMessageBody *oldBody = (EMImageMessageBody *)aMessage.body;
  1342. EMImageMessageBody *newBody = [[EMImageMessageBody alloc] initWithData:nil thumbnailData:[NSData dataWithContentsOfFile:oldBody.thumbnailLocalPath]];
  1343. newBody.thumbnailRemotePath = oldBody.thumbnailRemotePath;
  1344. newBody.remotePath = oldBody.remotePath;
  1345. [weakself _forwardMsgWithBody:newBody to:aUsername ext:aMsg.ext completion:^(EMMessage *message) {
  1346. [(EMImageMessageBody *)message.body setLocalPath:oldBody.localPath];
  1347. [[EMClient sharedClient].chatManager updateMessage:message completion:nil];
  1348. }];
  1349. };
  1350. if (![[NSFileManager defaultManager] fileExistsAtPath:thumbnailLocalPath]) {
  1351. [[EMClient sharedClient].chatManager downloadMessageThumbnail:aMsg progress:nil completion:^(EMMessage *message, EMError *error) {
  1352. if (error) {
  1353. [EMAlertController showErrorAlert:@"转发消息失败"];
  1354. } else {
  1355. block(aMsg);
  1356. }
  1357. }];
  1358. } else {
  1359. block(aMsg);
  1360. }
  1361. }
  1362. - (void)_forwardVideoMsg:(EMMessage *)aMsg
  1363. toUser:(NSString *)aUsername
  1364. {
  1365. EMVideoMessageBody *oldBody = (EMVideoMessageBody *)aMsg.body;
  1366. __weak typeof(self) weakself = self;
  1367. void (^block)(EMMessage *aMessage) = ^(EMMessage *aMessage) {
  1368. EMVideoMessageBody *newBody = [[EMVideoMessageBody alloc] initWithLocalPath:oldBody.localPath displayName:oldBody.displayName];
  1369. newBody.thumbnailLocalPath = oldBody.thumbnailLocalPath;
  1370. [weakself _forwardMsgWithBody:newBody to:aUsername ext:aMsg.ext completion:^(EMMessage *message) {
  1371. [(EMVideoMessageBody *)message.body setLocalPath:[(EMVideoMessageBody *)aMessage.body localPath]];
  1372. [[EMClient sharedClient].chatManager updateMessage:message completion:nil];
  1373. }];
  1374. };
  1375. if (![[NSFileManager defaultManager] fileExistsAtPath:oldBody.localPath]) {
  1376. [[EMClient sharedClient].chatManager downloadMessageAttachment:aMsg progress:nil completion:^(EMMessage *message, EMError *error) {
  1377. if (error) {
  1378. [EMAlertController showErrorAlert:@"转发消息失败"];
  1379. } else {
  1380. block(aMsg);
  1381. }
  1382. }];
  1383. } else {
  1384. block(aMsg);
  1385. }
  1386. }
  1387. - (void)_transpondMsg:(EMMessageModel *)aModel
  1388. toUser:(NSString *)aUsername
  1389. {
  1390. EMMessageBodyType type = aModel.emModel.body.type;
  1391. if (type == EMMessageBodyTypeText || type == EMMessageBodyTypeLocation) {
  1392. [self _forwardMsgWithBody:aModel.emModel.body to:aUsername ext:aModel.emModel.ext completion:nil];
  1393. } else if (type == EMMessageBodyTypeImage) {
  1394. [self _forwardImageMsg:aModel.emModel toUser:aUsername];
  1395. } else if (type == EMMessageBodyTypeVideo) {
  1396. [self _forwardVideoMsg:aModel.emModel toUser:aUsername];
  1397. }
  1398. }
  1399. #pragma mark - Send Message
  1400. - (void)_sendTextAction:(NSString *)aText
  1401. ext:(NSDictionary *)aExt
  1402. {
  1403. [self.chatBar clearInputViewText];
  1404. if ([aText length] == 0) {
  1405. return;
  1406. }
  1407. //TODO: 处理@
  1408. //messageExt
  1409. //TODO: 处理表情
  1410. // NSString *sendText = [EaseConvertToCommonEmoticonsHelper convertToCommonEmoticons:aText];
  1411. EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:aText];
  1412. [self _sendMessageWithBody:body ext:aExt isUpload:NO];
  1413. if (self.enableTyping) {
  1414. [self _sendEndTyping];
  1415. }
  1416. }
  1417. - (void)_sendImageDataAction:(NSData *)aImageData
  1418. {
  1419. EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithData:aImageData displayName:@"image"];
  1420. [self _sendMessageWithBody:body ext:nil isUpload:YES];
  1421. }
  1422. - (void)_sendLocationAction:(CLLocationCoordinate2D)aCoord
  1423. address:(NSString *)aAddress
  1424. {
  1425. EMLocationMessageBody *body = [[EMLocationMessageBody alloc] initWithLatitude:aCoord.latitude longitude:aCoord.longitude address:aAddress];
  1426. [self _sendMessageWithBody:body ext:nil isUpload:NO];
  1427. }
  1428. - (void)_sendVideoAction:(NSURL *)aUrl
  1429. {
  1430. EMVideoMessageBody *body = [[EMVideoMessageBody alloc] initWithLocalPath:[aUrl path] displayName:@"video.mp4"];
  1431. [self _sendMessageWithBody:body ext:nil isUpload:YES];
  1432. }
  1433. - (void)_sendBeginTyping
  1434. {
  1435. NSString *from = [[EMClient sharedClient] currentUsername];
  1436. NSString *to = self.conversationModel.emModel.conversationId;
  1437. EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:MSG_TYPING_BEGIN];
  1438. body.isDeliverOnlineOnly = YES;
  1439. EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:nil];
  1440. message.chatType = (EMChatType)self.conversationModel.emModel.type;
  1441. [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:nil];
  1442. }
  1443. //正在输入
  1444. - (void)_sendEndTyping
  1445. {
  1446. self.isTyping = NO;
  1447. NSString *from = [[EMClient sharedClient] currentUsername];
  1448. NSString *to = self.conversationModel.emModel.conversationId;
  1449. EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:MSG_TYPING_END];
  1450. body.isDeliverOnlineOnly = YES;
  1451. EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:nil];
  1452. message.chatType = (EMChatType)self.conversationModel.emModel.type;
  1453. [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:nil];
  1454. }
  1455. #pragma mark - Data
  1456. - (NSArray *)_formatMessages:(NSArray<EMMessage *> *)aMessages
  1457. {
  1458. NSMutableArray *formated = [[NSMutableArray alloc] init];
  1459. for (int i = 0; i < [aMessages count]; i++) {
  1460. EMMessage *msg = aMessages[i];
  1461. // cmd消息不展示
  1462. if(msg.body.type == EMMessageBodyTypeCmd) {
  1463. continue;
  1464. }
  1465. if (msg.chatType == EMChatTypeChat && msg.isReadAcked && (msg.body.type == EMMessageBodyTypeText || msg.body.type == EMMessageBodyTypeLocation)) {
  1466. //
  1467. [[EMClient sharedClient].chatManager sendMessageReadAck:msg.messageId toUser:msg.conversationId completion:nil];
  1468. } else if (msg.chatType == EMChatTypeGroupChat && !msg.isReadAcked && (msg.body.type == EMMessageBodyTypeText || msg.body.type == EMMessageBodyTypeLocation)) {
  1469. }
  1470. CGFloat interval = (self.msgTimelTag - msg.timestamp) / 1000;
  1471. if (self.msgTimelTag < 0 || interval > 60 || interval < -60) {
  1472. NSString *timeStr = [EMDateHelper formattedTimeFromTimeInterval:msg.timestamp];
  1473. [formated addObject:timeStr];
  1474. self.msgTimelTag = msg.timestamp;
  1475. }
  1476. EMMessageModel *model = [[EMMessageModel alloc] initWithEMMessage:msg];
  1477. [formated addObject:model];
  1478. }
  1479. return formated;
  1480. }
  1481. - (void)tableViewDidTriggerHeaderRefresh
  1482. {
  1483. __weak typeof(self) weakself = self;
  1484. void (^block)(NSArray *aMessages, EMError *aError) = ^(NSArray *aMessages, EMError *aError) {
  1485. if (!aError && [aMessages count]) {
  1486. EMMessage *msg = aMessages[0];
  1487. weakself.moreMsgId = msg.messageId;
  1488. dispatch_async(self.msgQueue, ^{
  1489. NSArray *formated = [weakself _formatMessages:aMessages];
  1490. [weakself.dataArray insertObjects:formated atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [formated count])]];
  1491. dispatch_async(dispatch_get_main_queue(), ^{
  1492. [weakself.tableView reloadData];
  1493. if (weakself.isFirstLoadMsg) {
  1494. weakself.isFirstLoadMsg = NO;
  1495. [weakself _scrollToBottomRow];
  1496. }
  1497. });
  1498. });
  1499. }
  1500. [weakself tableViewDidFinishTriggerHeader:YES reload:NO];
  1501. };
  1502. if ([EMDemoOptions sharedOptions].isPriorityGetMsgFromServer) {
  1503. EMConversation *conversation = self.conversationModel.emModel;
  1504. [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:conversation.conversationId
  1505. conversationType:conversation.type
  1506. startMessageId:self.moreMsgId
  1507. pageSize:50
  1508. completion:^(EMCursorResult *aResult, EMError *aError)
  1509. {
  1510. block(aResult.list, aError);
  1511. }];
  1512. } else {
  1513. [self.conversationModel.emModel loadMessagesStartFromId:self.moreMsgId
  1514. count:50
  1515. searchDirection:EMMessageSearchDirectionUp
  1516. completion:block];
  1517. if(self.conversationModel.emModel.unreadMessagesCount > 0){
  1518. [self sendDidReadReceipt];
  1519. }
  1520. }
  1521. }
  1522. #pragma mark - Action
  1523. - (void)backAction
  1524. {
  1525. [[EMAudioPlayerHelper sharedHelper] stopPlayer];
  1526. [EMConversationHelper resortConversationsLatestMessage];
  1527. EMConversation *conversation = self.conversationModel.emModel;
  1528. if (conversation.type == EMChatTypeChatRoom) {
  1529. [[EMClient sharedClient].roomManager leaveChatroom:conversation.conversationId completion:nil];
  1530. }
  1531. [self.navigationController popViewControllerAnimated:YES];
  1532. }
  1533. //删除该会话所有消息,同时清除内存和数据库中的消息
  1534. - (void)deleteAllMessageAction
  1535. {
  1536. EMError *error = nil;
  1537. [self.conversationModel.emModel deleteAllMessages:&error];
  1538. if (!error) {
  1539. [self.dataArray removeAllObjects];
  1540. [self.tableView reloadData];
  1541. }
  1542. }
  1543. - (void)groupOrChatroomInfoAction
  1544. {
  1545. if (self.conversationModel.emModel.type == EMConversationTypeGroupChat) {
  1546. [[NSNotificationCenter defaultCenter] postNotificationName:GROUP_INFO_PUSHVIEWCONTROLLER object:@{NOTIF_ID:self.conversationModel.emModel.conversationId, NOTIF_NAVICONTROLLER:self.navigationController}];
  1547. } else if (self.conversationModel.emModel.type == EMConversationTypeChatRoom) {
  1548. [[NSNotificationCenter defaultCenter] postNotificationName:CHATROOM_INFO_PUSHVIEWCONTROLLER object:@{NOTIF_ID:self.conversationModel.emModel.conversationId, NOTIF_NAVICONTROLLER:self.navigationController}];
  1549. }
  1550. }
  1551. //发送消息体
  1552. - (void)_sendMessageWithBody:(EMMessageBody *)aBody
  1553. ext:(NSDictionary *)aExt
  1554. isUpload:(BOOL)aIsUpload
  1555. {
  1556. if (!([EMClient sharedClient].options.isAutoTransferMessageAttachments) && aIsUpload) {
  1557. [self _showCustomTransferFileAlertView];
  1558. return;
  1559. }
  1560. NSString *from = [[EMClient sharedClient] currentUsername];
  1561. NSString *to = self.conversationModel.emModel.conversationId;
  1562. EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:aBody ext:aExt];
  1563. //是否需要发送阅读回执
  1564. if([aExt objectForKey:MSG_EXT_READ_RECEIPT]) {
  1565. message.isNeedGroupAck = YES;
  1566. }
  1567. message.chatType = (EMChatType)self.conversationModel.emModel.type;
  1568. __weak typeof(self) weakself = self;
  1569. [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
  1570. NSArray *formated = [weakself _formatMessages:@[message]];
  1571. [weakself.dataArray addObjectsFromArray:formated];
  1572. dispatch_async(dispatch_get_main_queue(), ^{
  1573. [weakself.tableView reloadData];
  1574. [weakself _scrollToBottomRow];
  1575. });
  1576. //[weakself.tableView reloadData];
  1577. }];
  1578. }
  1579. @end