JCHATConversationViewController.m 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350
  1. //
  2. // JCHATSendMessageViewController.m
  3. // JPush IM
  4. //
  5. // Created by Apple on 14/12/26.
  6. // Copyright (c) 2014年 Apple. All rights reserved.
  7. //
  8. #import "JCHATConversationViewController.h"
  9. #import "MJPhoto.h"
  10. #import "MJPhotoBrowser.h"
  11. #import "JCHATFileManager.h"
  12. #import "JCHATShowTimeCell.h"
  13. #import "AppDelegate.h"
  14. #import "UIImage+ResizeMagick.h"
  15. #import <MobileCoreServices/UTCoreTypes.h>
  16. #import <JMessage/JMSGConversation.h>
  17. #import "JCHATStringUtils.h"
  18. #import <UIKit/UIPrintInfo.h>
  19. #import "JCHATLoadMessageTableViewCell.h"
  20. #import "JCHATSendMsgManager.h"
  21. #import <AssetsLibrary/AssetsLibrary.h>
  22. #import <Photos/Photos.h>
  23. #import "TencentLocationVC.h"
  24. #import "twEmojiView.h"
  25. #import "ASRView.h"
  26. #import "PubH5.h"
  27. #import "YBCenterVC.h"
  28. #import <TZImagePickerController/TZImagePickerController.h>
  29. @interface JCHATConversationViewController ()<twEmojiViewDelegate,TouchMsgTabDelegate,TZImagePickerControllerDelegate,UIGestureRecognizerDelegate> {
  30. @private
  31. BOOL isNoOtherMessage;
  32. NSInteger messageOffset;
  33. NSMutableArray *_imgDataArr;
  34. // JMSGConversation *_conversation;
  35. NSMutableDictionary *_allMessageDic; //缓存所有的message model
  36. NSMutableArray *_allmessageIdArr; //按序缓存后有的messageId, 于allMessage 一起使用
  37. NSMutableArray *_userArr;
  38. UIButton *_rightBtn;
  39. NSMutableDictionary *_refreshAvatarUsersDic;
  40. twEmojiView *_emojiV;
  41. ASRView *_asrView;
  42. BOOL _asrMoveUp;
  43. UIView *followView;
  44. //图片多选
  45. BOOL _sendImgLimit;
  46. int _didSendCount;
  47. NSArray *_didSelImgA;
  48. NSString *isfirstAttent;
  49. }
  50. @end
  51. @implementation JCHATConversationViewController
  52. - (void)viewWillAppear:(BOOL)animated {
  53. DDLogDebug(@"Event - viewWillAppear");
  54. [super viewWillAppear:animated];
  55. [IQKeyboardManager sharedManager].enable = NO;
  56. [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
  57. [self.toolBarContainer.toolbar drawRect:self.toolBarContainer.toolbar.frame];
  58. kWEAKSELF
  59. [_conversation refreshTargetInfoFromServer:^(id resultObject, NSError *error) {
  60. DDLogDebug(@"refresh nav right button");
  61. kSTRONGSELF
  62. //[strongSelf.navigationController setNavigationBarHidden:NO];
  63. // 禁用 iOS7 返回手势
  64. if ([strongSelf.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  65. strongSelf.navigationController.interactivePopGestureRecognizer.enabled = YES;
  66. }
  67. if (strongSelf.conversation.conversationType == kJMSGConversationTypeGroup) {
  68. //[strongSelf updateGroupConversationTittle:nil];
  69. } else {
  70. strongSelf.title = [resultObject title];
  71. }
  72. [_messageTableView reloadData];
  73. }];
  74. }
  75. - (void)viewWillDisappear:(BOOL)animated {
  76. DDLogDebug(@"Event - viewWillDisappear");
  77. [super viewWillDisappear:animated];
  78. [IQKeyboardManager sharedManager].enable = YES;
  79. [_conversation clearUnreadCount];
  80. [[JCHATAudioPlayerHelper shareInstance] stopAudio];
  81. [[JCHATAudioPlayerHelper shareInstance] setDelegate:nil];
  82. }
  83. - (void)viewDidLoad {
  84. [super viewDidLoad];
  85. self.navigationController.navigationBar.hidden = YES;
  86. _asrMoveUp = NO;
  87. _refreshAvatarUsersDic = [NSMutableDictionary dictionary];
  88. _allMessageDic = [NSMutableDictionary dictionary];
  89. _allmessageIdArr = [NSMutableArray array];
  90. _imgDataArr = [NSMutableArray array];
  91. DDLogDebug(@"Action - viewDidLoad");
  92. self.rightBtn.hidden = NO;
  93. [self.rightBtn setImage:[UIImage imageNamed:@"center_more"] forState:0];
  94. self.titleL.text = _userModel.unameStr;
  95. self.messageTabTop.constant = 64+statusbarHeight;
  96. self.messageTableView.touchDelegate = self;
  97. self.messageTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  98. self.titleL.text = _userModel.unameStr;
  99. [self setupView];
  100. [self addNotification];
  101. [self addDelegate];
  102. [self getGroupMemberListWithGetMessageFlag:YES];
  103. if (![_userModel.isAtt isEqual:@"1"]) {
  104. [self creatFollowView];
  105. }
  106. }
  107. - (void)creatFollowView{
  108. followView = [[UIView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, 40)];
  109. followView.backgroundColor = _isWhiteStyle?[UIColor whiteColor]:CellRow_Cor;
  110. [self.view addSubview:followView];
  111. UIButton *fCloseBtn = [UIButton buttonWithType:0];
  112. fCloseBtn.frame = CGRectMake(5, 5, 30, 30);
  113. [fCloseBtn setImage:[UIImage imageNamed:@"提示关闭"] forState:0];
  114. fCloseBtn.imageEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 8);
  115. [fCloseBtn addTarget:self action:@selector(removeFollowView) forControlEvents:UIControlEventTouchUpInside];
  116. [followView addSubview:fCloseBtn];
  117. UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(fCloseBtn.right, 0, _window_width/2, 40)];
  118. label.font = [UIFont systemFontOfSize:12];
  119. label.text = YZMsg(@"点击关注,可及时看到对方动态");
  120. label.textColor = RGB_COLOR(@"#828282", 1);
  121. [followView addSubview:label];
  122. UIButton *followBtn = [UIButton buttonWithType:0];
  123. followBtn.frame = CGRectMake(_window_width-54, 10, 44, 20);
  124. [followBtn setTitle:YZMsg(@"关注") forState:0];
  125. followBtn.layer.cornerRadius = 10;
  126. followBtn.layer.masksToBounds = YES;
  127. followBtn.titleLabel.font = SYS_Font(12);
  128. followBtn.layer.borderColor = Pink_Cor.CGColor;
  129. followBtn.layer.borderWidth = 1;
  130. [followBtn setTitleColor:Pink_Cor forState:0];
  131. [followBtn addTarget:self action:@selector(doFollow) forControlEvents:UIControlEventTouchUpInside];
  132. [followView addSubview:followBtn];
  133. // 闪出关注的距离
  134. //_messageTableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
  135. }
  136. - (void)removeFollowView{
  137. [followView removeFromSuperview];
  138. followView = nil;
  139. //_messageTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
  140. }
  141. - (void)doFollow{
  142. YBWeakSelf;
  143. NSDictionary *dic = @{
  144. @"uid":[Config getOwnID],
  145. @"touid":_userModel.uidStr
  146. };
  147. [YBNetworking postWithUrl:@"User.isFirstAttent" Dic:dic Suc:^(int code, id info, NSString *msg) {
  148. if (code == 0) {
  149. NSDictionary *infos = [info firstObject];
  150. //is_first 1 第一次关注 0 不是第一次关注
  151. isfirstAttent = minstr([infos valueForKey:@"is_first"]);
  152. [weakSelf setAttent];
  153. }
  154. } Fail:^(id fail) {
  155. }];
  156. }
  157. -(void)setAttent{
  158. NSString *postUrl = @"User.setAttent";
  159. NSDictionary *postDic = @{
  160. @"touid":_userModel.uidStr
  161. };
  162. [YBNetworking postWithUrl:postUrl Dic:postDic Suc:^(int code, id info, NSString *msg) {
  163. if (code == 0) {
  164. [MBProgressHUD showError:YZMsg(@"关注对方成功")];
  165. if (self.block) {
  166. self.block(1);
  167. }
  168. [self removeFollowView];
  169. if ([isfirstAttent isEqual:@"1"]) {
  170. //发送自定义消息
  171. NSDictionary *infoDic = @{@"uid":[Config getOwnID],@"touid":_userModel.uidStr,@"type":@"follow"};
  172. JMSGMessage *message = nil;
  173. JMSGCustomContent *customFormat = [[JMSGCustomContent alloc]initWithCustomDictionary:infoDic];
  174. message = [_conversation createMessageWithContent:customFormat];
  175. JMSGOptionalContent *option = [[JMSGOptionalContent alloc] init];
  176. option.noSaveNotification = YES;
  177. [_conversation sendMessage:message optionalContent:option];
  178. [self addmessageShowTimeData:message.timestamp];
  179. JCHATChatModel *model =[[JCHATChatModel alloc] init];
  180. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  181. [self addMessage:model];
  182. }
  183. }else{
  184. [MBProgressHUD showError:msg];
  185. }
  186. } Fail:^(id fail) {
  187. }];
  188. }
  189. - (void)updateGroupConversationTittle:(JMSGGroup *)newGroup {
  190. JMSGGroup *group;
  191. if (newGroup == nil) {
  192. group = self.conversation.target;
  193. } else {
  194. group = newGroup;
  195. }
  196. if ([group.name isEqualToString:@""]) {
  197. self.title = @"群聊";
  198. } else {
  199. self.title = group.name;
  200. }
  201. self.title = [NSString stringWithFormat:@"%@(%lu)",self.title,(unsigned long)[group.memberArray count]];
  202. [self getGroupMemberListWithGetMessageFlag:NO];
  203. if (self.isConversationChange) {
  204. [self cleanMessageCache];
  205. [self getPageMessage];
  206. self.isConversationChange = NO;
  207. }
  208. }
  209. - (void)viewDidLayoutSubviews {
  210. DDLogDebug(@"Event - viewDidLayoutSubviews");
  211. [self scrollToBottomAnimated:NO];
  212. }
  213. #pragma mark --释放内存
  214. - (void)dealloc {
  215. DDLogDebug(@"Action -- dealloc");
  216. // [[NSNotificationCenter defaultCenter] removeObserver:self name:kAlertToSendImage object:self];
  217. [[NSNotificationCenter defaultCenter] removeObserver:self];
  218. [self.toolBarContainer.toolbar.textView removeObserver:self forKeyPath:@"contentSize"];
  219. //remove delegate
  220. [[NSNotificationCenter defaultCenter] removeObserver:self name:kAlertToSendImage object:self];
  221. [JMessage removeDelegate:self withConversation:_conversation];
  222. }
  223. - (void)addtoolbar {
  224. self.toolBarContainer.toolbar.frame = CGRectMake(0, 0, kApplicationWidth, 45);
  225. [self.toolBarContainer addSubview:self.toolBarContainer.toolbar];
  226. }
  227. #pragma mark - 子控件
  228. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;{
  229. if ([touch.view isDescendantOfView:_emojiV] ||
  230. [touch.view isDescendantOfView:_toolBarContainer] ||
  231. [touch.view isDescendantOfView:_moreViewContainer]) {
  232. return NO;
  233. }
  234. return YES;
  235. }
  236. - (void)setupView {
  237. [_conversation clearUnreadCount];
  238. UITapGestureRecognizer *gesture =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
  239. gesture.delegate = self;
  240. [self.view addGestureRecognizer:gesture];
  241. [self.view setBackgroundColor:RGB_COLOR(@"#201c36", 1)];
  242. _toolBarToBottomConstrait.constant = 0+ShowDiff;
  243. _toolBarContainer.toolbar.delegate = self;
  244. [_toolBarContainer.toolbar setUserInteractionEnabled:YES];
  245. self.toolBarContainer.toolbar.textView.text = [[JCHATSendMsgManager ins] draftStringWithConversation:_conversation];
  246. _messageTableView.userInteractionEnabled = YES;
  247. _messageTableView.showsVerticalScrollIndicator = NO;
  248. _messageTableView.delegate = self;
  249. _messageTableView.dataSource = self;
  250. _messageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  251. _messageTableView.backgroundColor = _isWhiteStyle?RGB_COLOR(@"#f4f5f6", 1):Normal_Color;
  252. _moreViewContainer.moreView.delegate = self;
  253. _moreViewContainer.moreView.backgroundColor = _isWhiteStyle?[UIColor whiteColor]:Normal_Color;
  254. if (_isWhiteStyle) {
  255. self.view.backgroundColor = [UIColor whiteColor];
  256. _toolBarContainer.toolbar.backgroundColor = [UIColor whiteColor];
  257. _toolBarContainer.toolbar.textView.backgroundColor = RGB_COLOR(@"#f4f5f6", 1);
  258. }
  259. //表情
  260. _emojiV = [[twEmojiView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff)];
  261. _emojiV.delegate = self;
  262. [self.view addSubview:_emojiV];
  263. }
  264. - (void)getGroupMemberListWithGetMessageFlag:(BOOL)getMesageFlag {
  265. if (self.conversation && self.conversation.conversationType == kJMSGConversationTypeGroup) {
  266. JMSGGroup *group = nil;
  267. group = self.conversation.target;
  268. _userArr = [NSMutableArray arrayWithArray:[group memberArray]];
  269. [self isContantMeWithUserArr:_userArr];
  270. if (getMesageFlag) {
  271. [self getPageMessage];
  272. }
  273. } else {
  274. if (getMesageFlag) {
  275. [self getPageMessage];
  276. }
  277. [self hidenDetailBtn:NO];
  278. }
  279. }
  280. - (void)isContantMeWithUserArr:(NSMutableArray *)userArr {
  281. BOOL hideFlag = YES;
  282. for (NSInteger i =0; i< [userArr count]; i++) {
  283. JMSGUser *user = [userArr objectAtIndex:i];
  284. if ([user.username isEqualToString:[JMSGUser myInfo].username]) {
  285. hideFlag = NO;
  286. break;
  287. }
  288. }
  289. if (!hideFlag) {
  290. [self reloadAllCellAvatarImage];
  291. }
  292. [self hidenDetailBtn:hideFlag];
  293. }
  294. - (void)hidenDetailBtn:(BOOL)flag {
  295. [_rightBtn setHidden:flag];
  296. }
  297. - (void)setTitleWithUser:(JMSGUser *)user {
  298. self.title = _conversation.title;
  299. }
  300. #pragma mark --JMessageDelegate
  301. - (void)onSendMessageResponse:(JMSGMessage *)message error:(NSError *)error {
  302. DDLogDebug(@"Event - sendMessageResponse");
  303. if (message != nil) {
  304. NSLog(@"发送的 Message: %@",message);
  305. }
  306. [self relayoutTableCellWithMessage:message];
  307. if (error != nil) {
  308. DDLogDebug(@"Send response error - %@", error);
  309. [_conversation clearUnreadCount];
  310. NSString *alert = [JCHATStringUtils errorAlert:error];
  311. if (alert == nil) {
  312. alert = [error description];
  313. }
  314. [MBProgressHUD hideHUDForView:self.view animated:YES];
  315. //[MBProgressHUD showMessage:alert view:self.view];
  316. //[MBProgressHUD showMessage:alert toView:self.view];
  317. [MBProgressHUD showPop:alert];
  318. return;
  319. }
  320. JCHATChatModel *model = _allMessageDic[message.msgId];
  321. if (!model) {
  322. return;
  323. }
  324. }
  325. #pragma mark - 消息撤回
  326. //撤回消息-重置声音播放和图片放大
  327. -(void)retractResetVoiceOrImg {
  328. if ([[JCHATAudioPlayerHelper shareInstance] isPlaying]) {
  329. [[JCHATAudioPlayerHelper shareInstance] stopAudio];
  330. }
  331. if ([[[YBBaseAppDelegate sharedAppDelegate] topViewController] isKindOfClass:[MJPhotoBrowser class]]) {
  332. MJPhotoBrowser *pBrowser = (MJPhotoBrowser *)[[YBBaseAppDelegate sharedAppDelegate] topViewController];
  333. [pBrowser retractMsgDismissBrowser];
  334. };
  335. }
  336. - (void)onReceiveMessageRetractEvent:(JMSGMessageRetractEvent *)retractEvent;{
  337. NSLog(@"----:%@-%@",retractEvent,retractEvent.retractMessage);
  338. [self retractResetVoiceOrImg];
  339. [self retractMsgReplace:retractEvent.retractMessage];
  340. }
  341. -(void)retractMsgReplace:(JMSGMessage *)jMessage {
  342. NSString *retractMsgId = jMessage.msgId;
  343. JCHATChatModel *model = [_allMessageDic objectForKey:retractMsgId];
  344. [model setChatModelWith:jMessage conversationType:_conversation userModel:_userModel];
  345. [_allMessageDic removeObjectForKey:retractMsgId];
  346. [_allMessageDic setObject:model forKey:model.message.msgId];
  347. //如果撤回的是图片图片数组要处理一下
  348. NSMutableArray *need_del_array = [NSMutableArray array];
  349. for (JCHATChatModel *imgModel in _imgDataArr) {
  350. if ([imgModel.message.msgId isEqual:model.message.msgId]) {
  351. [need_del_array addObject:imgModel];
  352. }
  353. }
  354. [_imgDataArr removeObjectsInArray:need_del_array];
  355. [_messageTableView reloadData];
  356. [self scrollToBottomAnimated:NO];
  357. }
  358. #pragma mark - 收到消息
  359. - (void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error {
  360. if (message != nil) {
  361. }
  362. if (error != nil) {
  363. JCHATChatModel *model = [[JCHATChatModel alloc] init];
  364. [model setErrorMessageChatModelWithError:error];
  365. [self addMessage:model];
  366. return;
  367. }
  368. if (![self.conversation isMessageForThisConversation:message]) {
  369. return;
  370. }
  371. //ray-----
  372. // if (message.contentType == kJMSGContentTypeCustom) {
  373. // return;
  374. // }
  375. DDLogDebug(@"Event - receiveMessageNotification");
  376. kWEAKSELF
  377. JCHATMAINTHREAD((^{
  378. kSTRONGSELF
  379. if (!message) {
  380. DDLogWarn(@"get the nil message .");
  381. return;
  382. }
  383. //if (_allMessageDic[message.msgId] != nil) {
  384. // DDLogDebug(@"该条消息已加载");
  385. // return;
  386. //}
  387. if (message.contentType == kJMSGContentTypeEventNotification) {
  388. if (((JMSGEventContent *)message.content).eventType == kJMSGEventNotificationRemoveGroupMembers
  389. && ![((JMSGGroup *)_conversation.target) isMyselfGroupMember]) {
  390. // [strongSelf setupNavigation];
  391. }
  392. }
  393. if (_conversation.conversationType == kJMSGConversationTypeSingle) {
  394. } else if (![((JMSGGroup *)_conversation.target).gid isEqualToString:((JMSGGroup *)message.target).gid]){
  395. return;
  396. }
  397. JCHATChatModel *model = [_allMessageDic objectForKey:message.msgId];
  398. if (model) {// 说明已经加载,说明可能是同步下来的多媒体消息,下载完成,然后再次收到就去刷新
  399. model.message = message;
  400. [strongSelf refreshCellMessageMediaWithChatModel:model];
  401. }else{
  402. NSString *firstMsgId = [_allmessageIdArr firstObject];
  403. JCHATChatModel *firstModel = [_allMessageDic objectForKey:firstMsgId];
  404. if (message.timestamp < firstModel.message.timestamp) {
  405. // 比数组中最老的消息时间都小的,无需加入界面显示,下次翻页时会加载
  406. return ;
  407. }
  408. model = [[JCHATChatModel alloc] init];
  409. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  410. if (message.contentType == kJMSGContentTypeImage) {
  411. [_imgDataArr addObject:model];
  412. }
  413. model.photoIndex = [_imgDataArr count] -1;
  414. [strongSelf addmessageShowTimeData:message.timestamp];
  415. [strongSelf addMessage:model];
  416. BOOL isHaveCache = NO;
  417. NSString *key = [NSString stringWithFormat:@"%@_%@",message.fromUser.username,message.fromUser.appKey];
  418. NSMutableArray *messages = _refreshAvatarUsersDic[key];
  419. if (messages) {
  420. isHaveCache = YES;
  421. [messages addObject:message];
  422. }else{
  423. messages = [NSMutableArray array];
  424. [messages addObject:message];
  425. }
  426. if (messages.count > 10) {
  427. [messages removeObjectAtIndex:0];
  428. }
  429. [_refreshAvatarUsersDic setObject:messages forKey:key];
  430. [strongSelf chcekReceiveMessageAvatarWithReceiveNewMessage:message];
  431. //if (!isHaveCache) {
  432. // [strongSelf performSelector:@selector(chcekReceiveMessageAvatarWithReceiveNewMessage:) withObject:message afterDelay:1.5];
  433. //}
  434. }
  435. }));
  436. }
  437. - (void)onReceiveMessageDownloadFailed:(JMSGMessage *)message {
  438. if (![self.conversation isMessageForThisConversation:message]) {
  439. return;
  440. }
  441. DDLogDebug(@"Event - receiveMessageNotification");
  442. JCHATMAINTHREAD((^{
  443. if (!message) {
  444. DDLogWarn(@"get the nil message .");
  445. return;
  446. }
  447. if (_conversation.conversationType == kJMSGConversationTypeSingle) {
  448. } else if (![((JMSGGroup *)_conversation.target).gid isEqualToString:((JMSGGroup *)message.target).gid]){
  449. return;
  450. }
  451. JCHATChatModel *model = [_allMessageDic objectForKey:message.msgId];
  452. if (model) {// 说明已经加载,说明可能是同步下来的多媒体消息,下载完成,然后再次收到就去刷新
  453. model.message = message;
  454. [self refreshCellMessageMediaWithChatModel:model];
  455. }else{
  456. model = [[JCHATChatModel alloc] init];
  457. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  458. if (message.contentType == kJMSGContentTypeImage) {
  459. [_imgDataArr addObject:model];
  460. }
  461. model.photoIndex = [_imgDataArr count] -1;
  462. [self addmessageShowTimeData:message.timestamp];
  463. [self addMessage:model];
  464. }
  465. }));
  466. }
  467. //同步离线消息
  468. - (void)onSyncOfflineMessageConversation:(JMSGConversation *)conversation
  469. offlineMessages:(NSArray<__kindof JMSGMessage *> *)offlineMessages {
  470. DDLogDebug(@"Action -- onSyncOfflineMessageConversation:offlineMessages:");
  471. if (conversation.conversationType != self.conversation.conversationType) {
  472. return ;
  473. }
  474. BOOL isThisConversation = NO;
  475. if (conversation.conversationType == kJMSGConversationTypeSingle) {
  476. JMSGUser *user1 = (JMSGUser *)conversation.target;
  477. JMSGUser *user2 = (JMSGUser *)self.conversation.target;
  478. if ([user1.username isEqualToString:user2.username] &&
  479. [user1.appKey isEqualToString:user2.appKey]) {
  480. isThisConversation = YES;
  481. }
  482. }else{
  483. JMSGGroup *group1 = (JMSGGroup *)conversation.target;
  484. JMSGGroup *group2 = (JMSGGroup *)conversation.target;
  485. if ([group1.gid isEqualToString:group2.gid]) {
  486. isThisConversation = YES;
  487. }
  488. }
  489. if (!isThisConversation) {
  490. return ;
  491. }
  492. NSMutableArray *pathsArray = [NSMutableArray array];
  493. NSMutableArray *allSyncMessages = [NSMutableArray arrayWithArray:offlineMessages];
  494. for (int i = 0; i< allSyncMessages.count; i++) {
  495. JMSGMessage *message = allSyncMessages[i];
  496. JCHATChatModel *model = [[JCHATChatModel alloc] init];
  497. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  498. if (message.contentType == kJMSGContentTypeImage) {
  499. [_imgDataArr addObject:model];
  500. }
  501. model.photoIndex = [_imgDataArr count] -1;
  502. [_allMessageDic setObject:model forKey:model.message.msgId];
  503. [_allmessageIdArr addObject:model.message.msgId];
  504. NSIndexPath *path = [NSIndexPath indexPathForRow:[_allmessageIdArr count]-1 inSection:0];
  505. [pathsArray addObject:path];
  506. }
  507. if (pathsArray.count) {
  508. [_messageTableView beginUpdates];
  509. [_messageTableView insertRowsAtIndexPaths:pathsArray withRowAnimation:UITableViewRowAnimationNone];
  510. [_messageTableView endUpdates];
  511. [self scrollToEnd];
  512. }
  513. }
  514. //同步漫游消息
  515. - (void)onSyncRoamingMessageConversation:(JMSGConversation *)conversation {
  516. DDLogDebug(@"Action -- onSyncRoamingMessageConversation:");
  517. if (conversation.conversationType != self.conversation.conversationType) {
  518. return ;
  519. }
  520. BOOL isThisConversation = NO;
  521. if (conversation.conversationType == kJMSGConversationTypeSingle) {
  522. JMSGUser *user1 = (JMSGUser *)conversation.target;
  523. JMSGUser *user2 = (JMSGUser *)self.conversation.target;
  524. if ([user1.username isEqualToString:user2.username] &&
  525. [user1.appKey isEqualToString:user2.appKey]) {
  526. isThisConversation = YES;
  527. }
  528. }
  529. if (!isThisConversation) {
  530. return ;
  531. }
  532. isNoOtherMessage = NO;
  533. messageOffset = 0;
  534. [_imgDataArr removeAllObjects];
  535. [_userArr removeAllObjects];
  536. [_allMessageDic removeAllObjects];
  537. [_allmessageIdArr removeAllObjects];
  538. [_imgDataArr removeAllObjects];
  539. [self getGroupMemberListWithGetMessageFlag:YES];
  540. }
  541. - (void)onGroupInfoChanged:(JMSGGroup *)group {
  542. // [self updateGroupConversationTittle:group];
  543. }
  544. - (void)relayoutTableCellWithMessage:(JMSGMessage *) message{
  545. DDLogDebug(@"relayoutTableCellWithMessage: msgid:%@",message.msgId);
  546. if ([message.msgId isEqualToString:@""]) {
  547. return;
  548. }
  549. JCHATChatModel *model = _allMessageDic[message.msgId];
  550. if (model) {
  551. model.message = message;
  552. [_allMessageDic setObject:model forKey:message.msgId];
  553. }
  554. NSInteger index = [_allmessageIdArr indexOfObject:message.msgId];
  555. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
  556. if (model.message.contentType == kJMSGContentTypeCustom) {
  557. JMSGMessage *latesMessage = model.message;
  558. JCHATShowTimeCell *cell = [_messageTableView cellForRowAtIndexPath:indexPath];
  559. JMSGAbstractContent *jmsContent =latesMessage.content;
  560. JMSGCustomContent *textContent = (JMSGCustomContent *)jmsContent;
  561. NSDictionary *lastDic = textContent.customDictionary;
  562. NSLog(@"22222222222=======:%@", lastDic);
  563. NSString *_lastMsgStr;
  564. if ([minstr([lastDic valueForKey:@"uid"]) isEqual:[Config getOwnID]]) {
  565. _lastMsgStr = YZMsg(@"你关注了对方,快跟Ta聊聊天吧~");
  566. }else{
  567. _lastMsgStr = YZMsg(@"对方已关注你,快跟Ta聊聊天吧~");
  568. }
  569. cell.messageTimeLabel.text =_lastMsgStr;
  570. }else{
  571. JCHATMessageTableViewCell *tableviewcell = [_messageTableView cellForRowAtIndexPath:indexPath];
  572. tableviewcell.model = model;
  573. [tableviewcell layoutAllView];
  574. }
  575. //[_messageTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
  576. }
  577. #pragma mark --获取对应消息的索引
  578. - (NSInteger )getIndexWithMessageId:(NSString *)messageID {
  579. for (NSInteger i=0; i< [_allmessageIdArr count]; i++) {
  580. NSString *getMessageID = _allmessageIdArr[i];
  581. if ([getMessageID isEqualToString:messageID]) {
  582. return i;
  583. }
  584. }
  585. return 0;
  586. }
  587. - (bool)checkDevice:(NSString *)name {
  588. NSString *deviceType = [UIDevice currentDevice].model;
  589. DDLogDebug(@"deviceType = %@", deviceType);
  590. NSRange range = [deviceType rangeOfString:name];
  591. return range.location != NSNotFound;
  592. }
  593. #pragma mark -- 清空消息缓存
  594. - (void)cleanMessageCache {
  595. [_allMessageDic removeAllObjects];
  596. [_allmessageIdArr removeAllObjects];
  597. [self.messageTableView reloadData];
  598. }
  599. #pragma mark --添加message
  600. - (void)addMessage:(JCHATChatModel *)model {
  601. if (model.isTime) {
  602. [_allMessageDic setObject:model forKey:model.timeId];
  603. [_allmessageIdArr addObject:model.timeId];
  604. [self addCellToTabel];
  605. return;
  606. }
  607. [_allMessageDic setObject:model forKey:model.message.msgId];
  608. [_allmessageIdArr addObject:model.message.msgId];
  609. [self addCellToTabel];
  610. }
  611. NSInteger sortMessageType(id object1,id object2,void *cha) {
  612. JMSGMessage *message1 = (JMSGMessage *)object1;
  613. JMSGMessage *message2 = (JMSGMessage *)object2;
  614. if([message1.timestamp integerValue] > [message2.timestamp integerValue]) {
  615. return NSOrderedDescending;
  616. } else if([message1.timestamp integerValue] < [message2.timestamp integerValue]) {
  617. return NSOrderedAscending;
  618. }
  619. return NSOrderedSame;
  620. }
  621. - (void)AlertToSendImage:(NSNotification *)notification {
  622. UIImage *img = notification.object;
  623. //[self prepareImageMessage:img];
  624. [self sendImage:img isMult:NO];
  625. }
  626. #pragma mark - 撤回
  627. -(void)userRetractMessage:(NSNotification *)notification {
  628. JMSGMessage *message = notification.object;
  629. NSLog(@"撤回===%@",message.msgId);
  630. [_conversation retractMessage:message completionHandler:^(id resultObject, NSError *error) {
  631. NSLog(@"===ch:%@-%@",resultObject,error);
  632. NSLog(@"撤回===2%@",resultObject);
  633. if (error != nil) {
  634. //[MBProgressHUD showPop:YZMsg(@"该消息发送时间已超过两分钟,无法撤回")];
  635. }else {
  636. [self retractMsgReplace:(JMSGMessage *)resultObject];
  637. }
  638. }];
  639. }
  640. - (void)deleteMessage:(NSNotification *)notification {
  641. JMSGMessage *message = notification.object;
  642. [_conversation deleteMessageWithMessageId:message.msgId];
  643. [_allMessageDic removeObjectForKey:message.msgId];
  644. [_allmessageIdArr removeObject:message.msgId];
  645. [_messageTableView loadMoreMessage];
  646. }
  647. #pragma mark - 排序conversation
  648. - (NSMutableArray *)sortMessage:(NSMutableArray *)messageArr {
  649. NSArray *sortResultArr = [messageArr sortedArrayUsingFunction:sortMessageType context:nil];
  650. return [NSMutableArray arrayWithArray:sortResultArr];
  651. }
  652. - (void)getPageMessage {
  653. DDLogDebug(@"Action - getAllMessage");
  654. [self cleanMessageCache];
  655. NSMutableArray * arrList = [[NSMutableArray alloc] init];
  656. [_allmessageIdArr addObject:[[NSObject alloc] init]];
  657. messageOffset = messagefristPageNumber;
  658. [arrList addObjectsFromArray:[[[_conversation messageArrayFromNewestWithOffset:@0 limit:@(messageOffset)] reverseObjectEnumerator] allObjects]];
  659. if ([arrList count] < messagefristPageNumber) {
  660. isNoOtherMessage = YES;
  661. [_allmessageIdArr removeObjectAtIndex:0];
  662. }
  663. for (NSInteger i=0; i< [arrList count]; i++) {
  664. JMSGMessage *message = [arrList objectAtIndex:i];
  665. JCHATChatModel *model = [[JCHATChatModel alloc] init];
  666. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  667. if (message.contentType == kJMSGContentTypeImage) {
  668. [_imgDataArr addObject:model];
  669. model.photoIndex = [_imgDataArr count] - 1;
  670. }
  671. [self dataMessageShowTime:message.timestamp];
  672. [_allMessageDic setObject:model forKey:model.message.msgId];
  673. [_allmessageIdArr addObject:model.message.msgId];
  674. }
  675. [_messageTableView reloadData];
  676. [self scrollToBottomAnimated:NO];
  677. }
  678. - (void)flashToLoadMessage {
  679. NSMutableArray * arrList = @[].mutableCopy;
  680. NSArray *newMessageArr = [_conversation messageArrayFromNewestWithOffset:@(messageOffset) limit:@(messagePageNumber)];
  681. [arrList addObjectsFromArray:newMessageArr];
  682. if ([arrList count] < messagePageNumber) {// 判断还有没有新数据
  683. isNoOtherMessage = YES;
  684. [_allmessageIdArr removeObjectAtIndex:0];
  685. }
  686. messageOffset += messagePageNumber;
  687. for (NSInteger i = 0; i < [arrList count]; i++) {
  688. JMSGMessage *message = arrList[i];
  689. JCHATChatModel *model = [[JCHATChatModel alloc] init];
  690. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  691. if (message.contentType == kJMSGContentTypeImage) {
  692. [_imgDataArr insertObject:model atIndex:0];
  693. model.photoIndex = [_imgDataArr count] - 1;
  694. }
  695. [_allMessageDic setObject:model forKey:model.message.msgId];
  696. [_allmessageIdArr insertObject:model.message.msgId atIndex: isNoOtherMessage?0:1];
  697. [self dataMessageShowTimeToTop:message.timestamp];// FIXME:
  698. }
  699. [_messageTableView loadMoreMessage];
  700. }
  701. - (JMSGUser *)getAvatarWithTargetId:(NSString *)targetId {
  702. for (NSInteger i=0; i<[_userArr count]; i++) {
  703. JMSGUser *user = [_userArr objectAtIndex:i];
  704. if ([user.username isEqualToString:targetId]) {
  705. return user;
  706. }
  707. }
  708. return nil;
  709. }
  710. - (XHVoiceRecordHelper *)voiceRecordHelper {
  711. if (!_voiceRecordHelper) {
  712. WEAKSELF
  713. _voiceRecordHelper = [[XHVoiceRecordHelper alloc] init];
  714. _voiceRecordHelper.maxTimeStopRecorderCompletion = ^{
  715. DDLogDebug(@"已经达到最大限制时间了,进入下一步的提示");
  716. __strong __typeof(weakSelf)strongSelf = weakSelf;
  717. [strongSelf finishRecorded];
  718. };
  719. _voiceRecordHelper.peakPowerForChannel = ^(float peakPowerForChannel) {
  720. __strong __typeof(weakSelf)strongSelf = weakSelf;
  721. strongSelf.voiceRecordHUD.peakPower = peakPowerForChannel;
  722. };
  723. _voiceRecordHelper.maxRecordTime = kVoiceRecorderTotalTime;
  724. }
  725. return _voiceRecordHelper;
  726. }
  727. - (XHVoiceRecordHUD *)voiceRecordHUD {
  728. if (!_voiceRecordHUD) {
  729. _voiceRecordHUD = [[XHVoiceRecordHUD alloc] initWithFrame:CGRectMake(0, 0, 140, 140)];
  730. }
  731. return _voiceRecordHUD;
  732. }
  733. - (void)backClick {
  734. if ([[JCHATAudioPlayerHelper shareInstance] isPlaying]) {
  735. [[JCHATAudioPlayerHelper shareInstance] stopAudio];
  736. }
  737. [self.navigationController popViewControllerAnimated:YES];
  738. }
  739. - (void)pressVoiceBtnToHideKeyBoard {///!!!
  740. [self.toolBarContainer.toolbar.textView resignFirstResponder];
  741. _toolBarHeightConstrait.constant = 45;
  742. [self dropToolBar];
  743. }
  744. - (void)switchToTextInputMode {
  745. UITextView *inputview = self.toolBarContainer.toolbar.textView;
  746. [inputview becomeFirstResponder];
  747. [self layoutAndAnimateMessageInputTextView:inputview];
  748. }
  749. #pragma mark -调用相册
  750. - (void)photoClick {
  751. _didSendCount = 0;
  752. _sendImgLimit = NO;
  753. TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
  754. imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
  755. imagePC.iconThemeColor = Pink_Cor;
  756. imagePC.naviBgColor = CellRow_Cor;
  757. imagePC.oKButtonTitleColorNormal = Pink_Cor;
  758. imagePC.oKButtonTitleColorDisabled = Pink_Cor_Dis;
  759. imagePC.allowTakePicture = NO;
  760. imagePC.allowTakeVideo = NO;
  761. imagePC.allowPickingVideo = NO;
  762. imagePC.showSelectedIndex = YES;
  763. imagePC.allowCrop = NO;
  764. imagePC.allowPickingOriginalPhoto = NO;
  765. imagePC.minImagesCount = 1;
  766. imagePC.maxImagesCount = 9;
  767. imagePC.modalPresentationStyle = 0;
  768. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  769. [self presentViewController:imagePC animated:YES completion:nil];
  770. });
  771. /*
  772. ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
  773. [lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
  774. JCHATPhotoPickerViewController *photoPickerVC = [[JCHATPhotoPickerViewController alloc] init];
  775. photoPickerVC.photoDelegate = self;
  776. [self presentViewController:photoPickerVC animated:YES completion:NULL];
  777. } failureBlock:^(NSError *error) {
  778. UIAlertController *alertC = [UIAlertController alertControllerWithTitle:YZMsg(@"没有相册权限") message:YZMsg(@"请到设置页面获取相册权限") preferredStyle:UIAlertControllerStyleAlert];
  779. UIAlertAction *cancelA = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleCancel handler:nil];
  780. [alertC addAction:cancelA];
  781. [self presentViewController:alertC animated:YES completion:nil];
  782. }];
  783. */
  784. }
  785. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
  786. NSMutableArray *imgArray = [NSMutableArray array];
  787. for (UIImage *img in photos) {
  788. UIImage *scaleImg = [PublicObj scaleImage:img scaleToSize:[PublicObj getObjSize:img.size]];
  789. [imgArray addObject:scaleImg];
  790. }
  791. _didSelImgA = [NSArray arrayWithArray:imgArray];
  792. [self goSendImg];
  793. [self dropToolBarNoAnimate];
  794. }
  795. -(void)goSendImg{
  796. if (_didSendCount < _didSelImgA.count && !_sendImgLimit) {
  797. [self sendImage:_didSelImgA[_didSendCount] isMult:YES];
  798. }
  799. }
  800. -(void)sendImage:(UIImage *)sendImg isMult:(BOOL)isMult{
  801. NSString *url = [NSString stringWithFormat:@"User.checkBlack&uid=%@&token=%@&touid=%@&content=",[Config getOwnID],[Config getOwnToken],_userModel.uidStr];
  802. [MBProgressHUD showMessage:@""];
  803. [YBNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
  804. [MBProgressHUD hideHUD];
  805. if (code == 0) {
  806. NSDictionary *infoDic = [info firstObject];
  807. NSString *isattent = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"isattent"]];
  808. NSString *t2u = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"t2u"]];
  809. NSString *sendConten = minstr([infoDic valueForKey:@"content"]);
  810. NSString *p_switch = [NSString stringWithFormat:@"%@",[common private_letter_switch]];
  811. int p_nums = [[NSString stringWithFormat:@"%@",[common private_letter_nums]] intValue];
  812. //我发送的条数
  813. NSMutableArray *frends_cont = [NSMutableArray array];
  814. for (int i = 0; i < _allmessageIdArr.count; i++) {
  815. NSString *msgid = [_allmessageIdArr objectAtIndex:i];
  816. JCHATChatModel *model = [_allMessageDic objectForKey:msgid];
  817. if ([model.uidStr isEqual:[Config getOwnID]]) {
  818. [frends_cont addObject:model];
  819. }
  820. }
  821. if ([t2u isEqual:@"0"]) {
  822. //已发送+将要发送的图片数量 不能大于最大消息数量
  823. if ([isattent isEqual:@"0"] && [p_switch isEqual:@"1"] && frends_cont.count >= p_nums) {
  824. [MBProgressHUD showPop:[NSString stringWithFormat:@"%@%d%@",YZMsg(@"对方未关注你,最多只能发送"),p_nums,YZMsg(@"条信息")]];
  825. if (isMult) {
  826. _sendImgLimit = YES;
  827. }
  828. }else {
  829. //可以发送
  830. [self prepareImageMessage:sendImg];
  831. if (isMult) {
  832. //继续下一张
  833. _didSendCount ++;
  834. [self goSendImg];
  835. }
  836. }
  837. }else {
  838. [MBProgressHUD showPop:YZMsg(@"对方暂时拒绝接收您的消息")];
  839. }
  840. }else {
  841. [MBProgressHUD showPop:msg];
  842. }
  843. } Fail:^(id fail) {
  844. [MBProgressHUD hideHUD];
  845. }];
  846. }
  847. #pragma mark -- 调用相机
  848. - (void)cameraClick {
  849. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  850. if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  851. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  852. NSString *requiredMediaType = ( NSString *)kUTTypeImage;
  853. NSArray *arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType,nil];
  854. [picker setMediaTypes:arrMediaTypes];
  855. picker.showsCameraControls = YES;
  856. picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  857. picker.editing = YES;
  858. picker.delegate = self;
  859. picker.modalPresentationStyle = 0;
  860. [self presentViewController:picker animated:YES completion:nil];
  861. }
  862. }
  863. #pragma mark - 语音输入
  864. -(void)voiceInputClick {
  865. NSLog(@"语音输入");
  866. YBWeakSelf;
  867. if (!_asrView) {
  868. _asrView = [[ASRView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, _window_height) callBack:^(NSString *type, NSString *content) {
  869. if ([type isEqual:@"返回"]) {
  870. NSLog(@"返回");
  871. [weakSelf asrBack];
  872. }else if ([type isEqual:@"发送"]){
  873. NSLog(@"发送");
  874. [weakSelf asrSend:content];
  875. }
  876. }];
  877. [self.view addSubview:_asrView];
  878. }
  879. [UIView animateWithDuration:0.25 animations:^{
  880. _asrView.frame = CGRectMake(0, 0, _window_width, _window_height);
  881. _moreViewHeight.constant = ASRHeight-_toolBarHeightConstrait.constant;
  882. [self scrollToEnd];
  883. }];
  884. }
  885. -(void)asrBack {
  886. [_asrView.textView resignFirstResponder];
  887. [UIView animateWithDuration:0.25 animations:^{
  888. _asrView.frame = CGRectMake(0, _window_height, _window_width, _window_height);
  889. _moreViewHeight.constant = kMoreHeight+ShowDiff;
  890. [self scrollToEnd];
  891. }];
  892. }
  893. -(void)asrSend:(NSString *)content {
  894. [self sendText:content];
  895. }
  896. #pragma mark - 位置信息
  897. -(void)locationClick {
  898. TencentLocationVC *locationVC = [[TencentLocationVC alloc]init];
  899. YBWeakSelf;
  900. locationVC.locationEvent = ^(NSDictionary *locDic) {
  901. [weakSelf prepareLocation:locDic];
  902. };
  903. [self.navigationController pushViewController:locationVC animated:YES];
  904. }
  905. -(void)prepareLocation:(NSDictionary *)dic{
  906. NSNumber *latitude = @([[NSString stringWithFormat:@"%@",[dic valueForKey:@"latitude"]] doubleValue]);
  907. NSNumber *longitude = @([[NSString stringWithFormat:@"%@",[dic valueForKey:@"longitude"]] doubleValue]);
  908. NSString *address = [dic valueForKey:@"address"];
  909. JMSGLocationContent *locationContent = [[JMSGLocationContent alloc]initWithLatitude:latitude longitude:longitude scale:@(1) address:address];
  910. [self checkBlack:locationContent voice:@"" textContent:@""];
  911. //JMSGMessage *message = nil;
  912. //message = [_conversation createMessageWithContent:locationContent];
  913. //[_conversation sendMessage:message];
  914. //[self addmessageShowTimeData:message.timestamp];
  915. //[model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  916. //[self addMessage:model];
  917. }
  918. #pragma mark - HMPhotoPickerViewController Delegate 发送图片
  919. - (void)JCHATPhotoPickerViewController:(JCHATPhotoSelectViewController *)PhotoPickerVC selectedPhotoArray:(NSArray *)selected_photo_array {
  920. NSString *url = [NSString stringWithFormat:@"User.checkBlack&uid=%@&token=%@&touid=%@&content=",[Config getOwnID],[Config getOwnToken],_userModel.uidStr];
  921. [MBProgressHUD showMessage:@""];
  922. [YBNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
  923. [MBProgressHUD hideHUD];
  924. if (code == 0) {
  925. NSDictionary *infoDic = [info firstObject];
  926. NSString *isattent = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"isattent"]];
  927. NSString *t2u = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"t2u"]];
  928. NSString *sendConten = minstr([infoDic valueForKey:@"content"]);
  929. NSString *p_switch = [NSString stringWithFormat:@"%@",[common private_letter_switch]];
  930. int p_nums = [[NSString stringWithFormat:@"%@",[common private_letter_nums]] intValue];
  931. //我发送的条数
  932. NSMutableArray *frends_cont = [NSMutableArray array];
  933. for (int i = 0; i < _allmessageIdArr.count; i++) {
  934. NSString *msgid = [_allmessageIdArr objectAtIndex:i];
  935. JCHATChatModel *model = [_allMessageDic objectForKey:msgid];
  936. if ([model.uidStr isEqual:[Config getOwnID]]) {
  937. [frends_cont addObject:model];
  938. }
  939. }
  940. if ([t2u isEqual:@"0"]) {
  941. //已发送+将要发送的图片数量 不能大于最大消息数量
  942. if ([isattent isEqual:@"0"] && [p_switch isEqual:@"1"] && (frends_cont.count+selected_photo_array.count) > p_nums) {
  943. [MBProgressHUD showPop:[NSString stringWithFormat:@"%@%d%@",YZMsg(@"对方未关注你,最多只能发送"),p_nums,YZMsg(@"条信息")]];
  944. }else {
  945. //可以发送
  946. for (UIImage *image in selected_photo_array) {
  947. [self prepareImageMessage:image];
  948. }
  949. }
  950. }else {
  951. [MBProgressHUD showPop:YZMsg(@"对方暂时拒绝接收您的消息")];
  952. }
  953. }else {
  954. [MBProgressHUD showPop:msg];
  955. }
  956. } Fail:^(id fail) {
  957. [MBProgressHUD hideHUD];
  958. }];
  959. [self dropToolBarNoAnimate];
  960. }
  961. #pragma mark - UIImagePickerController Delegate
  962. //相机,相册Finish的代理
  963. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  964. NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
  965. if ([mediaType isEqualToString:@"public.movie"]) {
  966. [self dismissViewControllerAnimated:YES completion:nil];
  967. [MBProgressHUD showMessage:YZMsg(@"不支持视频发送") toView:self.view];
  968. return;
  969. }
  970. UIImage *image;
  971. image = [info objectForKey:UIImagePickerControllerOriginalImage];
  972. // [self prepareImageMessage:image];
  973. [self sendImage:image isMult:NO];
  974. [self dropToolBarNoAnimate];
  975. [self dismissViewControllerAnimated:YES completion:nil];
  976. }
  977. #pragma mark -- 发送图片
  978. - (void)prepareImageMessage:(UIImage *)img {
  979. DDLogDebug(@"Action - prepareImageMessage");
  980. img = [img resizedImageByWidth:upLoadImgWidth];
  981. JMSGMessage* message = nil;
  982. JCHATChatModel *model = [[JCHATChatModel alloc] init];
  983. JMSGImageContent *imageContent = [[JMSGImageContent alloc] initWithImageData:UIImagePNGRepresentation(img)];
  984. if (imageContent) {
  985. message = [_conversation createMessageWithContent:imageContent];
  986. [[JCHATSendMsgManager ins] addMessage:message withConversation:_conversation];
  987. [self addmessageShowTimeData:message.timestamp];
  988. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  989. [_imgDataArr addObject:model];
  990. model.photoIndex = [_imgDataArr count] - 1;
  991. [model setupImageSize];
  992. [self addMessage:model];
  993. }
  994. }
  995. #pragma mark --
  996. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
  997. {
  998. [picker dismissViewControllerAnimated:YES completion:nil];
  999. }
  1000. #pragma mark --add Delegate
  1001. - (void)addDelegate {
  1002. [JMessage addDelegate:self withConversation:self.conversation];
  1003. }
  1004. #pragma mark --加载通知
  1005. - (void)addNotification{
  1006. //给键盘注册通知
  1007. NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
  1008. [notiCenter addObserver:self selector:@selector(inputKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  1009. [notiCenter addObserver:self selector:@selector(inputKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  1010. [notiCenter addObserver:self selector:@selector(cleanMessageCache) name:kDeleteAllMessage object:nil];
  1011. [notiCenter addObserver:self selector:@selector(AlertToSendImage:) name:kAlertToSendImage object:nil];
  1012. [notiCenter addObserver:self selector:@selector(userRetractMessage:) name:kRetractMsg object:nil];
  1013. [notiCenter addObserver:self selector:@selector(deleteMessage:) name:kDeleteMessage object:nil];
  1014. [self.toolBarContainer.toolbar.textView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
  1015. self.toolBarContainer.toolbar.textView.delegate = self;
  1016. }
  1017. #pragma mark --发送文本
  1018. - (void)sendText:(NSString *)text {
  1019. [self prepareTextMessage:text];
  1020. }
  1021. - (void)perform {
  1022. _moreViewHeight.constant = 0;
  1023. _toolBarToBottomConstrait.constant = 0+ShowDiff;
  1024. }
  1025. #pragma mark --返回下面的位置
  1026. - (void)dropToolBar {
  1027. if (self.naviView.hidden) {
  1028. [UIView animateWithDuration:0.25 animations:^{//0.3
  1029. self.view.frame = CGRectMake(0, _window_height - _window_height*0.4, _window_width, _window_height*0.4);
  1030. _emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight);
  1031. _toolBarContainer.toolbar.faceBtn.selected = NO;
  1032. }];
  1033. return;
  1034. }
  1035. _barBottomFlag =YES;
  1036. _previousTextViewContentHeight = 36;
  1037. _toolBarContainer.toolbar.addButton.selected = NO;
  1038. _toolBarContainer.toolbar.faceBtn.selected = NO;
  1039. // [_messageTableView reloadData];
  1040. [UIView animateWithDuration:0.25 animations:^{//0.3
  1041. _toolBarToBottomConstrait.constant = 0+ShowDiff;
  1042. _emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
  1043. _moreViewHeight.constant = 0;
  1044. }];
  1045. }
  1046. - (void)dropToolBarNoAnimate {
  1047. _barBottomFlag =YES;
  1048. _previousTextViewContentHeight = 36;
  1049. _toolBarContainer.toolbar.addButton.selected = NO;
  1050. _toolBarContainer.toolbar.faceBtn.selected = NO;
  1051. //[_messageTableView reloadData];
  1052. _toolBarToBottomConstrait.constant = 0+ShowDiff;
  1053. _emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
  1054. _moreViewHeight.constant = 0;
  1055. }
  1056. #pragma mark - 键盘
  1057. - (void)inputKeyboardWillShow:(NSNotification *)notification{
  1058. //获取键盘的高
  1059. NSDictionary *userInfo = [notification userInfo];
  1060. NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
  1061. CGRect keyboardRect = [aValue CGRectValue];
  1062. CGFloat height = keyboardRect.origin.y;
  1063. CGFloat newHeight = _window_height - height;
  1064. if (self.naviView.hidden) {
  1065. [UIView animateWithDuration:0.25 animations:^{//0.3
  1066. _toolBarToBottomConstrait.constant = 0;
  1067. self.view.frame = CGRectMake(0,_window_height*0.2, _window_width, _window_height*0.8 - newHeight);
  1068. _toolBarContainer.toolbar.faceBtn.selected = NO;
  1069. }];
  1070. return;
  1071. }
  1072. _toolBarContainer.toolbar.addButton.selected = NO;
  1073. _toolBarContainer.toolbar.faceBtn.selected = NO;
  1074. _barBottomFlag=NO;
  1075. CGRect keyBoardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  1076. CGFloat animationTime = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1077. if (_asrView.textView.isFirstResponder == YES) {
  1078. [UIView animateWithDuration:0.25 animations:^{
  1079. _asrMoveUp = YES;
  1080. _asrView.frame = CGRectMake(0, -keyBoardFrame.size.height, _window_width, _window_height);
  1081. _moreViewHeight.constant = keyBoardFrame.size.height-_toolBarHeightConstrait.constant;
  1082. }];
  1083. }else{
  1084. [UIView animateWithDuration:animationTime animations:^{
  1085. _moreViewHeight.constant = keyBoardFrame.size.height;
  1086. _toolBarToBottomConstrait.constant = 0;
  1087. [self.view layoutIfNeeded];
  1088. }];
  1089. }
  1090. [self scrollToEnd];//!
  1091. }
  1092. - (void)inputKeyboardWillHide:(NSNotification *)notification {
  1093. CGFloat animationTime = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  1094. kWEAKSELF
  1095. if (_asrMoveUp == YES) {
  1096. [UIView animateWithDuration:0.25 animations:^{
  1097. _asrMoveUp = NO;
  1098. _asrView.frame = CGRectMake(0, 0, _window_width, _window_height);
  1099. _moreViewHeight.constant = ASRHeight-_toolBarHeightConstrait.constant;
  1100. }];
  1101. }else{
  1102. [UIView animateWithDuration:animationTime animations:^{
  1103. _moreViewHeight.constant = 0;
  1104. _toolBarToBottomConstrait.constant = 0+ShowDiff;
  1105. [weakSelf.view layoutIfNeeded];
  1106. }];
  1107. }
  1108. if (self.naviView.hidden) {
  1109. [UIView animateWithDuration:0.25 animations:^{//0.1
  1110. self.view.frame = CGRectMake(0, _window_height - _window_height*0.4, _window_width, _window_height*0.4);
  1111. }];
  1112. }
  1113. [self scrollToBottomAnimated:NO];
  1114. [self dropToolBar];
  1115. }
  1116. #pragma mark -- 更多
  1117. - (void)pressMoreBtnClick:(UIButton *)btn {
  1118. _barBottomFlag=NO;
  1119. [_toolBarContainer.toolbar.textView resignFirstResponder];
  1120. [UIView animateWithDuration:0.25 animations:^{//0.3
  1121. _toolBarToBottomConstrait.constant = 0;
  1122. _emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight+ShowDiff);
  1123. _moreViewHeight.constant = kMoreHeight+ShowDiff;
  1124. [_messageTableView layoutIfNeeded];
  1125. [_toolBarContainer layoutIfNeeded];
  1126. [_moreViewContainer layoutIfNeeded];
  1127. }];
  1128. [_toolBarContainer.toolbar switchToolbarToTextMode];
  1129. }
  1130. - (void)noPressmoreBtnClick:(UIButton *)btn {
  1131. [self dropToolBar];
  1132. //_emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight);
  1133. [_toolBarContainer.toolbar.textView becomeFirstResponder];
  1134. }
  1135. #pragma mark - 表情弹起、落下
  1136. -(void)pressFaceBtnClick:(UIButton *)btn {
  1137. [_toolBarContainer.toolbar.textView resignFirstResponder];
  1138. if (self.naviView.hidden) {
  1139. [UIView animateWithDuration:0.25 animations:^{//0.3
  1140. self.view.frame = CGRectMake(0,_window_height*0.2, _window_width, _window_height*0.8 - EmojiHeight);
  1141. _emojiV.frame = CGRectMake(0, _window_height-EmojiHeight, _window_width, EmojiHeight);
  1142. }];
  1143. return ;
  1144. }
  1145. _barBottomFlag=NO;
  1146. [_toolBarContainer.toolbar.textView resignFirstResponder];
  1147. [UIView animateWithDuration:0.25 animations:^{//0.3
  1148. _toolBarToBottomConstrait.constant = EmojiHeight+ShowDiff;
  1149. _moreViewHeight.constant = 0;
  1150. _emojiV.frame = CGRectMake(0, _window_height-EmojiHeight-ShowDiff, _window_width, EmojiHeight+ShowDiff);
  1151. [_messageTableView layoutIfNeeded];
  1152. [_toolBarContainer layoutIfNeeded];
  1153. [_moreViewContainer layoutIfNeeded];
  1154. }];
  1155. [_toolBarContainer.toolbar switchToolbarToTextMode];
  1156. }
  1157. -(void)noPressFaceBtnClick:(UIButton *)btn {
  1158. //_toolBarToBottomConstrait.constant = 0;
  1159. //[_toolBarContainer layoutIfNeeded];
  1160. //_emojiV.frame = CGRectMake(0, _window_height, _window_width, EmojiHeight);
  1161. [self dropToolBar];
  1162. [_toolBarContainer.toolbar.textView becomeFirstResponder];
  1163. }
  1164. #pragma mark - Emoji 代理
  1165. -(void)sendimage:(NSString *)str {
  1166. if ([str isEqual:@"msg_del"]) {
  1167. [_toolBarContainer.toolbar.textView deleteBackward];
  1168. }else {
  1169. [_toolBarContainer.toolbar.textView insertText:str];
  1170. }
  1171. }
  1172. -(void)clickSendEmojiBtn {
  1173. [self prepareTextMessage:_toolBarContainer.toolbar.textView.text];
  1174. _toolBarContainer.toolbar.textView.text = @"";
  1175. }
  1176. #pragma mark ----发送文本消息
  1177. - (void)prepareTextMessage:(NSString *)text {
  1178. [[JCHATSendMsgManager ins] updateConversation:_conversation withDraft:@""];
  1179. NSString *allText = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
  1180. if (allText.length<1) {
  1181. [MBProgressHUD showPop:YZMsg(@"消息不能为空")];
  1182. return;;
  1183. }
  1184. JMSGTextContent *textContent = [[JMSGTextContent alloc] initWithText:text];
  1185. [self checkBlack:textContent voice:@"" textContent:text];
  1186. //JMSGMessage *message = nil;
  1187. //message = [_conversation createMessageWithContent:textContent];//!
  1188. //[_conversation sendMessage:message];
  1189. //[self addmessageShowTimeData:message.timestamp];
  1190. //[model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  1191. //[self addMessage:model];
  1192. }
  1193. #pragma mark -- 刷新对应的
  1194. - (void)addCellToTabel {
  1195. NSIndexPath *path = [NSIndexPath indexPathForRow:[_allmessageIdArr count]-1 inSection:0];
  1196. [_messageTableView beginUpdates];
  1197. [_messageTableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
  1198. [_messageTableView endUpdates];
  1199. [self scrollToEnd];
  1200. }
  1201. #pragma mark ---比较和上一条消息时间超过5分钟之内增加时间model
  1202. - (void)addmessageShowTimeData:(NSNumber *)timeNumber{
  1203. NSString *messageId = [_allmessageIdArr lastObject];
  1204. JCHATChatModel *lastModel = _allMessageDic[messageId];
  1205. NSTimeInterval timeInterVal = [timeNumber longLongValue];
  1206. if ([_allmessageIdArr count] > 0 && lastModel.isTime == NO) {
  1207. NSDate* lastdate = [NSDate dateWithTimeIntervalSince1970:[lastModel.messageTime longLongValue]/1000];
  1208. NSDate* currentDate = [NSDate dateWithTimeIntervalSince1970:timeInterVal/1000];
  1209. NSTimeInterval timeBetween = [currentDate timeIntervalSinceDate:lastdate];
  1210. if (fabs(timeBetween) > interval) {
  1211. [self addTimeData:timeInterVal];
  1212. }
  1213. } else if ([_allmessageIdArr count] == 0) {//首条消息显示时间
  1214. [self addTimeData:timeInterVal];
  1215. } else {
  1216. DDLogDebug(@"不用显示时间");
  1217. }
  1218. }
  1219. #pragma mark ---比较和上一条消息时间超过5分钟之内增加时间model
  1220. - (void)dataMessageShowTime:(NSNumber *)timeNumber{
  1221. NSString *messageId = [_allmessageIdArr lastObject];
  1222. JCHATChatModel *lastModel = _allMessageDic[messageId];
  1223. NSTimeInterval timeInterVal = [timeNumber longLongValue];
  1224. if ([_allmessageIdArr count]>0 && lastModel.isTime == NO) {
  1225. NSDate* lastdate = [NSDate dateWithTimeIntervalSince1970:[lastModel.messageTime longLongValue]/1000];
  1226. NSDate* currentDate = [NSDate dateWithTimeIntervalSince1970:timeInterVal/1000];
  1227. NSTimeInterval timeBetween = [currentDate timeIntervalSinceDate:lastdate];
  1228. if (fabs(timeBetween) > interval) {
  1229. JCHATChatModel *timeModel =[[JCHATChatModel alloc] init];
  1230. timeModel.timeId = [self getTimeId];
  1231. timeModel.isTime = YES;
  1232. timeModel.messageTime = @(timeInterVal);
  1233. timeModel.contentHeight = [timeModel getTextHeight];//!
  1234. [_allMessageDic setObject:timeModel forKey:timeModel.timeId];
  1235. [_allmessageIdArr addObject:timeModel.timeId];
  1236. }
  1237. } else if ([_allmessageIdArr count] ==0) {//首条消息显示时间
  1238. JCHATChatModel *timeModel =[[JCHATChatModel alloc] init];
  1239. timeModel.timeId = [self getTimeId];
  1240. timeModel.isTime = YES;
  1241. timeModel.messageTime = @(timeInterVal);
  1242. timeModel.contentHeight = [timeModel getTextHeight];//!
  1243. [_allMessageDic setObject:timeModel forKey:timeModel.timeId];
  1244. [_allmessageIdArr addObject:timeModel.timeId];
  1245. } else {
  1246. DDLogDebug(@"不用显示时间");
  1247. }
  1248. }
  1249. - (void)dataMessageShowTimeToTop:(NSNumber *)timeNumber{
  1250. NSString *messageId = [_allmessageIdArr lastObject];
  1251. JCHATChatModel *lastModel = _allMessageDic[messageId];
  1252. NSTimeInterval timeInterVal = [timeNumber longLongValue];
  1253. if ([_allmessageIdArr count]>0 && lastModel.isTime == NO) {
  1254. NSDate* lastdate = [NSDate dateWithTimeIntervalSince1970:[lastModel.messageTime doubleValue]];
  1255. NSDate* currentDate = [NSDate dateWithTimeIntervalSince1970:timeInterVal];
  1256. NSTimeInterval timeBetween = [currentDate timeIntervalSinceDate:lastdate];
  1257. if (fabs(timeBetween) > interval) {
  1258. JCHATChatModel *timeModel =[[JCHATChatModel alloc] init];
  1259. timeModel.timeId = [self getTimeId];
  1260. timeModel.isTime = YES;
  1261. timeModel.messageTime = @(timeInterVal);
  1262. timeModel.contentHeight = [timeModel getTextHeight];
  1263. [_allMessageDic setObject:timeModel forKey:timeModel.timeId];
  1264. [_allmessageIdArr insertObject:timeModel.timeId atIndex: isNoOtherMessage?0:1];
  1265. }
  1266. } else if ([_allmessageIdArr count] ==0) {//首条消息显示时间
  1267. JCHATChatModel *timeModel =[[JCHATChatModel alloc] init];
  1268. timeModel.timeId = [self getTimeId];
  1269. timeModel.isTime = YES;
  1270. timeModel.messageTime = @(timeInterVal);
  1271. timeModel.contentHeight = [timeModel getTextHeight];
  1272. [_allMessageDic setObject:timeModel forKey:timeModel.timeId];
  1273. [_allmessageIdArr insertObject:timeModel.timeId atIndex: isNoOtherMessage?0:1];
  1274. } else {
  1275. DDLogDebug(@"不用显示时间");
  1276. }
  1277. }
  1278. - (void)addTimeData:(NSTimeInterval)timeInterVal {
  1279. JCHATChatModel *timeModel =[[JCHATChatModel alloc] init];
  1280. timeModel.timeId = [self getTimeId];
  1281. timeModel.isTime = YES;
  1282. timeModel.messageTime = @(timeInterVal);
  1283. timeModel.contentHeight = [timeModel getTextHeight];//!
  1284. [self addMessage:timeModel];
  1285. }
  1286. - (NSString *)getTimeId {
  1287. NSString *timeId = [NSString stringWithFormat:@"%d",arc4random()%1000000];
  1288. return timeId;
  1289. }
  1290. #pragma mark - 屏幕触摸事件
  1291. //代理
  1292. -(void)msgTableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  1293. if (_barBottomFlag==NO) {
  1294. if (_asrView.isFirstResponder == YES) {
  1295. [UIView animateWithDuration:0.25 animations:^{
  1296. _asrView.frame = CGRectMake(0, 0, _window_width, _window_height);
  1297. _moreViewHeight.constant = ASRHeight-_toolBarHeightConstrait.constant;
  1298. }];
  1299. }
  1300. UITouch *touch = [[event allTouches] anyObject];
  1301. CGPoint _touchPoint = [touch locationInView:self.view];
  1302. if (YES == CGRectContainsPoint(_messageTableView.frame, _touchPoint)){
  1303. [self.toolBarContainer.toolbar.textView resignFirstResponder];
  1304. [self dropToolBar];
  1305. }
  1306. }
  1307. }
  1308. - (void)tapClick:(UIGestureRecognizer *)gesture {
  1309. [self.toolBarContainer.toolbar.textView resignFirstResponder];
  1310. [self dropToolBar];
  1311. }
  1312. #pragma mark --滑动至尾端
  1313. - (void)scrollToEnd {
  1314. if ([_allmessageIdArr count] != 0) {
  1315. [self.messageTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_allmessageIdArr count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
  1316. }
  1317. }
  1318. #pragma mark - tableView datasoce
  1319. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  1320. if (!isNoOtherMessage) {
  1321. if (indexPath.row == 0) { //这个是第 0 行 用于刷新
  1322. return 40;
  1323. }
  1324. }
  1325. if (indexPath.row >= _allmessageIdArr.count) {
  1326. DDLogDebug(@"1.index %ld beyond bounds %ld",indexPath.row,_allmessageIdArr.count);
  1327. return 40;
  1328. }
  1329. NSString *messageId = _allmessageIdArr[indexPath.row];
  1330. JCHATChatModel *model = _allMessageDic[messageId];
  1331. if (model.isTime == YES) {
  1332. return 31;
  1333. }
  1334. if (model.message.contentType == kJMSGContentTypeEventNotification) {
  1335. return model.contentHeight + 17;
  1336. }
  1337. if (model.message.contentType == kJMSGContentTypeText) {
  1338. if (model.message.content.extras && [[model.message.content.extras allKeys]containsObject:@"goodsid"]) {
  1339. return _window_width*0.6 + 10;
  1340. }else{
  1341. return model.contentHeight + 17;
  1342. }
  1343. } else if (model.message.contentType == kJMSGContentTypeImage ||
  1344. model.message.contentType == kJMSGContentTypeFile ||
  1345. model.message.contentType == kJMSGContentTypeLocation) {
  1346. if (model.imageSize.height == 0) {
  1347. [model setupImageSize];
  1348. }
  1349. return model.imageSize.height < 44?59:model.imageSize.height + 14;
  1350. } else if (model.message.contentType == kJMSGContentTypeVoice) {
  1351. return 69;
  1352. } else {
  1353. return 49;
  1354. }
  1355. }
  1356. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  1357. return 1;
  1358. }
  1359. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  1360. return [_allmessageIdArr count];
  1361. }
  1362. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  1363. if (!isNoOtherMessage) {
  1364. if (indexPath.row == 0) {
  1365. static NSString *cellLoadIdentifier = @"loadCell"; //name
  1366. JCHATLoadMessageTableViewCell *cell = (JCHATLoadMessageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellLoadIdentifier];
  1367. if (cell == nil) {
  1368. cell = [[JCHATLoadMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellLoadIdentifier];
  1369. }
  1370. [cell startLoading];
  1371. [self flashToLoadMessage];
  1372. // [self performSelector:@selector(flashToLoadMessage) withObject:nil afterDelay:0];
  1373. return cell;
  1374. }
  1375. }
  1376. if (indexPath.row >= _allmessageIdArr.count) {
  1377. DDLogDebug(@"2.index %ld beyond bounds %ld",indexPath.row,_allmessageIdArr.count);
  1378. return nil;
  1379. }
  1380. NSString *messageId = _allmessageIdArr[indexPath.row];
  1381. if (!messageId) {
  1382. DDLogDebug(@"messageId is nil%@",messageId);
  1383. return nil;
  1384. }
  1385. JCHATChatModel *model = _allMessageDic[messageId];
  1386. if (!model) {
  1387. DDLogDebug(@"JCHATChatModel is nil%@", messageId);
  1388. return nil;
  1389. }
  1390. if (model.isTime == YES || model.message.contentType == kJMSGContentTypeEventNotification || model.isErrorMessage
  1391. || model.message.contentType == kJMSGContentTypePrompt) {
  1392. //消息时间
  1393. static NSString *cellIdentifier = @"timeCell";
  1394. JCHATShowTimeCell *cell = (JCHATShowTimeCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  1395. if (cell == nil) {
  1396. cell = [[[NSBundle mainBundle] loadNibNamed:@"JCHATShowTimeCell" owner:nil options:nil] lastObject];
  1397. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  1398. }
  1399. if (model.isErrorMessage) {
  1400. cell.messageTimeLabel.text = [NSString stringWithFormat:@"%@ %@:%ld",st_receiveErrorMessageDes,YZMsg(@"错误码"),model.messageError.code];
  1401. return cell;
  1402. }
  1403. if (model.message.contentType == kJMSGContentTypeEventNotification) {
  1404. cell.messageTimeLabel.text = [((JMSGEventContent *)model.message.content) showEventNotification];
  1405. }else if (model.message.contentType == kJMSGContentTypePrompt) {
  1406. NSString *alertMsg = YZMsg(@"你撤回了一条消息");
  1407. if (model.message.isReceived) {
  1408. alertMsg = YZMsg(@"对方撤回了一条消息");
  1409. }
  1410. cell.messageTimeLabel.text = alertMsg;
  1411. }else {
  1412. cell.messageTimeLabel.text = [JCHATStringUtils getFriendlyDateString:[model.messageTime longLongValue]];
  1413. }
  1414. return cell;
  1415. } else {
  1416. if (model.message.contentType == kJMSGContentTypeCustom) {
  1417. JMSGMessage *latesMessage = model.message;
  1418. static NSString *cellIdentifier = @"timeCell";
  1419. JCHATShowTimeCell *cell = (JCHATShowTimeCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  1420. if (cell == nil) {
  1421. cell = [[[NSBundle mainBundle] loadNibNamed:@"JCHATShowTimeCell" owner:nil options:nil] lastObject];
  1422. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  1423. }
  1424. JMSGAbstractContent *jmsContent =latesMessage.content;
  1425. JMSGCustomContent *textContent = (JMSGCustomContent *)jmsContent;
  1426. NSDictionary *lastDic = textContent.customDictionary;
  1427. NSLog(@"22222222222=======:%@", lastDic);
  1428. NSString *_lastMsgStr;
  1429. if ([minstr([lastDic valueForKey:@"uid"]) isEqual:[Config getOwnID]]) {
  1430. _lastMsgStr = YZMsg(@"你关注了对方,快跟Ta聊聊天吧~");
  1431. }else{
  1432. _lastMsgStr = YZMsg(@"对方已关注你,快跟Ta聊聊天吧~");
  1433. }
  1434. cell.messageTimeLabel.text =_lastMsgStr;
  1435. return cell;
  1436. }
  1437. //消息内容
  1438. static NSString *cellIdentifier = @"MessageCell";
  1439. JCHATMessageTableViewCell *cell = (JCHATMessageTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  1440. if (cell == nil) {
  1441. cell = [[JCHATMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  1442. cell.conversation = _conversation;
  1443. }
  1444. [cell setCellData:model delegate:self indexPath:indexPath];
  1445. kWEAKSELF
  1446. cell.messageTableViewCellRefreshMediaMessage = ^(JCHATChatModel *cellModel,BOOL isShouldRefresh){
  1447. if (isShouldRefresh) {
  1448. [weakSelf refreshCellMessageMediaWithChatModel:cellModel];
  1449. }
  1450. };
  1451. //rk20201030
  1452. cell.passRKTextView = self.toolBarContainer.toolbar.textView;
  1453. return cell;
  1454. }
  1455. }
  1456. #pragma mark - 检查并刷新消息图片图片
  1457. - (void)refreshCellMessageMediaWithChatModel:(JCHATChatModel *)model {
  1458. DDLogDebug(@"Action - refreshCellMessageMediaWithChatModel:");
  1459. if (!model) {
  1460. return ;
  1461. }
  1462. if (!model.message || ![self.conversation isMessageForThisConversation:model.message]) {
  1463. return ;
  1464. }
  1465. NSString *msgId = model.message.msgId;
  1466. JMSGMessage *db_message = [self.conversation messageWithMessageId:msgId];
  1467. if (!db_message || !db_message.msgId) {
  1468. return ;
  1469. }
  1470. model.message = db_message;
  1471. [_allMessageDic setObject:model forKey:model.message.msgId];
  1472. //[_allmessageIdArr addObject:model.message.msgId];msgId 不会变化所以不用去修改
  1473. // 1.method
  1474. //[self.messageTableView reloadData];
  1475. // 2.method
  1476. //NSArray *cellArray = [_messageTableView visibleCells];
  1477. //for (id temp in cellArray) {
  1478. // if ([temp isKindOfClass:[JCHATMessageTableViewCell class]]) {
  1479. // JCHATMessageTableViewCell *cell = (JCHATMessageTableViewCell *)temp;
  1480. // if ([cell.model.message.msgId isEqualToString:msgId]) {
  1481. // cell.model = model;
  1482. // [cell layoutAllView];
  1483. // }
  1484. // }
  1485. //}
  1486. // 3.在cell 里面刷新
  1487. }
  1488. #pragma mark - 检查并刷新头像
  1489. - (void)chcekReceiveMessageAvatarWithReceiveNewMessage:(JMSGMessage *)message {
  1490. DDLogDebug(@"chcekReceiveMessageAvatarWithReceiveNewMessage:%@",message.serverMessageId);
  1491. if (!message || !message.fromUser) {
  1492. return ;
  1493. }
  1494. JMSGMessage *lastMessage = message;
  1495. JMSGUser *fromUser = lastMessage.fromUser;
  1496. [fromUser thumbAvatarData:^(NSData *data, NSString *objectId, NSError *error) {
  1497. if (error == nil && [objectId isEqualToString:fromUser.username]) {
  1498. if (data != nil) {
  1499. NSUInteger lenght = data.length;
  1500. [self refreshVisibleRowsAvatarWithNewMessage:lastMessage avatarDataLength:lenght];
  1501. }
  1502. }
  1503. }];
  1504. //NSString *key = [NSString stringWithFormat:@"%@_%@",message.fromUser.username,message.fromUser.appKey];
  1505. //NSMutableArray *messages = _refreshAvatarUsersDic[key];
  1506. //if (messages.count > 0) {
  1507. // JMSGMessage *lastMessage = [messages lastObject];
  1508. // JMSGUser *fromUser = lastMessage.fromUser;
  1509. // [fromUser thumbAvatarData:^(NSData *data, NSString *objectId, NSError *error) {
  1510. // if (error == nil && [objectId isEqualToString:fromUser.username]) {
  1511. // if (data != nil) {
  1512. // NSUInteger lenght = data.length;
  1513. // [self refreshVisibleRowsAvatarWithNewMessage:lastMessage avatarDataLength:lenght];
  1514. // }
  1515. // }
  1516. // [_refreshAvatarUsersDic removeObjectForKey:key];
  1517. // }];
  1518. //}
  1519. }
  1520. - (void)refreshVisibleRowsAvatarWithNewMessage:(JMSGMessage *)message avatarDataLength:(NSUInteger)length {
  1521. DDLogDebug(@"refreshVisibleRowsAvatarWithNewMessage::%@",message.serverMessageId);
  1522. NSString *username_appkey = [NSString stringWithFormat:@"%@_%@",message.fromUser.username,message.fromUser.appKey];
  1523. NSString *msgId = message.msgId;
  1524. NSArray *indexPaths = [[_messageTableView indexPathsForVisibleRows] mutableCopy];
  1525. NSMutableArray *reloadIndexPaths = [NSMutableArray array];
  1526. for (int i = 0; i < indexPaths.count; i++) {
  1527. NSIndexPath *indexPath = indexPaths[i];
  1528. JCHATMessageTableViewCell *cell = [_messageTableView cellForRowAtIndexPath:indexPath];
  1529. JCHATChatModel *cellModel = cell.model;
  1530. JMSGUser *cellUser = cell.model.message.fromUser;
  1531. NSString *key = [NSString stringWithFormat:@"%@_%@",cellUser.username,cellUser.appKey];
  1532. if (![username_appkey isEqualToString:key]) {
  1533. continue ;
  1534. }
  1535. if (cellModel.avatarDataLength != length) {
  1536. JMSGMessage *dbMessage = [self.conversation messageWithMessageId:msgId];
  1537. JCHATChatModel *model = [_allMessageDic objectForKey:msgId];
  1538. model.message = dbMessage;
  1539. [_allMessageDic setObject:model forKey:msgId];
  1540. [reloadIndexPaths addObject:indexPath];
  1541. }
  1542. }
  1543. if (reloadIndexPaths.count > 0) {
  1544. [_messageTableView reloadRowsAtIndexPaths:reloadIndexPaths withRowAnimation:UITableViewRowAnimationFade];
  1545. }
  1546. }
  1547. - (void)reloadAllCellAvatarImage {
  1548. DDLogDebug(@"Action -reloadAllCellAvatarImage");
  1549. for (int i = 0; i < _allmessageIdArr.count; i++) {
  1550. NSString *msgid = [_allmessageIdArr objectAtIndex:i];
  1551. JCHATChatModel *model = [_allMessageDic objectForKey:msgid];
  1552. if (model.message.isReceived && !model.message.fromUser.avatar) {
  1553. JMSGMessage *message = [self.conversation messageWithMessageId:msgid];
  1554. model.message = message;
  1555. [_allMessageDic setObject:model forKey:msgid];
  1556. }
  1557. }
  1558. NSArray *cellArray = [_messageTableView visibleCells];
  1559. for (id temp in cellArray) {
  1560. if ([temp isKindOfClass:[JCHATMessageTableViewCell class]]) {
  1561. JCHATMessageTableViewCell *cell = (JCHATMessageTableViewCell *)temp;
  1562. if (cell.model.message.isReceived) {
  1563. [cell reloadAvatarImage];
  1564. }
  1565. }
  1566. }
  1567. }
  1568. #pragma mark -PlayVoiceDelegate
  1569. - (void)successionalPlayVoice:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
  1570. if ([_allmessageIdArr count] - 1 > indexPath.row) {
  1571. NSString *messageId = _allmessageIdArr[indexPath.row + 1];
  1572. JCHATChatModel *model = _allMessageDic[ messageId];
  1573. if (model.message.contentType == kJMSGContentTypeVoice && model.message.flag) {
  1574. JCHATMessageTableViewCell *voiceCell =(JCHATMessageTableViewCell *)[self.messageTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]];
  1575. [voiceCell playVoice];
  1576. }
  1577. }
  1578. }
  1579. - (void)setMessageIDWithMessage:(JMSGMessage *)message chatModel:(JCHATChatModel * __strong *)chatModel index:(NSInteger)index {
  1580. [_allMessageDic removeObjectForKey:(*chatModel).message.msgId];
  1581. [_allMessageDic setObject:*chatModel forKey:message.msgId];
  1582. if ([_allmessageIdArr count] > index) {
  1583. [_allmessageIdArr removeObjectAtIndex:index];
  1584. [_allmessageIdArr insertObject:message.msgId atIndex:index];
  1585. }
  1586. }
  1587. #pragma mark - 头像点击事件代理
  1588. - (void)selectHeadView:(JCHATChatModel *)model {
  1589. if (_isWhiteStyle) {
  1590. return;
  1591. }
  1592. if (!model.message.fromUser) {
  1593. [MBProgressHUD showMessage:@"该用户为API用户" toView:self.view];
  1594. return;
  1595. }
  1596. if ([model.uidStr isEqual:@"dsp_admin_1"]||[model.uidStr isEqual:@"dsp_admin_2"]) {
  1597. return;
  1598. }
  1599. YBCenterVC *center = [[YBCenterVC alloc]init];
  1600. if (![model.message isReceived]) {
  1601. //自己
  1602. center.otherUid =[Config getOwnID];
  1603. }else {
  1604. //别人
  1605. center.otherUid = model.uidStr;
  1606. }
  1607. center.isChatPage = YES;
  1608. center.isPush = YES;
  1609. center.hidesBottomBarWhenPushed = YES;
  1610. [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
  1611. }
  1612. #pragma mark -连续播放语音
  1613. - (void)getContinuePlay:(UITableViewCell *)cell
  1614. indexPath:(NSIndexPath *)indexPath {
  1615. JCHATMessageTableViewCell *tempCell = (JCHATMessageTableViewCell *) cell;
  1616. if ([_allmessageIdArr count] - 1 > indexPath.row) {
  1617. NSString *messageId = _allmessageIdArr[indexPath.row + 1];
  1618. JCHATChatModel *model = _allMessageDic[ messageId];
  1619. if (model.message.contentType == kJMSGContentTypeVoice && [model.message.flag isEqualToNumber:@(0)] && [model.message isReceived]) {
  1620. if ([[JCHATAudioPlayerHelper shareInstance] isPlaying]) {
  1621. tempCell.continuePlayer = YES;
  1622. }else {
  1623. tempCell.continuePlayer = NO;
  1624. }
  1625. }
  1626. }
  1627. }
  1628. #pragma mark 预览图片 PictureDelegate
  1629. //PictureDelegate
  1630. - (void)tapPicture:(NSIndexPath *)index tapView:(UIImageView *)tapView tableViewCell:(UITableViewCell *)tableViewCell {
  1631. [self.toolBarContainer.toolbar.textView resignFirstResponder];
  1632. JCHATMessageTableViewCell *cell =(JCHATMessageTableViewCell *)tableViewCell;
  1633. NSInteger count = _imgDataArr.count;
  1634. NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
  1635. for (int i = 0; i<count; i++) {
  1636. JCHATChatModel *messageObject = [_imgDataArr objectAtIndex:i];
  1637. MJPhoto *photo = [[MJPhoto alloc] init];
  1638. photo.message = messageObject;
  1639. photo.srcImageView = tapView; // 来源于哪个UIImageView
  1640. [photos addObject:photo];
  1641. }
  1642. MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
  1643. browser.currentPhotoIndex = [_imgDataArr indexOfObject:cell.model];
  1644. // browser.currentPhotoIndex = cell.model.photoIndex; // 弹出相册时显示的第一张图片是?
  1645. browser.photos = photos; // 设置所有的图片
  1646. browser.conversation =_conversation;
  1647. [browser show];
  1648. }
  1649. #pragma mark --获取所有发送消息图片
  1650. - (NSArray *)getAllMessagePhotoImg {
  1651. NSMutableArray *urlArr =[NSMutableArray array];
  1652. for (NSInteger i=0; i<[_allmessageIdArr count]; i++) {
  1653. NSString *messageId = _allmessageIdArr[i];
  1654. JCHATChatModel *model = _allMessageDic[messageId];
  1655. if (model.message.contentType == kJMSGContentTypeImage) {
  1656. [urlArr addObject:((JMSGImageContent *)model.message.content)];
  1657. }
  1658. }
  1659. return urlArr;
  1660. }
  1661. #pragma mark SendMessageDelegate
  1662. - (void)didStartRecordingVoiceAction {
  1663. DDLogVerbose(@"Action - didStartRecordingVoice");
  1664. [self startRecord];
  1665. }
  1666. - (void)didCancelRecordingVoiceAction {
  1667. DDLogVerbose(@"Action - didCancelRecordingVoice");
  1668. [self cancelRecord];
  1669. }
  1670. - (void)didFinishRecordingVoiceAction {
  1671. DDLogVerbose(@"Action - didFinishRecordingVoiceAction");
  1672. [self finishRecorded];
  1673. }
  1674. - (void)didDragOutsideAction {
  1675. DDLogVerbose(@"Action - didDragOutsideAction");
  1676. [self resumeRecord];
  1677. }
  1678. - (void)didDragInsideAction {
  1679. DDLogVerbose(@"Action - didDragInsideAction");
  1680. [self pauseRecord];
  1681. }
  1682. - (void)pauseRecord {
  1683. [self.voiceRecordHUD pauseRecord];
  1684. }
  1685. - (void)resumeRecord {
  1686. [self.voiceRecordHUD resaueRecord];
  1687. }
  1688. - (void)cancelRecord {
  1689. WEAKSELF
  1690. [self.voiceRecordHUD cancelRecordCompled:^(BOOL fnished) {
  1691. __strong __typeof(weakSelf)strongSelf = weakSelf;
  1692. strongSelf.voiceRecordHUD = nil;
  1693. }];
  1694. [self.voiceRecordHelper cancelledDeleteWithCompletion:^{
  1695. }];
  1696. }
  1697. #pragma mark - Voice Recording Helper Method
  1698. - (void)startRecord {
  1699. DDLogDebug(@"Action - startRecord");
  1700. [self.voiceRecordHUD startRecordingHUDAtView:self.view];
  1701. [self.voiceRecordHelper startRecordingWithPath:[self getRecorderPath] andVideo:NO StartRecorderCompletion:^{
  1702. }];
  1703. }
  1704. - (void)finishRecorded {
  1705. DDLogDebug(@"Action - finishRecorded");
  1706. WEAKSELF
  1707. [self.voiceRecordHUD stopRecordCompled:^(BOOL fnished) {
  1708. __strong __typeof(weakSelf)strongSelf = weakSelf;
  1709. strongSelf.voiceRecordHUD = nil;
  1710. }];
  1711. [self.voiceRecordHelper stopRecordingWithStopRecorderCompletion:^{
  1712. __strong __typeof(weakSelf)strongSelf = weakSelf;
  1713. [strongSelf SendMessageWithVoice:strongSelf.voiceRecordHelper.recordPath
  1714. voiceDuration:strongSelf.voiceRecordHelper.recordDuration];
  1715. }];
  1716. }
  1717. #pragma mark - Message Send helper Method
  1718. #pragma mark --发送语音
  1719. - (void)SendMessageWithVoice:(NSString *)voicePath
  1720. voiceDuration:(NSString*)voiceDuration {
  1721. DDLogDebug(@"Action - SendMessageWithVoice");
  1722. if ([voiceDuration integerValue]<0.5 || [voiceDuration integerValue]>60) {
  1723. if ([voiceDuration integerValue]<0.5) {
  1724. DDLogDebug(@"录音时长小于 0.5s");
  1725. } else {
  1726. DDLogDebug(@"录音时长大于 60s");
  1727. }
  1728. return;
  1729. }
  1730. JMSGVoiceContent *voiceContent = [[JMSGVoiceContent alloc] initWithVoiceData:[NSData dataWithContentsOfFile:voicePath]
  1731. voiceDuration:[NSNumber numberWithInteger:[voiceDuration integerValue]]];
  1732. [self checkBlack:voiceContent voice:voicePath textContent:@""];
  1733. //JMSGMessage *voiceMessage = nil;
  1734. //voiceMessage = [_conversation createMessageWithContent:voiceContent];
  1735. //[_conversation sendMessage:voiceMessage];
  1736. //[self addmessageShowTimeData:voiceMessage.timestamp];
  1737. //[model setChatModelWith:voiceMessage conversationType:_conversation userModel:_userModel];
  1738. //[JCHATFileManager deleteFile:voicePath];
  1739. //[self addMessage:model];
  1740. }
  1741. #pragma mark - 检查拉黑(只过滤文本消息关键词)
  1742. -(void)checkBlack:(JMSGAbstractContent *)content voice:(NSString *)voicePath textContent:(NSString *)textConten{
  1743. if (voicePath.length>0) {
  1744. [JCHATFileManager deleteFile:voicePath];
  1745. }
  1746. NSString *url = [NSString stringWithFormat:@"User.checkBlack&uid=%@&token=%@&touid=%@&content=%@",[Config getOwnID],[Config getOwnToken],_userModel.uidStr,textConten];
  1747. [YBNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
  1748. if (code == 0) {
  1749. NSDictionary *infoDic = [info firstObject];
  1750. NSString *isattent = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"isattent"]];
  1751. NSString *t2u = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"t2u"]];
  1752. NSString *sendConten = minstr([infoDic valueForKey:@"content"]);
  1753. NSString *p_switch = [NSString stringWithFormat:@"%@",[common private_letter_switch]];
  1754. int p_nums = [[NSString stringWithFormat:@"%@",[common private_letter_nums]] intValue];
  1755. //我发送的条数
  1756. NSMutableArray *frends_cont = [NSMutableArray array];
  1757. for (int i = 0; i < _allmessageIdArr.count; i++) {
  1758. NSString *msgid = [_allmessageIdArr objectAtIndex:i];
  1759. JCHATChatModel *model = [_allMessageDic objectForKey:msgid];
  1760. if ([model.uidStr isEqual:[Config getOwnID]]) {
  1761. [frends_cont addObject:model];
  1762. }
  1763. }
  1764. if ([t2u isEqual:@"0"]) {
  1765. if ([isattent isEqual:@"0"] && [p_switch isEqual:@"1"] && frends_cont.count >= p_nums) {
  1766. [MBProgressHUD showPop:[NSString stringWithFormat:@"%@%d%@",YZMsg(@"对方未关注你,最多只能发送"),p_nums,YZMsg(@"条信息")]];
  1767. }else {
  1768. JMSGMessage *message = nil;
  1769. if (![PublicObj checkNull:textConten]) {
  1770. //说明是文本消息
  1771. JMSGTextContent *textContentFormat = [[JMSGTextContent alloc] initWithText:sendConten];
  1772. message = [_conversation createMessageWithContent:textContentFormat];
  1773. }else{
  1774. message = [_conversation createMessageWithContent:content];
  1775. }
  1776. //[_conversation sendMessage:message];
  1777. JMSGOptionalContent *option = [[JMSGOptionalContent alloc] init];
  1778. option.noSaveNotification = YES;
  1779. [_conversation sendMessage:message optionalContent:option];
  1780. [self addmessageShowTimeData:message.timestamp];
  1781. JCHATChatModel *model =[[JCHATChatModel alloc] init];
  1782. [model setChatModelWith:message conversationType:_conversation userModel:_userModel];
  1783. [self addMessage:model];
  1784. }
  1785. }else {
  1786. [MBProgressHUD showPop:YZMsg(@"对方暂时拒绝接收您的消息")];
  1787. }
  1788. }else {
  1789. [MBProgressHUD showPop:msg];
  1790. }
  1791. } Fail:^(id fail) {
  1792. }];
  1793. }
  1794. #pragma mark - RecorderPath Helper Method
  1795. - (NSString *)getRecorderPath {
  1796. NSString *recorderPath = nil;
  1797. NSDate *now = [NSDate date];
  1798. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1799. dateFormatter.dateFormat = @"yy-MMMM-dd";
  1800. recorderPath = [[NSString alloc] initWithFormat:@"%@/Documents/", NSHomeDirectory()];
  1801. dateFormatter.dateFormat = @"yyyy-MM-dd-hh-mm-ss";
  1802. recorderPath = [recorderPath stringByAppendingFormat:@"%@-MySound.ilbc", [dateFormatter stringFromDate:now]];
  1803. return recorderPath;
  1804. }
  1805. #pragma mark - Key-value Observing
  1806. - (void)observeValueForKeyPath:(NSString *)keyPath
  1807. ofObject:(id)object
  1808. change:(NSDictionary *)change
  1809. context:(void *)context {
  1810. if (self.barBottomFlag) {
  1811. return;
  1812. }
  1813. if (object == self.toolBarContainer.toolbar.textView && [keyPath isEqualToString:@"contentSize"]) {
  1814. [self layoutAndAnimateMessageInputTextView:object];
  1815. }
  1816. }
  1817. #pragma mark - UITextView Helper Method
  1818. - (CGFloat)getTextViewContentH:(UITextView *)textView {
  1819. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
  1820. return ceilf([textView sizeThatFits:textView.frame.size].height);
  1821. } else {
  1822. return textView.contentSize.height;
  1823. }
  1824. }
  1825. #pragma mark - Layout Message Input View Helper Method
  1826. //计算input textfield 的高度
  1827. - (void)layoutAndAnimateMessageInputTextView:(UITextView *)textView {
  1828. CGFloat maxHeight = [JCHATToolBar maxHeight];
  1829. CGFloat contentH = [self getTextViewContentH:textView];
  1830. BOOL isShrinking = contentH < _previousTextViewContentHeight;
  1831. CGFloat changeInHeight = contentH - _previousTextViewContentHeight;
  1832. if (!isShrinking && (_previousTextViewContentHeight == maxHeight || textView.text.length == 0)) {
  1833. changeInHeight = 0;
  1834. }
  1835. else {
  1836. changeInHeight = MIN(changeInHeight, maxHeight - _previousTextViewContentHeight);
  1837. }
  1838. if (changeInHeight != 0.0f) {
  1839. kWEAKSELF
  1840. [UIView animateWithDuration:0.25f
  1841. animations:^{
  1842. [weakSelf setTableViewInsetsWithBottomValue:_messageTableView.contentInset.bottom + changeInHeight];
  1843. [weakSelf scrollToBottomAnimated:NO];
  1844. if (isShrinking) {
  1845. if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
  1846. _previousTextViewContentHeight = MIN(contentH, maxHeight);
  1847. }
  1848. // if shrinking the view, animate text view frame BEFORE input view frame
  1849. [_toolBarContainer.toolbar adjustTextViewHeightBy:changeInHeight];
  1850. }
  1851. if (!isShrinking) {
  1852. if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
  1853. weakSelf.previousTextViewContentHeight = MIN(contentH, maxHeight);
  1854. }
  1855. // growing the view, animate the text view frame AFTER input view frame
  1856. [weakSelf.toolBarContainer.toolbar adjustTextViewHeightBy:changeInHeight];
  1857. }
  1858. }
  1859. completion:^(BOOL finished) {
  1860. }];
  1861. JCHATMessageTextView *textview =_toolBarContainer.toolbar.textView;
  1862. CGSize textSize = [JCHATStringUtils stringSizeWithWidthString:textview.text withWidthLimit:textView.frame.size.width withFont:[UIFont systemFontOfSize:st_toolBarTextSize]];
  1863. CGFloat textHeight = textSize.height > maxHeight?maxHeight:textSize.height;
  1864. _toolBarHeightConstrait.constant = (textHeight + 8)>=45?(textHeight + 8):45;//!
  1865. self.previousTextViewContentHeight = MIN(contentH, maxHeight);
  1866. }
  1867. // Once we reached the max height, we have to consider the bottom offset for the text view.
  1868. // To make visible the last line, again we have to set the content offset.
  1869. if (self.previousTextViewContentHeight == maxHeight) {
  1870. double delayInSeconds = 0.01;
  1871. dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
  1872. dispatch_after(popTime,
  1873. dispatch_get_main_queue(),
  1874. ^(void) {
  1875. CGPoint bottomOffset = CGPointMake(0.0f, contentH - textView.bounds.size.height);
  1876. [textView setContentOffset:bottomOffset animated:YES];
  1877. });
  1878. }
  1879. }
  1880. - (void)inputTextViewDidChange:(JCHATMessageTextView *)messageInputTextView {
  1881. //rk_20-6-28 去掉草稿
  1882. //[[JCHATSendMsgManager ins] updateConversation:_conversation withDraft:messageInputTextView.text];
  1883. }
  1884. - (void)scrollToBottomAnimated:(BOOL)animated {
  1885. if (![self shouldAllowScroll]) return;
  1886. NSInteger rows = [self.messageTableView numberOfRowsInSection:0];
  1887. if (rows > 0) {
  1888. [self.messageTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_allmessageIdArr count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
  1889. }
  1890. }
  1891. #pragma mark - Previte Method
  1892. - (BOOL)shouldAllowScroll {
  1893. //if (self.isUserScrolling) {
  1894. // if ([self.delegate respondsToSelector:@selector(shouldPreventScrollToBottomWhileUserScrolling)]
  1895. // && [self.delegate shouldPreventScrollToBottomWhileUserScrolling]) {
  1896. // return NO;
  1897. // }
  1898. // }
  1899. return YES;
  1900. }
  1901. #pragma mark - Scroll Message TableView Helper Method
  1902. - (void)setTableViewInsetsWithBottomValue:(CGFloat)bottom {
  1903. //UIEdgeInsets insets = [self tableViewInsetsWithBottomValue:bottom];
  1904. //self.messageTableView.contentInset = insets;
  1905. //self.messageTableView.scrollIndicatorInsets = insets;
  1906. }
  1907. - (UIEdgeInsets)tableViewInsetsWithBottomValue:(CGFloat)bottom {
  1908. UIEdgeInsets insets = UIEdgeInsetsZero;
  1909. if ([self respondsToSelector:@selector(topLayoutGuide)]) {
  1910. insets.top = 64;
  1911. }
  1912. insets.bottom = bottom;
  1913. return insets;
  1914. }
  1915. #pragma mark - XHMessageInputView Delegate
  1916. - (void)inputTextViewWillBeginEditing:(JCHATMessageTextView *)messageInputTextView {
  1917. _textViewInputViewType = JPIMInputViewTypeText;
  1918. }
  1919. - (void)inputTextViewDidBeginEditing:(JCHATMessageTextView *)messageInputTextView {
  1920. if (!_previousTextViewContentHeight)
  1921. _previousTextViewContentHeight = [self getTextViewContentH:messageInputTextView];
  1922. }
  1923. - (void)inputTextViewDidEndEditing:(JCHATMessageTextView *)messageInputTextView;
  1924. {
  1925. if (!_previousTextViewContentHeight)
  1926. _previousTextViewContentHeight = [self getTextViewContentH:messageInputTextView];
  1927. }
  1928. - (void)didReceiveMemoryWarning {
  1929. [super didReceiveMemoryWarning];
  1930. }
  1931. #pragma mark - 拉黑
  1932. -(void)setBlack {
  1933. NSString *url = [NSString stringWithFormat:@"User.setBlack&uid=%@&token=%@&touid=%@",[Config getOwnID],[Config getOwnToken],_userModel.uidStr];
  1934. [YBNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
  1935. if (code == 0) {
  1936. NSString *infoDic = [info firstObject];
  1937. NSString *isBlakc = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"isblack"]];
  1938. if ([isBlakc isEqual:@"1"]) {
  1939. [MBProgressHUD showPop:YZMsg(@"拉黑成功")];
  1940. }else {
  1941. [MBProgressHUD showPop:YZMsg(@"解除拉黑成功")];
  1942. }
  1943. }else {
  1944. [MBProgressHUD showPop:msg];
  1945. }
  1946. } Fail:^(id fail) {
  1947. }];
  1948. }
  1949. //clickRightMore
  1950. -(void)clickNaviRightBtn {
  1951. NSString *url = [NSString stringWithFormat:@"User.checkBlack&uid=%@&token=%@&touid=%@",[Config getOwnID],[Config getOwnToken],_userModel.uidStr];
  1952. YBWeakSelf;
  1953. [YBNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
  1954. if (code == 0) {
  1955. NSDictionary *infoDic = [info firstObject];
  1956. NSString *u2t = [NSString stringWithFormat:@"%@",[infoDic valueForKey:@"u2t"]];
  1957. //u2t 0-未拉黑 1-已拉黑
  1958. NSString *blackTitle = YZMsg(@"拉黑");
  1959. if ([u2t isEqual:@"1"]) {
  1960. blackTitle = YZMsg(@"解除拉黑");
  1961. }
  1962. [weakSelf showSheetView:blackTitle];
  1963. }else {
  1964. [MBProgressHUD showPop:msg];
  1965. }
  1966. } Fail:^(id fail) {
  1967. }];
  1968. }
  1969. -(void)showSheetView:(NSString *)blackTitle {
  1970. YBWeakSelf;
  1971. RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
  1972. [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"举报") complete:^{
  1973. PubH5 *h5vc = [[PubH5 alloc]init];
  1974. h5vc.url =[h5url stringByAppendingString:[NSString stringWithFormat:@"/appapi/userreport/index?uid=%@&token=%@&touid=%@",[Config getOwnID],[Config getOwnToken],_userModel.uidStr]];
  1975. [weakSelf.navigationController pushViewController:h5vc animated:YES];
  1976. }];
  1977. [sheet addActionWithType:RKSheet_Default andTitle:blackTitle complete:^{
  1978. [weakSelf setBlack];
  1979. }];
  1980. [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
  1981. }];
  1982. [sheet showSheet];
  1983. }
  1984. #pragma mark - 导航
  1985. - (void)clickNaviLeftBtn {
  1986. if ([[JCHATAudioPlayerHelper shareInstance] isPlaying]) {
  1987. [[JCHATAudioPlayerHelper shareInstance] stopAudio];
  1988. }
  1989. [self.navigationController popViewControllerAnimated:YES];
  1990. }
  1991. //聊天小窗口
  1992. - (void)reloadSamllChtaView:(NSString *)isatt{
  1993. self.naviView.hidden = YES;
  1994. UIView *smallNavi = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 35)];
  1995. smallNavi.backgroundColor = _isWhiteStyle?RGB_COLOR(@"#f9fafb", 1):CellRow_Cor;
  1996. [self.view addSubview:smallNavi];
  1997. if ([isatt isEqual:@"1"]) {
  1998. [followView removeFromSuperview];
  1999. followView = nil;
  2000. }else{
  2001. if (followView) {
  2002. followView.y = 35;
  2003. }
  2004. }
  2005. [self.moreViewContainer.moreView removeFromSuperview];
  2006. UIButton *btn = [UIButton buttonWithType:0];
  2007. btn.frame = CGRectMake(0, 0, 35, 35);
  2008. [btn setImage:[UIImage imageNamed:@"gray_back"] forState:0];
  2009. btn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
  2010. [btn addTarget:self action:@selector(hideSmallView) forControlEvents:UIControlEventTouchUpInside];
  2011. [smallNavi addSubview:btn];
  2012. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 0, _window_width-70, 35)];
  2013. titleLabel.font = [UIFont systemFontOfSize:13];
  2014. titleLabel.textColor= RGB_COLOR(@"#636464", 1);
  2015. titleLabel.textAlignment = NSTextAlignmentCenter;
  2016. titleLabel.text = _userModel.unameStr;
  2017. [smallNavi addSubview:titleLabel];
  2018. self.messageTabTop.constant = 35;
  2019. _messageTableView.frame = CGRectMake(0, 0, _window_width, _window_height*0.4-80);
  2020. [self getGroupMemberListWithGetMessageFlag:YES];
  2021. self.toolBarContainer.toolbar.voideWidth.constant -= 30;
  2022. self.toolBarContainer.toolbar.addBtnWidth.constant -= 30;
  2023. [_emojiV removeFromSuperview];
  2024. _emojiV = nil;
  2025. _emojiV = [[twEmojiView alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, EmojiHeight)];
  2026. _emojiV.delegate = self;
  2027. _emojiV.isWhiteStyle = _isWhiteStyle;
  2028. [[UIApplication sharedApplication].delegate.window addSubview:_emojiV];
  2029. }
  2030. - (void)hideSmallView{
  2031. [_asrView.textView resignFirstResponder];
  2032. //[[NSNotificationCenter defaultCenter] removeObserver:self];
  2033. //[self.toolBarContainer.toolbar.textView removeObserver:self forKeyPath:@"contentSize"];
  2034. ////remove delegate
  2035. //[[NSNotificationCenter defaultCenter] removeObserver:self name:kAlertToSendImage object:self];
  2036. //[JMessage removeDelegate:self withConversation:_conversation];
  2037. [self dropToolBar];
  2038. if (self.block) {
  2039. self.block(0);
  2040. }
  2041. }
  2042. @end