ChatController.m 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558
  1. //
  2. // ChatController.m
  3. // AIIM
  4. //
  5. // Created by gan on 2025/4/6.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <Photos/Photos.h>
  10. #import <PhotosUI/PhotosUI.h>
  11. #import <MobileCoreServices/MobileCoreServices.h>
  12. #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
  13. #import "ChatController.h"
  14. #import "FriendController.h"
  15. #import "GroupController.h"
  16. #import "ChatsStore.h"
  17. #import "ChatListStore.h"
  18. #import "FriendNetApi.h"
  19. #import "FileNetApi.h"
  20. #import "GroupNetApi.h"
  21. #import "UserNetApi.h"
  22. #import "GWebSocket.h"
  23. #import "UDManager.h"
  24. #import "CryptoAES.h"
  25. #import "GDBManager.h"
  26. #import "chatpopView.h"
  27. #import "config.h"
  28. #import "JSGController.h"
  29. #import "SDWebImage/SDWebImage.h"
  30. #import "ChatMessageModel.h"
  31. #import "ChatFileModel.h"
  32. #import "AppDelegate.h"
  33. #import "HistoryPreloader.h"
  34. #import "chatCellView.h"
  35. #import "CameraViewController.h"
  36. #import "ForwardViewController.h"
  37. #import "ChatBatchView.h"
  38. #import "ChatQuoteView.h"
  39. #import "ChatAtMemberView.h"
  40. #import "PopupView.h"
  41. #import "MentionTextView.h"
  42. #import "TopPopupView.h"
  43. #import "OSSManager.h"
  44. static const CGFloat kQuoteViewHeight = 46.0f;
  45. @interface ChatController()<UITextViewDelegate,ChatsStoreDelegate,UITableViewDelegate,UITableViewDataSource,chatpopViewDelegate,PHPickerViewControllerDelegate,UINavigationControllerDelegate,UIDocumentPickerDelegate,UIScrollViewDelegate,OSSManagerDelegate>
  46. @property (weak, nonatomic) IBOutlet UILabel *titlelb;
  47. @property (weak, nonatomic) IBOutlet UITableView *_tableView;
  48. @property(nonatomic, strong) MentionTextView *inputView;
  49. //@property(nonatomic, strong) UITextView *inputView;
  50. @property (weak, nonatomic) IBOutlet UIView *bottonView;
  51. @property (weak, nonatomic) IBOutlet UIButton *yuyinctr;
  52. @property (weak, nonatomic) IBOutlet UIButton *fasngBt;
  53. @property (weak, nonatomic) IBOutlet UIButton *gengduoBt;
  54. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottom;
  55. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;
  56. @property (nonatomic, strong) HistoryPreloader * preloader;
  57. //录音
  58. @property(nonatomic, strong) UIButton *AVRecordBt;
  59. @property (nonatomic,strong) AVAudioRecorder *recorder;
  60. @property (nonatomic,strong) NSString *AudiofilePath;
  61. @property (nonatomic,strong) NSString *AudiofileName;
  62. @property (nonatomic) NSInteger rcdL;
  63. @property (strong, nonatomic) NSTimer *heatBeat;
  64. @property (nonatomic,strong) AVPlayer *player;
  65. @property (nonatomic) CGFloat keyboardHeight;
  66. @property (nonatomic) BOOL isfriend;
  67. @property (nonatomic) BOOL keybarShow;
  68. @property (nonatomic) BOOL canloadhistory;
  69. @property (nonatomic) BOOL canloadhistoryMore;
  70. @property (nonatomic) CGFloat offset;
  71. @property (nonatomic,strong) NSString *username;
  72. @property (nonatomic,strong) NSString *useravatar;
  73. @property (nonatomic,strong) UITextView *textV;
  74. @property (nonatomic,strong) chatpopView *popView;
  75. @property (nonatomic,strong) UIView *markView;
  76. @property (nonatomic, strong) ChatBatchView * batchView;
  77. @property (nonatomic, strong) ChatQuoteView * quoteView;
  78. @property (nonatomic, assign) BOOL isQuoteMessage;
  79. @property (strong, nonatomic) NSTimer *timer;
  80. @property (nonatomic, strong) NSDictionary * groupInfo;
  81. @property (nonatomic,strong) NSMutableArray *messageArray;
  82. @property (nonatomic, strong) NSMutableArray * forwordMsgArray;
  83. @property (nonatomic, strong) NSMutableArray * atSomeoneArray;
  84. @property (nonatomic, assign) BOOL isBatchMode;
  85. @property (nonatomic, assign) BOOL showLoading;
  86. @end
  87. @implementation ChatController
  88. - (UIStatusBarStyle)preferredStatusBarStyle {
  89. return UIStatusBarStyleLightContent;
  90. }
  91. -(void)viewDidLoad{
  92. [super viewDidLoad];
  93. [self.navigationController setNavigationBarHidden:YES animated:NO];
  94. [self._tableView registerClass:chatCellView.class forCellReuseIdentifier:@"chatCellView"];
  95. self._tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  96. self._tableView.backgroundColor = [UIColor clearColor];
  97. self._tableView.delegate=self;
  98. self._tableView.dataSource = self;
  99. _isfriend=true;
  100. //输入框
  101. _inputView = [[MentionTextView alloc] initWithFrame:CGRectMake(54, 10, self.view.frame.size.width - 180, 40)];
  102. _inputView.backgroundColor = globalColor(GCTypeDark2);
  103. _inputView.layer.cornerRadius = 4.0;
  104. _inputView.textColor = [UIColor blackColor];
  105. _inputView.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
  106. [_bottonView addSubview:_inputView];
  107. _inputView.delegate = self; // 设置代理
  108. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  109. [_inputView setup];
  110. //删除@用户名
  111. weakSelf(self);
  112. _inputView.mentionDeleteHandler = ^(NSString * _Nonnull deletedMention, NSUInteger index) {
  113. // NSLog(@"第%ld---%@",index,deletedMention);
  114. // NSLog(@"weakself.atSomeoneArray:%@",weakself.atSomeoneArray);
  115. if ([deletedMention isEqualToString:@"@所有人"]) {
  116. return;
  117. }
  118. [weakself removeAtList:index];
  119. };
  120. [_inputView mas_makeConstraints:^(MASConstraintMaker *make) {
  121. // make.height.mas_equalTo(40);
  122. make.left.equalTo(self.yuyinctr.mas_right).mas_offset(10);
  123. make.right.equalTo(self.gengduoBt.mas_left).mas_offset(-10);
  124. make.bottom.mas_offset(-10);
  125. make.top.mas_offset(10);
  126. }];
  127. //录音按钮
  128. _AVRecordBt = [[UIButton alloc] initWithFrame:CGRectMake(54, 10, self.view.frame.size.width - 180, 40)];
  129. [_bottonView addSubview:_AVRecordBt];
  130. _AVRecordBt.alpha = 0;
  131. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeDark2).CGColor;
  132. _AVRecordBt.layer.cornerRadius = 4.0;
  133. [_AVRecordBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  134. [_AVRecordBt setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
  135. [_AVRecordBt setTitle:@" 按住 说话" forState:UIControlStateNormal];
  136. [_AVRecordBt addTarget:self action:@selector(longTarget) forControlEvents:UIControlEventTouchDown];
  137. [_AVRecordBt addTarget:self action:@selector(UpInside) forControlEvents:UIControlEventTouchUpInside];
  138. [self.bottonView addSubview:self.quoteView];
  139. [self.quoteView mas_makeConstraints:^(MASConstraintMaker *make) {
  140. make.left.mas_equalTo(_inputView.mas_left);
  141. make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-180, 30));
  142. make.top.mas_equalTo(self.inputView.mas_bottom).offset(8);
  143. }];
  144. // 注册键盘显示通知
  145. [[NSNotificationCenter defaultCenter] addObserver:self
  146. selector:@selector(keyboardWillShow:)
  147. name:UIKeyboardWillShowNotification object:nil];
  148. // 注册键盘隐藏通知
  149. [[NSNotificationCenter defaultCenter] addObserver:self
  150. selector:@selector(keyboardWillHide:)
  151. name:UIKeyboardWillHideNotification object:nil];
  152. //nkonNewMessageNote
  153. [[NSNotificationCenter defaultCenter] addObserver:self
  154. selector:@selector(othersChatMessageAlert:)
  155. name:nkonNewMessageNote
  156. object:nil];
  157. [self inidatastate];
  158. _textV=[[UITextView alloc] init];
  159. _markView=[[UIView alloc] init];
  160. [self.view addSubview:_markView];
  161. NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"chatpopView" owner:self options:nil];
  162. _popView = [nibs objectAtIndex:0];
  163. [self.view addSubview:_popView];
  164. _popView.delegate= self;
  165. [self initpopbottonView];
  166. [self setupPreloader];
  167. NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  168. NSLog(@"viewDidLoad userinfo:%@",userinfo);
  169. self.userId = userinfo[@"id"];
  170. self.username = userinfo[@"name"];
  171. self.useravatar = userinfo[@"avatar"];
  172. ChatsStore.shareInstance.delegate = self;
  173. ChatsStore.shareInstance.chatId = self.chatId;
  174. ChatsStore.shareInstance.userid =self.userId;
  175. ChatListStore.shareInstance.chatId = self.chatId;
  176. [ChatsStore.shareInstance getchatReadTime:self.chatId];
  177. [OSSManager sharedManager].delegate = self;
  178. _showLoading = YES;
  179. NSString *type=@"";
  180. if(self.type==0){
  181. type=@"0";
  182. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  183. }
  184. else if(self.type==1){
  185. type=@"1";
  186. // [ChatsStore.shareInstance reloadQunData:@"1871105598206210050" type:self.type];
  187. [ChatsStore.shareInstance getGroupUserList:self.chatId];
  188. [self getGroupInfo];
  189. }
  190. _canloadhistory=true;
  191. NSDictionary *chatMsg=@{
  192. @"chatId":self.chatId,
  193. @"name":self.titlename?:@"",
  194. @"avatar":self.avatar?:@"",
  195. @"type":type
  196. };
  197. // NSLog(@"self.chatId:%@",self.chatId);
  198. [ChatListStore.shareInstance chatDidOpen:chatMsg];
  199. [GWebSocket.shareInstance chekWebSocket];
  200. }
  201. -(void)reloadAllData{
  202. [self.messageArray removeAllObjects];
  203. self.msgList = @[];
  204. [__tableView reloadData];
  205. _titlelb.text = self.titlename;
  206. ChatsStore.shareInstance.delegate = self;
  207. [OSSManager sharedManager].delegate = self;
  208. ChatsStore.shareInstance.chatId = self.chatId;
  209. ChatsStore.shareInstance.userid =self.userId;
  210. ChatListStore.shareInstance.chatId = self.chatId;
  211. [ChatsStore.shareInstance getchatReadTime:self.chatId];
  212. NSString *type=@"";
  213. if(self.type==0){
  214. type=@"0";
  215. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  216. }
  217. else if(self.type==1){
  218. type=@"1";
  219. // [ChatsStore.shareInstance reloadQunData:@"1871105598206210050" type:self.type];
  220. [ChatsStore.shareInstance getGroupUserList:self.chatId];
  221. [self getGroupInfo];
  222. }
  223. _canloadhistory=true;
  224. NSDictionary *chatMsg=@{
  225. @"chatId":self.chatId,
  226. @"name":self.titlename?:@"",
  227. @"avatar":self.avatar?:@"",
  228. @"type":type
  229. };
  230. // NSLog(@"self.chatId:%@",self.chatId);
  231. [ChatListStore.shareInstance chatDidOpen:chatMsg];
  232. [GWebSocket.shareInstance chekWebSocket];
  233. [self movetoBotton];
  234. }
  235. - (void)dealloc {
  236. // NSLog(@"dealloc-----:%@",self);
  237. [self.preloader stopMonitoring];
  238. [[NSNotificationCenter defaultCenter] removeObserver:self];
  239. ChatsStore.shareInstance.delegate = nil;
  240. [OSSManager sharedManager].delegate = nil;
  241. ChatsStore.shareInstance.chatId = nil;
  242. }
  243. -(void)viewDidAppear:(BOOL)animated{
  244. [super viewDidAppear:animated];
  245. _titlelb.text = self.titlename;
  246. [self startTimer];
  247. // NSLog(@"viewDidAppear-----:%@",self);
  248. }
  249. -(void)viewWillDisappear:(BOOL)animated{
  250. [super viewWillDisappear:animated];
  251. [self endTimer];
  252. // NSLog(@"viewWillDisappear-----");
  253. }
  254. - (ChatBatchView *)batchView{
  255. if (!_batchView) {
  256. _batchView = [[ChatBatchView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_X_BTM+64)];
  257. [self.view addSubview:_batchView];
  258. }
  259. return _batchView;
  260. }
  261. - (ChatQuoteView *)quoteView{
  262. if (!_quoteView) {
  263. _quoteView = [[ChatQuoteView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-180, 30)];
  264. _quoteView.hidden = YES;
  265. [_quoteView.closeBtn addTarget:nil action:@selector(closeQuoteView) forControlEvents:UIControlEventTouchUpInside];
  266. // [_quoteView.closeBtn jk_addActionHandler:^(NSInteger tag) {
  267. // [self closeQuoteView];
  268. // }];
  269. }
  270. return _quoteView;
  271. }
  272. -(NSMutableArray *)messageArray{
  273. if (!_messageArray) {
  274. _messageArray = [NSMutableArray array];
  275. }
  276. return _messageArray;
  277. }
  278. -(NSMutableArray *)forwordMsgArray{
  279. if (!_forwordMsgArray) {
  280. _forwordMsgArray = [NSMutableArray array];
  281. }
  282. return _forwordMsgArray;
  283. }
  284. -(NSMutableArray *)atSomeoneArray{
  285. if (!_atSomeoneArray) {
  286. _atSomeoneArray = [NSMutableArray array];
  287. }
  288. return _atSomeoneArray;
  289. }
  290. -(void)inidatastate{
  291. [FriendNetApi isfriend:self.chatId succ:^(int code, NSDictionary * res) {
  292. NSLog(@"isfriend:%@",[res[@"data"] class]);
  293. BOOL state = res[@"data"];
  294. if(state){
  295. NSLog(@"isfriend1:");
  296. self.isfriend = true;
  297. }
  298. else{
  299. NSLog(@"isfriend2:");
  300. self.isfriend=false;
  301. }
  302. } fail:^(NSError * _Nonnull error) {
  303. }];
  304. }
  305. -(void)initpopbottonView{
  306. [self hidBottonView];
  307. // UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
  308. // // 将手势添加到主视图上
  309. // [self.view addGestureRecognizer:tap];
  310. UITapGestureRecognizer *tapbotton = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissBotton)];
  311. // 将手势添加到主视图上
  312. [_markView addGestureRecognizer:tapbotton];
  313. _keybarShow=false;
  314. }
  315. - (IBAction)fanhui:(id)sender {
  316. NSLog(@"fanhui-------");
  317. [self dismissViewControllerAnimated:YES completion:nil];
  318. }
  319. - (IBAction)rightBt:(id)sender {
  320. if (self.type==0) {
  321. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  322. FriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"FriendController"];
  323. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  324. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  325. friendctr.friendMsg = nil;
  326. friendctr.friendId = self.chatId;
  327. [self presentViewController :uiNavC animated:YES completion:nil];
  328. }
  329. else{
  330. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  331. GroupController *friendctr = [board instantiateViewControllerWithIdentifier:@"GroupController"];
  332. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  333. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  334. friendctr.groupMsg = nil;
  335. friendctr.groupId = self.chatId;
  336. [self presentViewController :uiNavC animated:YES completion:nil];
  337. }
  338. }
  339. - (IBAction)yuyinBt:(id)sender {
  340. if(_AVRecordBt.alpha==1){
  341. _AVRecordBt.alpha = 0;
  342. _inputView.alpha = 1;
  343. [_yuyinctr setImage:[UIImage imageNamed:@"yuyin"] forState:UIControlStateNormal];
  344. [self dismissKeyboard];
  345. }
  346. else{
  347. _AVRecordBt.alpha = 1;
  348. _inputView.alpha = 0;
  349. [_yuyinctr setImage:[UIImage imageNamed:@"jianpan"] forState:UIControlStateNormal];
  350. }
  351. }
  352. - (IBAction)biaoqingBt:(id)sender {
  353. }
  354. - (IBAction)gengduo:(id)sender {
  355. [self showBottonView];
  356. }
  357. - (IBAction)fasongBt:(id)sender {
  358. NSLog(@"fasongBt:1");
  359. if(_isfriend){
  360. NSLog(@"fasongBt:2");
  361. [self sendtextData];
  362. }
  363. else{//提示不是好友
  364. NSLog(@"fasongBt:3");
  365. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"不是好友关系" preferredStyle:UIAlertControllerStyleAlert];
  366. [self presentViewController:alert animated:NO completion:nil];
  367. NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(dismissAlert:) userInfo:alert repeats:NO];
  368. }
  369. //[app showAlert:@"警告" msg:@"不是好友关系" timelate:2];
  370. }
  371. - (void)dismissAlert:(NSTimer *)timer {
  372. UIAlertController *alert = [timer userInfo];
  373. [alert dismissViewControllerAnimated:YES completion:nil];
  374. alert = nil;
  375. }
  376. #pragma mark 群信息
  377. - (void)getGroupInfo{
  378. [GroupNetApi getGroupInfo:self.chatId succ:^(int code, NSDictionary * _Nullable result) {
  379. // NSLog(@"GroupInfo:----%@",result);
  380. self.groupInfo = result[@"data"];
  381. self.titlename = self.groupInfo[@"name"];
  382. self.titlelb.text = self.groupInfo[@"name"];
  383. } fail:^(NSError * _Nonnull error) {
  384. NSLog(@"error:%@",error);
  385. }];
  386. }
  387. #pragma mark ChatsStoreDelegate
  388. -(void)getlocalData{
  389. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  390. }
  391. -(void)ChatsChange:(NSArray *)msgList type:(NSInteger)typpe{
  392. // NSLog(@"msgList:%@",msgList);
  393. if([msgList count]==0){
  394. return;
  395. }
  396. if(self.msgList.count>0){
  397. NSArray *array = msgList.copy;
  398. NSMutableArray *marray = [NSMutableArray new];
  399. // [marray addObjectsFromArray:self.msgList];
  400. [marray addObjectsFromArray:array];
  401. NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:marray];
  402. NSMutableArray *uniqueArray = [orderedSet.array mutableCopy];
  403. self.msgList = [ChatsStore.shareInstance arraysort:uniqueArray];
  404. }
  405. else{
  406. self.msgList = msgList.copy;
  407. NSMutableArray *array = [NSMutableArray new];
  408. [array addObjectsFromArray:self.msgList];
  409. NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:array];
  410. NSMutableArray *uniqueArray = [orderedSet.array mutableCopy];
  411. self.msgList = [ChatsStore.shareInstance arraysort:uniqueArray];
  412. }
  413. // NSLog(@"self.msgList11:%@",self.msgList);
  414. NSMutableArray * tempArray = [NSMutableArray array];
  415. for (NSDictionary * msg in self.msgList) {
  416. // NSLog(@"msg:%@",msg);
  417. ChatMessageModel *message = [ChatMessageModel modelWithDictionary:msg];
  418. if (message.avatar.length==0 && message.isSender) {
  419. message.avatar = self.useravatar;
  420. }else if (message.avatar.length==0 && !message.isSender) {
  421. message.avatar = self.avatar;
  422. }
  423. if ([message.chatId isEqualToString:self.chatId]) {
  424. [tempArray addObject:message];
  425. }
  426. }
  427. // NSLog(@"----222---:coun-------:%lu",(unsigned long)tempArray.count);
  428. NSMutableArray * indexPathArray = [NSMutableArray array];
  429. BOOL isHistoryRecord = NO;
  430. if (self.messageArray.count == 0) {
  431. [self.messageArray removeAllObjects];
  432. [self.messageArray addObjectsFromArray:tempArray];
  433. // NSLog(@"----222---:count ==%lu",(unsigned long)self.messageArray.count);
  434. //禁用隐式动画 加载历史消息
  435. [CATransaction begin];
  436. [CATransaction setDisableActions:YES];
  437. [self._tableView reloadData];
  438. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  439. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  440. [CATransaction commit];
  441. [self.preloader startMonitoring];
  442. [self faSongYidu];
  443. _canloadhistory = true;
  444. return;
  445. }else{
  446. for (ChatMessageModel *message in tempArray) {
  447. BOOL isContain = NO;
  448. // NSLog(@"----333---:%ld",(long)message.localtime);
  449. for (ChatMessageModel * localMessage in self.messageArray) {
  450. if (localMessage.localtime==message.localtime) {
  451. isContain = YES;
  452. if (![message.url isEqualToString:localMessage.url] || ![message.readStatus isEqualToString:localMessage.readStatus]||localMessage.messageType!=message.messageType) {
  453. [localMessage exchangeModelWithModel:message];
  454. // NSLog(@"----11---:%@",message.content);
  455. dispatch_async(dispatch_get_main_queue(), ^{
  456. [CATransaction begin];
  457. [CATransaction setDisableActions:YES];
  458. NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:[self.messageArray indexOfObject:localMessage] inSection:0];
  459. [self._tableView beginUpdates];
  460. [self._tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationNone];
  461. [self._tableView endUpdates];
  462. [CATransaction commit];
  463. });
  464. }else{
  465. [localMessage exchangeModelWithModel:message];
  466. // NSLog(@"----222---:%@",message.content);
  467. }
  468. }
  469. else{
  470. // NSLog(@"1122211------");
  471. }
  472. }
  473. if (!isContain) {
  474. // NSLog(@"!isContain");
  475. ChatMessageModel *lastObj = self.messageArray.lastObject;
  476. if (lastObj.timestamp > message.timestamp) {
  477. //插入历史消息
  478. for (ChatMessageModel * localMessage in self.messageArray) {
  479. if(localMessage.timestamp>message.timestamp){
  480. NSInteger index = [self.messageArray indexOfObject:localMessage];
  481. // NSLog(@"插入历史消息1------:%@",message.content);
  482. // NSLog(@"index:%ld",(long)index);
  483. [self.messageArray insertObject:message atIndex:index];
  484. NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
  485. [indexPathArray addObject:newIndexPath];
  486. break;
  487. }
  488. }
  489. }else{
  490. // NSLog(@"插入历史消息2------:%@",message.content);
  491. isHistoryRecord = NO;
  492. [self.messageArray addObject:message];
  493. NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:self.messageArray.count-1 inSection:0];
  494. [indexPathArray addObject:newIndexPath];
  495. }
  496. }
  497. else{
  498. // NSLog(@"插入历史消息6------:%@",message.content);
  499. }
  500. }
  501. }
  502. if (indexPathArray.count == 0) {
  503. if(msgList.count>0){
  504. _canloadhistory = true;
  505. }
  506. else{
  507. _canloadhistory = false;
  508. }
  509. return;
  510. }
  511. // NSLog(@"----222444---:count ==%lu",(unsigned long)self.messageArray.count);
  512. if (isHistoryRecord) {
  513. // 执行插入操作(禁用动画)
  514. for (NSIndexPath * index in indexPathArray) {
  515. if (index.row>=self.messageArray.count) {
  516. return;
  517. }
  518. }
  519. [CATransaction begin];
  520. [CATransaction setDisableActions:YES];
  521. [self._tableView beginUpdates];
  522. [self._tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
  523. [self._tableView endUpdates];
  524. [CATransaction commit];
  525. [self.preloader resetScrollState];
  526. if(msgList.count>0){
  527. _canloadhistory = true;
  528. }
  529. else{
  530. _canloadhistory = false;
  531. }
  532. }else{
  533. [CATransaction begin];
  534. [CATransaction setDisableActions:YES];
  535. [self._tableView beginUpdates];
  536. [self._tableView insertRowsAtIndexPaths:indexPathArray
  537. withRowAnimation:UITableViewRowAnimationNone];
  538. [self._tableView endUpdates];
  539. [CATransaction commit];
  540. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  541. //插入新消息时,判断是否在底部附近,在底部附近则滚动至底部,不在底部则不打断用户浏览
  542. CGFloat visibleHeight = self._tableView.bounds.size.height - self._tableView.contentInset.top - self._tableView.contentInset.bottom;
  543. CGFloat yOffset = self._tableView.contentOffset.y;
  544. CGFloat threshold = MAX(20, visibleHeight * 0.8); // 距离底部20点或20%可见高度
  545. // NSLog(@"threshold:%f,%f",threshold,self._tableView.contentSize.height - yOffset - visibleHeight);
  546. BOOL shouldScrollToBottom = (self._tableView.contentSize.height - yOffset - visibleHeight) <= threshold;
  547. if (shouldScrollToBottom) {
  548. [CATransaction begin];
  549. [CATransaction setDisableActions:YES];
  550. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  551. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  552. [CATransaction commit];
  553. }
  554. });
  555. [self faSongYidu];
  556. if(msgList.count>0){
  557. _canloadhistory = true;
  558. }
  559. else{
  560. _canloadhistory = false;
  561. }
  562. }
  563. if(self.messageArray.count>20){
  564. _showLoading = false;
  565. }
  566. else{
  567. _showLoading = true;
  568. }
  569. }
  570. -(void)movetoBotton{
  571. // NSLog(@"movetoBotton------movetoBotton");
  572. if (self.messageArray.count>0) {
  573. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  574. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  575. //NSLog(@"lastRowIndexPath:%ld",(long)lastRowIndexPath.row);
  576. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  577. });
  578. }
  579. }
  580. #pragma mark chatpopViewDelegate
  581. -(void)actionNote:(NSString *)note{
  582. [self hidBottonView];
  583. if([note isEqualToString:@"1"]){//发送图片
  584. [self showImagePicker:1];
  585. }
  586. if([note isEqualToString:@"2"]){//发送视频
  587. [self showImagePicker:2];
  588. }
  589. if([note isEqualToString:@"3"]){//发送文件
  590. [self showfilePicker];
  591. }
  592. if([note isEqualToString:@"4"]){//语音
  593. [self showWebRtcVidio:4];
  594. }
  595. if([note isEqualToString:@"5"]){//视频
  596. [self showWebRtcVidio:5];
  597. }
  598. if([note isEqualToString:@"6"]){//拍摄
  599. [self takePhoto];
  600. }
  601. }
  602. #pragma mark preload
  603. -(void)setupPreloader{
  604. //预加载管理器
  605. NSLog(@"setupPreloader");
  606. self.preloader = [[HistoryPreloader alloc] init];
  607. self.preloader.tableView = self._tableView;
  608. self.preloader.threshold = 700;
  609. weakSelf(self);
  610. self.preloader.loadBlock = ^{
  611. if (!weakself.canloadhistory) {
  612. return;
  613. }
  614. [weakself loadhistoryData];
  615. };
  616. self.preloader.toofast = ^{
  617. if (weakself.showLoading) {
  618. }else{
  619. weakself.showLoading = YES;
  620. // [MBProgressHUD showLoadingWithText:@"數據解密中。。。。" inView:weakself.view hideAfterDelay:2];
  621. }
  622. };
  623. }
  624. -(void)loadhistoryData{
  625. if(self.messageArray.count>0){
  626. NSLog(@"loadhistoryData-------");
  627. _canloadhistory = false;
  628. if(self.type==0){
  629. ChatMessageModel *eldata = self.messageArray[0];
  630. NSInteger time =eldata.timestamp;
  631. [ChatsStore.shareInstance loadNextData:self.chatId timestp:time];
  632. }
  633. else if(self.type==1){
  634. ChatMessageModel *eldata = self.messageArray[0];
  635. NSInteger time =eldata.timestamp;
  636. [ChatsStore.shareInstance loadQunNextData:self.chatId timestp:time];
  637. }
  638. }
  639. }
  640. #pragma mark UITableViewDelegate,UITableViewDataSource
  641. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  642. return 1;
  643. }
  644. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  645. return self.messageArray.count;
  646. }
  647. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  648. if(self.messageArray.count<indexPath.row){
  649. return nil;
  650. }
  651. static NSString *cellID = @"chatCellView";
  652. chatCellView *cell =[tableView dequeueReusableCellWithIdentifier:cellID];
  653. if(cell==nil){
  654. cell=[[chatCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
  655. }
  656. cell.parentViewController = self;
  657. cell.isHistory = false;
  658. ChatMessageModel *message = self.messageArray[indexPath.row];
  659. // NSLog(@"---:%ld,%@",(long)message.localtime,message.content);
  660. weakSelf(self);
  661. cell.bubbleCellLongPressMenuBlock = ^(NSInteger index) {
  662. switch (index) {
  663. case 0:
  664. NSLog(@"-------复制------");
  665. [weakself copyMessageContent:message.content];
  666. break;
  667. case 1:
  668. NSLog(@"------删除------");
  669. [weakself deleteMyMsg:message.formerMessage];
  670. break;
  671. case 2:
  672. NSLog(@"-----转发-------");
  673. [weakself forwardMsg:@[message.formerMessage] isMultiple:NO];
  674. break;
  675. case 3:
  676. NSLog(@"-----收藏-------");
  677. [weakself addFavorites:message.formerMessage];
  678. break;
  679. case 4:
  680. NSLog(@"------撤回------");
  681. [weakself messageCallback:message.formerMessage];
  682. break;
  683. case 5:
  684. NSLog(@"------多选------");
  685. [weakself batchProcess];
  686. break;
  687. case 6:
  688. NSLog(@"------引用------");
  689. [weakself quoteMessage:message];
  690. break;
  691. case 7:
  692. NSLog(@"------保存------");
  693. [weakself saveFile:message];
  694. break;
  695. // case 8:
  696. // NSLog(@"------文件视频图片重新上传------");
  697. // [weakself resendFile:message];
  698. // break;
  699. case 99:
  700. // NSLog(@"------长按开始------");
  701. [weakself dismissKeyboard];
  702. break;
  703. default:
  704. break;
  705. }
  706. };
  707. cell.batchSelectedStateBlock = ^(BOOL isSelected) {
  708. if (isSelected) {
  709. NSMutableDictionary *dic =message.formerMessage.mutableCopy;
  710. NSString *coontent = dic[@"content"]?:@"";
  711. coontent =[CryptoAES.shareInstance encryptStringL:coontent];
  712. [dic setObject:coontent forKey:@"content"];
  713. [weakself.forwordMsgArray addObject:dic];
  714. }else{
  715. [weakself.forwordMsgArray removeObject:message.formerMessage];
  716. }
  717. NSLog(@"weakself.forwordMsgArray:%@",weakself.forwordMsgArray);
  718. };
  719. cell.avatarTapBlock = ^(ChatMessageModel * _Nonnull message) {
  720. // if (message.isSender) {
  721. // return;
  722. // }
  723. // //前往用户信息页
  724. // UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  725. // FriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"FriendController"];
  726. // friendctr.friendMsg = nil;
  727. // friendctr.friendId = message.fromId;
  728. //
  729. // UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  730. // uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  731. //
  732. // [weakself presentViewController :uiNavC animated:YES completion:nil];
  733. };
  734. [cell setResendMessageBlock:^(ChatMessageModel *message) {
  735. if (message.isUploadFile) {
  736. [weakself resendFile:message];
  737. } else {
  738. [weakself resendMsg:message.formerMessage];
  739. }
  740. }];
  741. return cell;
  742. }
  743. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  744. ChatMessageModel *message = self.messageArray[indexPath.row];
  745. // NSLog(@"heightForRowAtIndexPath-----");
  746. return [chatCellView cellHeightForMessage:message];
  747. }
  748. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
  749. chatCellView * currentCell = (chatCellView *)cell;
  750. ChatMessageModel *message = self.messageArray[indexPath.row];
  751. currentCell.messageModel = message;
  752. // NSLog(@"willDisplayCell-----");
  753. currentCell.batchState = self.isBatchMode;
  754. }
  755. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  756. if(_keybarShow){
  757. [self dismissKeyboard];
  758. return;
  759. }
  760. }
  761. -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
  762. // 计算距离顶部的距离
  763. // CGFloat offsetY = scrollView.contentOffset.y;
  764. // CGFloat contentHeight = scrollView.contentSize.height;
  765. // CGFloat frameHeight = scrollView.frame.size.height;
  766. //// NSLog(@"scrollViewDidScroll:offsetY:%f,contentHeight:%f,frameHeight:%f",offsetY,contentHeight,frameHeight);
  767. // // 预加载阈值(距离顶部300pt时触发)
  768. // CGFloat threshold = 300.0;
  769. //// NSLog(@"scrollViewDidScroll:%f",offsetY);
  770. // if (offsetY > threshold&&!_canloadhistory) {
  771. // _canloadhistory=true;
  772. // _offset =offsetY;
  773. // return;
  774. // }
  775. // if(_offset-offsetY>400){
  776. // _canloadhistoryMore=false;
  777. // }
  778. //
  779. // if(_canloadhistory&&offsetY < threshold){
  780. //// NSLog(@"-----1------1");
  781. // if(!_canloadhistoryMore){
  782. //// NSLog(@"-----1------2");
  783. // _ishistory=true;
  784. // [self loadhistoryData];
  785. // }
  786. // }
  787. }
  788. -(void)saveFile:(ChatMessageModel *)msgMdl{
  789. NSString *localPath =msgMdl.localurl;
  790. if (localPath && [[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
  791. NSLog(@"本地路径");
  792. NSString *fileExtension = [[msgMdl.localurl pathExtension] lowercaseString];
  793. if([self isVideoFile:fileExtension]){
  794. NSURL *fileURL = [NSURL fileURLWithPath:localPath];
  795. [self saveVideoToPhotoLibrary:fileURL];
  796. }
  797. else{
  798. [self saveFileToLibrary:localPath];
  799. }
  800. }
  801. else{
  802. [MBProgressHUD showWithText:@"文件尚未加载完成,请稍后重试"];
  803. }
  804. }
  805. - (BOOL)isVideoFile:(NSString *)fileExtension {
  806. NSArray *videoExtensions = @[@"mp4", @"mov", @"m4v", @"avi", @"mkv", @"flv", @"wmv"];
  807. return [videoExtensions containsObject:fileExtension];
  808. }
  809. - (void)saveVideoToPhotoLibrary:(NSURL *)videoURL {
  810. // 检查 PHPhotoLibrary 的授权状态
  811. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  812. if (status == PHAuthorizationStatusAuthorized) {
  813. // 授权成功,保存视频
  814. [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  815. // 创建资产更改请求
  816. PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
  817. // 可以设置其他属性,如位置信息等
  818. // [assetChangeRequest setLocation:location];
  819. } completionHandler:^(BOOL success, NSError *error) {
  820. if (success) {
  821. NSLog(@"视频保存成功");
  822. dispatch_async(dispatch_get_main_queue(), ^{
  823. [self showNot:@"保存到手机成功"];
  824. });
  825. } else {
  826. NSLog(@"视频保存失败: %@", error.localizedDescription);
  827. }
  828. }];
  829. } else {
  830. // 授权失败或未授权,处理用户未授权的情况
  831. NSLog(@"请在设置中授权访问相册");
  832. }
  833. }];
  834. }
  835. -(void)showNot:(NSString *)str{
  836. [MBProgressHUD showWithText:str];
  837. }
  838. -(void)saveFileToLibrary:(NSString *)fileUrl{
  839. NSURL *fileURL = [NSURL fileURLWithPath:fileUrl];
  840. UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
  841. [documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
  842. }
  843. #pragma mark UITextViewDelegate
  844. - (void)textViewDidChange:(UITextView *)textView {
  845. CGFloat maxHeight = 160;
  846. CGFloat maxWidth = self.view.frame.size.width - 190;
  847. CGSize newSize = [textView sizeThatFits:CGSizeMake(maxWidth, MAXFLOAT)];
  848. if(newSize.height>maxHeight){
  849. _inputView.scrollEnabled = YES; // 允许滚动,出现滚动条
  850. }
  851. else{
  852. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  853. [self movetoBotton];
  854. }
  855. CGFloat height = MAX(40, MIN(maxHeight, newSize.height));
  856. self.bottomViewHeight.constant = height+20;
  857. }
  858. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  859. // 计算新文本的长度
  860. NSInteger newLength = textView.text.length - range.length + text.length;
  861. NSLog(@"shouldChangeTextInRange---");
  862. // 若新文本长度超出最大长度,则不允许输入
  863. if (newLength > 1000) {
  864. [MBProgressHUD showWithText:@"超出最大文本长度,请重新输入"];
  865. if (textView.text.length == 0) {
  866. return NO;
  867. }
  868. // 截取最大长度的文本
  869. NSString *substring = [textView.text substringToIndex:1000];
  870. textView.text = substring;
  871. return NO;
  872. }
  873. if ([text isEqualToString:@"@"] && self.type == 1) {
  874. NSLog(@"用户输入了@符号");
  875. // 可以在这里添加你需要执行的代码
  876. [textView resignFirstResponder];
  877. [self showAtMemberView];
  878. }
  879. if ([text isEqualToString:@""] && self.type == 1) { // 删除操作
  880. // 处理连续删除特殊字符的情况
  881. if (range.length == 1) {
  882. NSRange deleteRange = range;
  883. NSString *deletedChar = [textView.text substringWithRange:deleteRange];
  884. // 如果删除的是连字符,尝试删除整个mention
  885. if ([deletedChar isEqualToString:@"-"]) {
  886. if ([self.inputView deleteMentionAtCursorPosition]) {
  887. return NO;
  888. }
  889. }
  890. }
  891. NSLog(@"1111111");
  892. // 正常删除处理
  893. if ([self.inputView deleteMentionAtCursorPosition]) {
  894. NSLog(@"deleteMentionAtCursorPosition");
  895. return NO;
  896. }
  897. }
  898. return YES;
  899. }
  900. - (void)keyboardWillShow:(NSNotification *)notification {
  901. // 获取键盘的动画持续时间和动画曲线
  902. NSDictionary *userInfo = [notification userInfo];
  903. double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  904. // UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  905. //
  906. // 获取键盘的高度
  907. CGRect keyboardEndFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  908. _keyboardHeight = keyboardEndFrame.size.height;
  909. NSLog(@"_keyboardHeight:%f",_keyboardHeight);
  910. // 根据需要调整视图大小或位置(例如,移动某个视图)
  911. // 示例:将一个视图向下移动以适应键盘高度
  912. _gengduoBt.alpha = 1;
  913. _fasngBt.alpha = 1;
  914. _keybarShow=true;
  915. [UIView animateWithDuration:duration
  916. delay:0
  917. options:UIViewAnimationOptionCurveEaseInOut
  918. animations:^{
  919. self.inputViewBottom.constant = self.keyboardHeight;
  920. [self.view setNeedsLayout];
  921. [self.view layoutIfNeeded];
  922. } completion:^(BOOL finished) {
  923. [self movetoBotton];
  924. }];
  925. }
  926. - (void)keyboardWillHide:(NSNotification *)notification {
  927. // 获取键盘的动画持续时间和动画曲线
  928. NSDictionary *userInfo = [notification userInfo];
  929. double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  930. UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  931. NSLog(@"_keyboardHeight:%f",_keyboardHeight);
  932. [UIView animateWithDuration:duration
  933. delay:0.0
  934. options:(curve << 16)
  935. animations:^{
  936. self.inputViewBottom.constant = 0;
  937. [self.view setNeedsLayout];
  938. [self.view layoutIfNeeded];
  939. } completion:^(BOOL finished) {
  940. [self movetoBotton];
  941. }];
  942. if(_inputView.text.length>0){
  943. _gengduoBt.alpha = 1;
  944. _fasngBt.alpha = 1;
  945. }
  946. else{
  947. _gengduoBt.alpha = 1;
  948. _fasngBt.alpha = 1;
  949. }
  950. _keybarShow=false;
  951. }
  952. -(void)dismissKeyboard{
  953. [self.view endEditing:YES];
  954. }
  955. -(void)fasongwanwenzi{
  956. CGRect newFrame = _inputView.frame;
  957. newFrame.size.height =40;
  958. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  959. _inputView.frame =newFrame;
  960. CGRect viewFrame = _bottonView.frame;
  961. viewFrame.size.height = 62;
  962. if (self.isQuoteMessage) {
  963. self.quoteView.hidden = YES;
  964. CGRect audioBtnFrame = self.yuyinctr.frame;
  965. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y+kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  966. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  967. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y+kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  968. CGRect sendBtnFrame = self.fasngBt.frame;
  969. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y+kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  970. }
  971. if(_keybarShow){
  972. viewFrame.origin.y =self.view.frame.size.height-_keyboardHeight-viewFrame.size.height;
  973. CGRect tframe = self._tableView.frame;
  974. tframe.size.height = viewFrame.origin.y-tframe.origin.y;
  975. self._tableView.frame = tframe;
  976. [self movetoBotton];
  977. }
  978. else{
  979. // 恢复视图原始位置或大小
  980. viewFrame.origin.y = self.view.frame.size.height-viewFrame.size.height-34;
  981. CGRect tframe = self._tableView.frame;
  982. tframe.size.height = viewFrame.origin.y-tframe.origin.y;
  983. self._tableView.frame = tframe;
  984. [self movetoBotton];
  985. }
  986. _bottonView.frame = viewFrame;
  987. }
  988. #pragma mark 发送数据
  989. -(void)sendtextData{
  990. NSLog(@"sendtextData1");
  991. NSString *msg = _inputView.text;
  992. msg = [msg stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  993. msg = [msg stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  994. msg = [msg stringByReplacingOccurrencesOfString:@"\t" withString:@""];
  995. msg = [msg stringByReplacingOccurrencesOfString:@" " withString:@""];
  996. if (msg.length==0) {
  997. NSLog(@"空内容");
  998. return;
  999. }
  1000. [self fasongwanwenzi];
  1001. NSLog(@"sendtextData2");
  1002. NSDictionary * quoteMessage;
  1003. if (self.isQuoteMessage) {
  1004. // NSInteger quoteIndex = [self.messageArray indexOfObject:self.quoteView.model];
  1005. // NSLog(@"quoteIndex:%ld------------",quoteIndex);
  1006. quoteMessage = self.quoteView.model.formerMessage;
  1007. }
  1008. NSString *content= [CryptoAES.shareInstance encryptStringL:_inputView.text];
  1009. // NSLog(@"content:%@",content);
  1010. NSString *strtime = [self getLocalTime];
  1011. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1012. NSDictionary *Lmsgd=@{
  1013. @"messageType":@"0",
  1014. @"chatId":self.chatId,
  1015. @"fromId":self.userId,
  1016. @"fromName":self.username,
  1017. @"fromAvatar":self.useravatar,
  1018. @"content":content,
  1019. @"type":type,
  1020. @"reSend":[NSNumber numberWithBool:false],
  1021. @"extend": @{
  1022. @"atAll":@"false",
  1023. @"atUserIds":@[],
  1024. },
  1025. @"localtime":strtime,
  1026. @"timestamp":strtime,
  1027. @"mine":@"true",
  1028. @"id":strtime,
  1029. };
  1030. NSMutableDictionary * tempMsgDict = [NSMutableDictionary dictionaryWithDictionary:Lmsgd];
  1031. NSMutableDictionary * tempExtandDict = [NSMutableDictionary dictionaryWithDictionary:Lmsgd[@"extend"]];
  1032. if (quoteMessage) {
  1033. [tempExtandDict setObject:quoteMessage forKey:@"quoteMessage"];
  1034. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1035. }
  1036. if (self.atSomeoneArray.count!=0 && self.type == 1) {
  1037. //@单人或者多人参数插入
  1038. NSMutableArray * atUserIdsArray = [NSMutableArray array];
  1039. for (NSDictionary * user in self.atSomeoneArray) {
  1040. [atUserIdsArray addObject:user[@"id"]];
  1041. }
  1042. [tempExtandDict setObject:atUserIdsArray forKey:@"atUserIds"];
  1043. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1044. }
  1045. if ([self.inputView.text containsString:@"@所有人"] && self.type == 1 && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  1046. [tempExtandDict setObject:@"true" forKey:@"atAll"];
  1047. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1048. }
  1049. NSString * tempChatId = self.chatId.mutableCopy;
  1050. [ChatsStore shareInstance].chatId = tempChatId;
  1051. [ChatsStore shareInstance].delegate = self;
  1052. [ChatsStore.shareInstance reciveMsg:tempMsgDict];//预先展示聊天窗信息
  1053. // NSLog(@"sendtextData3");
  1054. NSDictionary *Smsgd=@{
  1055. @"messageType":@"0",
  1056. @"chatId":self.chatId,
  1057. @"fromId":self.userId,
  1058. @"fromName":self.username,
  1059. @"fromAvatar":self.useravatar,
  1060. @"content":content,
  1061. @"type":type,
  1062. @"reSend":[NSNumber numberWithBool:false],
  1063. @"extend": @{
  1064. @"atAll":@"false",
  1065. @"atUserIds":@[],
  1066. },
  1067. @"localtime":strtime,
  1068. @"timestamp":strtime,
  1069. };
  1070. NSMutableDictionary * tempSendMsgDict = [NSMutableDictionary dictionaryWithDictionary:Smsgd];
  1071. NSMutableDictionary * tempSendExtandDict = [NSMutableDictionary dictionaryWithDictionary:Smsgd[@"extend"]];
  1072. if (quoteMessage) {
  1073. [tempSendExtandDict setObject:quoteMessage forKey:@"quoteMessage"];
  1074. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1075. }
  1076. if (self.atSomeoneArray.count!=0 && self.type == 1) {
  1077. //@单人或者多人参数插入
  1078. NSMutableArray * atUserIdsArray = [NSMutableArray array];
  1079. for (NSDictionary * user in self.atSomeoneArray) {
  1080. [atUserIdsArray addObject:user[@"id"]];
  1081. }
  1082. [tempSendExtandDict setObject:atUserIdsArray forKey:@"atUserIds"];
  1083. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1084. }
  1085. if ([self.inputView.text containsString:@"@所有人"] && self.type == 1 && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  1086. [tempSendExtandDict setObject:@"true" forKey:@"atAll"];
  1087. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1088. }
  1089. NSDictionary *sendInfo = @{
  1090. @"code":@"2",
  1091. @"message":tempSendMsgDict,
  1092. };
  1093. NSError *error;
  1094. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1095. if (!jsonData) {
  1096. NSLog(@"Got an error: %@", error);
  1097. } else {
  1098. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1099. //NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1100. // NSLog(@"----发送文字----");
  1101. [GWebSocket.shareInstance sendMsg:jsonString];
  1102. if (self.isQuoteMessage) {
  1103. self.isQuoteMessage = NO;
  1104. }
  1105. _inputView.text=@"";
  1106. }
  1107. if(_keybarShow){
  1108. _gengduoBt.alpha = 1;
  1109. _fasngBt.alpha = 1;
  1110. }
  1111. else{
  1112. _gengduoBt.alpha = 1;
  1113. _fasngBt.alpha = 1;
  1114. }
  1115. }
  1116. -(void)faSongYidu{
  1117. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  1118. // 应用已经解锁并且在前台
  1119. NSLog(@"应用已经解锁并且在前台viewWillDisappear-----1111");
  1120. }
  1121. else{
  1122. return;
  1123. }
  1124. NSString *strtime = [self getLocalTime];
  1125. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1126. NSDictionary *dic =@{
  1127. @"chatId":self.chatId,
  1128. @"userId":self.userId,
  1129. @"type":type,
  1130. @"timestamp":strtime,
  1131. };
  1132. NSDictionary *sendInfo = @{
  1133. @"code":SendCode_READ,
  1134. @"message":dic,
  1135. };
  1136. NSError *error;
  1137. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1138. if (!jsonData) {
  1139. NSLog(@"Got an error: %@", error);
  1140. } else {
  1141. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1142. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1143. // NSLog(@"1--------发送已读时间--------2");
  1144. [GWebSocket.shareInstance sendMsg:jsonString];
  1145. }
  1146. }
  1147. #pragma mark 弹框
  1148. -(void)showBottonView{
  1149. [self dismissKeyboard];
  1150. _markView.frame = self.view.frame;
  1151. CGRect popfram = CGRectMake(0,self.view.frame.size.height-250, self.view.frame.size.width, 250);
  1152. _popView.frame = popfram;
  1153. }
  1154. -(void)hidBottonView{
  1155. CGRect popfram = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, 250);
  1156. _popView.frame = popfram;
  1157. _markView.frame=popfram;
  1158. _markView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  1159. [self movetoBotton];
  1160. }
  1161. -(void)dismissBotton{
  1162. [self hidBottonView];
  1163. }
  1164. #pragma mark 定时服务
  1165. -(void)startTimer{
  1166. if(self.timer==nil){
  1167. self.timer = [NSTimer scheduledTimerWithTimeInterval:10.1 target:self selector:@selector(TimerAction) userInfo:nil repeats:YES];
  1168. [self.timer setFireDate:[NSDate distantPast]];
  1169. [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
  1170. }
  1171. }
  1172. -(void)endTimer{
  1173. [self.timer invalidate];
  1174. self.timer = nil;
  1175. }
  1176. -(void)TimerAction{
  1177. //处理重发事件
  1178. // NSLog(@"self.msgList:%@",self.msgList);
  1179. for(NSDictionary *dis in self.msgList){
  1180. NSString *mine = dis[@"mine"];
  1181. if(mine.boolValue){
  1182. if([dis[@"id"] isEqualToString:dis[@"localtime"]]){
  1183. [self resendMsg:dis.copy];
  1184. }
  1185. }
  1186. }
  1187. }
  1188. -(BOOL)canResend:(NSDictionary *)msg{
  1189. NSLog(@"canResend:%@",msg);
  1190. NSString *localtime = msg[@"localtime"];
  1191. NSString *messageType = msg[@"messageType"];
  1192. if([messageType isEqualToString:MessageType_text]){
  1193. for (NSDictionary *item in self.msgList) {
  1194. NSString *itlocaltime =item[@"localtime"];
  1195. if([localtime isEqualToString:itlocaltime]){
  1196. NSLog(@"canResend2:%@",item);
  1197. if(![item[@"id"] isEqualToString:item[@"localtime"]]){
  1198. return false;
  1199. }
  1200. NSDate *now = [NSDate date];
  1201. NSTimeInterval trt = [now timeIntervalSince1970];
  1202. NSNumber *tt =msg[@"localtime"];
  1203. if((trt-tt.integerValue/1000)>40){
  1204. //发送失败
  1205. NSLog(@"发送失败-------");
  1206. return false;
  1207. }
  1208. }
  1209. }
  1210. }
  1211. else{
  1212. [self fileUploadState:msg];
  1213. return false;
  1214. }
  1215. return YES;
  1216. }
  1217. -(void)fileUploadState:(NSDictionary *)msg{
  1218. NSString *localtime = msg[@"localtime"];
  1219. NSString *messageType = msg[@"messageType"];
  1220. if([messageType isEqualToString:MessageType_file]||[messageType isEqualToString:MessageType_image]||[messageType isEqualToString:MessageType_video]) {
  1221. if([OSSManager.sharedManager isuploadTanck:localtime]){
  1222. return;
  1223. }
  1224. for (NSDictionary *item in self.msgList) {
  1225. NSString *itlocaltime =item[@"localtime"];
  1226. if([localtime isEqualToString:itlocaltime]){
  1227. NSLog(@"canResend2:%@",item);
  1228. if(![item[@"id"] isEqualToString:item[@"localtime"]]){
  1229. return;
  1230. }
  1231. NSDictionary *extend =item[@"extend"];
  1232. NSString *url =extend[@"url"];
  1233. if([url isEqualToString:@""]){
  1234. NSString *savedPath =extend[@"localurl"];
  1235. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1236. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1237. model.fileURL = fileUrl;
  1238. model.filePath = savedPath;
  1239. [self OSSuploadFile:model thrid:localtime];
  1240. NSLog(@"重发文件");
  1241. [self FileReUpload:localtime];
  1242. }
  1243. }
  1244. }
  1245. }
  1246. }
  1247. -(void)FileReUpload:(NSString *)localtime{
  1248. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1249. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1250. if(array){
  1251. if(array.count>0){
  1252. NSDictionary *msg =array[0];
  1253. NSString *msgtype = msg[@"messageType"];
  1254. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  1255. return;
  1256. }
  1257. NSDictionary *extend=msg[@"extend"];
  1258. NSMutableDictionary *mextend = [extend mutableCopy];
  1259. [mextend setObject:[NSNumber numberWithInt:0] forKey:@"fileError"];
  1260. NSMutableDictionary *mmsg = [msg mutableCopy];
  1261. [mmsg setObject:mextend forKey:@"extend"];
  1262. [ChatsStore.shareInstance reciveMsg:mmsg];
  1263. }
  1264. }
  1265. } fail:^(NSString * _Nullable error) {
  1266. ;
  1267. }];
  1268. }
  1269. //重发消息
  1270. -(void)resendMsg:(NSDictionary *)msg{
  1271. if(![self canResend:msg]){
  1272. return;
  1273. }
  1274. NSMutableDictionary *dic = [msg mutableCopy];
  1275. NSString *resend =dic[@"reSend"];
  1276. NSLog(@"resend:%@",[resend class]);
  1277. if (resend.boolValue) {
  1278. return;
  1279. }
  1280. else{
  1281. NSString * str = msg[@"messageType"];
  1282. if (![str isEqualToString:@"0"]) {
  1283. return;
  1284. }
  1285. [dic setObject:[NSNumber numberWithBool:YES] forKey:@"reSend"];
  1286. NSDictionary * dict = dic.copy;
  1287. [ChatsStore.shareInstance reciveMsg:dict];//预先展示聊天窗信息
  1288. [dic setObject:[NSNull null] forKey:@"id"];
  1289. }
  1290. NSDictionary *sendInfo = @{
  1291. @"code":@"2",
  1292. @"message":dic,
  1293. };
  1294. NSError *error;
  1295. // NSLog(@"resendMsg---------:%@",msg[@"localtime"]);
  1296. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1297. if (!jsonData) {
  1298. NSLog(@"Got an error: %@", error);
  1299. } else {
  1300. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1301. [GWebSocket.shareInstance sendMsg:jsonString];
  1302. }
  1303. }
  1304. #pragma mark 上传图片
  1305. -(void)showImagePicker:(NSInteger)state{
  1306. NSLog(@"showImagePicker");
  1307. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  1308. if (status == PHAuthorizationStatusAuthorized) {
  1309. // 已经授权,可以访问相册
  1310. } else {
  1311. // 未授权,请求授权
  1312. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1313. if (status == PHAuthorizationStatusAuthorized) {
  1314. // 用户授权了访问相册
  1315. // 在这里执行相册相关的操作
  1316. } else {
  1317. // 用户拒绝授权
  1318. // 可以提供一些用户指导或提示信息
  1319. return;
  1320. }
  1321. }];
  1322. }
  1323. PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
  1324. if(state==1){
  1325. config.filter = [PHPickerFilter imagesFilter]; // 可以设置过滤器,例如只选择图片或视频等
  1326. }
  1327. else if(state==2){
  1328. config.filter = [PHPickerFilter videosFilter]; // 可以设置过滤器,例如只选择图片或视频等
  1329. }
  1330. config.selectionLimit = 9; // 限制选择数量,设置为1表示只能选择一张图片
  1331. config.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent;
  1332. PHPickerViewController *imagePicker = [[PHPickerViewController alloc] initWithConfiguration:config];
  1333. imagePicker.delegate = self; // 设置代理以接收选择结果
  1334. [self presentViewController:imagePicker animated:YES completion:nil];
  1335. }
  1336. - (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results {
  1337. [picker dismissViewControllerAnimated:YES completion:nil]; // 关闭选择器视图控制器
  1338. if (results.count == 0) {
  1339. return;
  1340. }
  1341. NSMutableArray * fileArray = [NSMutableArray array];
  1342. for (PHPickerResult * result in results) {
  1343. NSItemProvider *itemProvider = result.itemProvider;
  1344. NSString *typeIdentifier = result.itemProvider.registeredTypeIdentifiers.firstObject;
  1345. if ([result.itemProvider canLoadObjectOfClass:[UIImage class]]) {
  1346. [result.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
  1347. if (error) {
  1348. NSLog(@"Error loading file: %@", error);
  1349. return;
  1350. }
  1351. NSLog(@"File URL: %@", url); // 这里就是文件的 URL 路径
  1352. // 你可以使用这个 URL 进行进一步处理,例如读取文件内容或者将其复制到应用沙盒中的其他位置。
  1353. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1354. if(savedPath.length>0){
  1355. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1356. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1357. model.fileURL = fileUrl;
  1358. model.filePath = savedPath;
  1359. [fileArray addObject:model];
  1360. if (fileArray.count==results.count) {
  1361. dispatch_async(dispatch_get_main_queue(), ^{
  1362. [self handleMediaData:fileArray];
  1363. });
  1364. }
  1365. }
  1366. else{
  1367. NSLog(@"-----找不到文件------");
  1368. }
  1369. }];
  1370. }else{
  1371. [result.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
  1372. if (error) {
  1373. NSLog(@"Error loading file: %@", error);
  1374. return;
  1375. }
  1376. NSLog(@"File URL: %@", url); // 这里就是文件的 URL 路径
  1377. // 你可以使用这个 URL 进行进一步处理,例如读取文件内容或者将其复制到应用沙盒中的其他位置。
  1378. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1379. if(savedPath.length>0){
  1380. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1381. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1382. model.fileURL = fileUrl;
  1383. model.filePath = savedPath;
  1384. [fileArray addObject:model];
  1385. if (fileArray.count==results.count) {
  1386. dispatch_async(dispatch_get_main_queue(), ^{
  1387. [self handleMediaData:fileArray];
  1388. });
  1389. }
  1390. }
  1391. else{
  1392. NSLog(@"-----找不到文件------");
  1393. }
  1394. }];
  1395. }
  1396. }
  1397. }
  1398. #pragma mark - 写入方法
  1399. - (NSString *)saveImageToSandbox:(UIImage *)image {
  1400. // 获取沙盒Documents目录
  1401. NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1402. // 生成唯一文件名
  1403. NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID] UUIDString]];
  1404. NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];
  1405. // 将图片转换为JPEG格式数据
  1406. NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
  1407. // 写入文件
  1408. BOOL success = [imageData writeToFile:filePath atomically:YES];
  1409. if (success) {
  1410. NSLog(@"图片保存成功,路径: %@", filePath);
  1411. return filePath;
  1412. } else {
  1413. NSLog(@"图片保存失败");
  1414. return nil;
  1415. }
  1416. }
  1417. - (NSString *)saveVideoDataToDocumentsDirectory:(NSData *)videoData {
  1418. // 1. 生成唯一文件名
  1419. NSString *fileName = [NSString stringWithFormat:@"%@.mp4", [[NSUUID UUID] UUIDString]];
  1420. // 2. 获取Documents目录路径
  1421. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1422. NSString *documentsDirectory = [paths firstObject];
  1423. NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
  1424. // 3. 写入数据
  1425. NSError *writeError;
  1426. [videoData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
  1427. if (writeError) {
  1428. NSLog(@"Error writing video data: %@", writeError.localizedDescription);
  1429. return nil;
  1430. }
  1431. return filePath;
  1432. }
  1433. - (NSString *)saveFileToDocumentsDirectory:(NSURL *)fromePath {
  1434. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1435. NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:fromePath.lastPathComponent]; // 目标文件路径
  1436. NSFileManager *fileManager = [NSFileManager defaultManager];
  1437. NSError *error = nil;
  1438. if([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]){
  1439. return destinationPath;
  1440. }
  1441. else{
  1442. BOOL success = [fileManager copyItemAtPath:fromePath.path toPath:destinationPath error:&error];
  1443. if (success) {
  1444. NSLog(@"文件成功复制到本地");
  1445. return destinationPath;
  1446. } else {
  1447. NSLog(@"文件复制失败: %@", error.localizedDescription);
  1448. return @"";
  1449. }
  1450. }
  1451. }
  1452. #pragma mark -文件选择和处理
  1453. -(void)showfilePicker{
  1454. // 创建文档选择器
  1455. NSArray<UTType *> *contentTypes = @[UTTypeItem];
  1456. UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:contentTypes
  1457. asCopy:YES];
  1458. documentPicker.allowsMultipleSelection = YES;
  1459. documentPicker.delegate = self;
  1460. [self presentViewController:documentPicker animated:YES completion:nil];
  1461. }
  1462. #pragma mark - 文件选择回调 UIDocumentPickerDelegate
  1463. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
  1464. // 用户选择了一个或多个文件,处理这些文件
  1465. if (urls.count > 9) {
  1466. //选择文件最多 9 个
  1467. [MBProgressHUD showWithText:@"一次最多上傳 9 個檔案"];
  1468. }
  1469. NSMutableArray * fileArray = [NSMutableArray array];
  1470. for (NSURL * url in urls) {
  1471. if ([urls indexOfObject:url] > 9) {
  1472. break;
  1473. }
  1474. NSLog(@"url:%@",url);
  1475. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1476. if(savedPath.length>0){
  1477. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1478. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1479. model.fileURL = fileUrl;
  1480. model.filePath = savedPath;
  1481. [fileArray addObject:model];
  1482. }
  1483. }
  1484. dispatch_async(dispatch_get_main_queue(), ^{
  1485. [self handleMediaData:fileArray];
  1486. });
  1487. }
  1488. #pragma mark 批量处理文件上传
  1489. - (void)handleMediaData:(NSArray *)mediaArray{
  1490. // NSMutableArray * tempArray = [NSMutableArray array];
  1491. NSArray *sorArray = [self fileArraysort:mediaArray];
  1492. for (ChatFileModel * model in sorArray) {
  1493. NSString *strtime = [self getLocalTime];
  1494. [self uploadFile:[NSString stringWithFormat:@"%@",model.fileURL] fpath:model.filePath state:1 act:1 localtime:strtime];
  1495. [self OSSuploadFile:model thrid:strtime];
  1496. }
  1497. }
  1498. -(void)OSSuploadFile:(ChatFileModel *)model thrid:(NSString *)strtime{
  1499. NSString * tempChatId = self.chatId.mutableCopy;
  1500. [ChatsStore shareInstance].chatId = tempChatId;
  1501. [ChatsStore shareInstance].delegate = self;
  1502. // 断点续传
  1503. [OSSManager.sharedManager asyncResumableUploadFile:model.fileURL.lastPathComponent localFilePath:model.filePath thrid:strtime];
  1504. }
  1505. -(void)stateChange:(NSDictionary *)changeMsg{
  1506. dispatch_main_async_safe(^{
  1507. NSString *loacaltime = changeMsg[@"thrid"];
  1508. NSString *pcent = changeMsg[@"pcent"];
  1509. NSString *state = changeMsg[@"state"];
  1510. NSLog(@"uploadProgress: %@",pcent);
  1511. if([state isEqualToString:@"1"]){
  1512. [self Ossupdatajidu:loacaltime uploadProgress:pcent.intValue];
  1513. }
  1514. })
  1515. }
  1516. -(void)resendFile:(ChatMessageModel *)msg{
  1517. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)msg.localtime];
  1518. NSString *loaclFile = [NSString stringWithFormat:@"%@",msg.localurl];
  1519. if(![[NSFileManager defaultManager] fileExistsAtPath:loaclFile]){
  1520. [MBProgressHUD showWithText:@"文件不存在,請重新選擇"];
  1521. return;
  1522. }
  1523. NSURL * fileUrl = [NSURL fileURLWithPath:loaclFile];
  1524. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1525. model.fileURL = fileUrl;
  1526. model.filePath = loaclFile;
  1527. [self OSSuploadFile:model thrid:strtime];
  1528. }
  1529. -(void)uploadFile:(NSString *)url fpath:(NSString *)path state:(NSInteger)state act:(NSInteger)act localtime:(NSString *)localtime{
  1530. NSURL *filePath;
  1531. if([url containsString:@"http"]){
  1532. filePath=[NSURL URLWithString:url]; //
  1533. }
  1534. else{
  1535. NSString *filestr = [[OSSManager sharedManager] fullUploadURLByAppendPath:url];
  1536. filePath=[NSURL URLWithString:filestr]; //
  1537. }
  1538. NSString *content=@"【文件】";
  1539. NSString *messageType=MessageType_file;
  1540. NSDictionary *extend;
  1541. if(state==1){//文件类消息
  1542. NSString *kzm = filePath.pathExtension;
  1543. kzm=[kzm lowercaseString];
  1544. if([kzm isEqualToString:@"png"]||[kzm isEqualToString:@"jpg"]||[kzm isEqualToString:@"jpeg"]||[kzm isEqualToString:@"bmp"]){
  1545. content=@"【图片】";
  1546. messageType=MessageType_image;
  1547. }
  1548. if([kzm isEqualToString:@"mp4"]||[kzm isEqualToString:@"avi"]||[kzm isEqualToString:@"wmv"]||[kzm isEqualToString:@"mov"]||[kzm isEqualToString:@"mpeg"]){
  1549. content=@"【视频】";
  1550. messageType=MessageType_video;
  1551. }
  1552. }
  1553. content= [CryptoAES.shareInstance encryptStringL:content];
  1554. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1555. NSDictionary *msgt;
  1556. NSDictionary *msgd;
  1557. if(act==1){
  1558. extend=@{
  1559. @"url":@"",
  1560. @"fileName":filePath.lastPathComponent,
  1561. @"localurl":path,
  1562. @"fileError":[NSNumber numberWithInt:0]
  1563. };
  1564. msgt=@{
  1565. @"messageType":messageType,
  1566. @"chatId":self.chatId,
  1567. @"fromId":self.userId,
  1568. @"fromName":self.username,
  1569. @"fromAvatar":self.useravatar,
  1570. @"content":content,
  1571. @"type":type,
  1572. @"reSend": [NSNumber numberWithBool:false],
  1573. @"extend": extend,
  1574. @"localtime":localtime,
  1575. @"timestamp":localtime,
  1576. @"mine":[NSNumber numberWithBool:YES],
  1577. @"id":localtime,
  1578. };
  1579. msgd=@{
  1580. @"messageType":messageType,
  1581. @"chatId":self.chatId,
  1582. @"fromId":self.userId,
  1583. @"fromName":self.username,
  1584. @"fromAvatar":self.useravatar,
  1585. @"content":content,
  1586. @"type":type,
  1587. @"reSend": [NSNumber numberWithBool:false],
  1588. @"extend": extend,
  1589. @"localtime":localtime,
  1590. @"timestamp":localtime,
  1591. @"mine":[NSNumber numberWithBool:YES],
  1592. @"id":@"",
  1593. };
  1594. NSString * tempChatId = self.chatId.mutableCopy;
  1595. [ChatsStore shareInstance].chatId = tempChatId;
  1596. [ChatsStore shareInstance].delegate = self;
  1597. [ChatsStore.shareInstance reciveMsg:msgt];
  1598. NSDictionary *sendInfo = @{
  1599. @"code":@"2",
  1600. @"message":msgd,
  1601. };
  1602. NSError *error;
  1603. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1604. if (!jsonData) {
  1605. NSLog(@"Got an error: %@", error);
  1606. } else {
  1607. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1608. // NSLog(@"%@", jsonString);
  1609. NSLog(@"----发送文件消息----%@",localtime);
  1610. //self.ismyTurn = YES;
  1611. //[GWebSocket.shareInstance sendMsg:jsonString];
  1612. }
  1613. [self movetoBotton];
  1614. }
  1615. if(act==2){
  1616. if(url){
  1617. [self uploadFileSucc:url localtime:localtime];
  1618. }
  1619. else{
  1620. }
  1621. }
  1622. }
  1623. -(void)uploadFileSucc:(NSString *)url localtime:(NSString *)localtime{
  1624. if(![url containsString:@"http"]){
  1625. url = [[OSSManager sharedManager] fullUploadURLByAppendPath:url];
  1626. }
  1627. NSURL *filePath = [NSURL URLWithString:url];
  1628. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1629. // NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1630. if(array){
  1631. if(array.count>0){
  1632. NSDictionary *msg =array[0];
  1633. NSDictionary *extend=msg[@"extend"];
  1634. NSMutableDictionary *mextend = [extend mutableCopy];
  1635. [mextend setObject:url forKey:@"url"];
  1636. [mextend setObject:filePath.lastPathComponent forKey:@"fileName"];
  1637. NSMutableDictionary *mmsg = [msg mutableCopy];
  1638. [mmsg setObject:mextend forKey:@"extend"];
  1639. [mmsg setObject:@"" forKey:@"id"];
  1640. NSDictionary *sendInfo = @{
  1641. @"code":@"2",
  1642. @"message":mmsg,
  1643. };
  1644. NSError *error;
  1645. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1646. if (!jsonData) {
  1647. NSLog(@"Got an error: %@", error);
  1648. } else {
  1649. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1650. // NSLog(@"%@", jsonString);
  1651. NSLog(@"----发送文件消息2----%@",localtime);
  1652. // self.ismyTurn = YES;
  1653. [GWebSocket.shareInstance sendMsg:jsonString];
  1654. }
  1655. }
  1656. }
  1657. } fail:^(NSString * _Nullable error) {
  1658. ;
  1659. }];
  1660. }
  1661. -(void)uploadFilefail:(NSString *)localtime{
  1662. NSLog(@"uploadFilefail----:%@",localtime);
  1663. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1664. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1665. if(array){
  1666. if(array.count>0){
  1667. NSDictionary *msg =array[0];
  1668. NSString *msgtype = msg[@"messageType"];
  1669. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  1670. return;
  1671. }
  1672. NSString *strtime = [self getLocalTime];
  1673. NSDictionary *extend=msg[@"extend"];
  1674. NSMutableDictionary *mextend = [extend mutableCopy];
  1675. [mextend setObject:@"" forKey:@"url"];
  1676. [mextend setObject:@"" forKey:@"fileName"];
  1677. [mextend setObject:[NSNumber numberWithInt:1] forKey:@"fileError"];
  1678. NSMutableDictionary *mmsg = [msg mutableCopy];
  1679. [mmsg setObject:mextend forKey:@"extend"];
  1680. [mmsg setObject:strtime forKey:@"timestamp"];
  1681. [ChatsStore.shareInstance reciveMsg:mmsg];
  1682. NSDictionary *sendInfo = @{
  1683. @"code":@"2",
  1684. @"message":mmsg,
  1685. };
  1686. NSError *error;
  1687. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1688. if (!jsonData) {
  1689. NSLog(@"Got an error: %@", error);
  1690. } else {
  1691. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1692. // NSLog(@"%@", jsonString);
  1693. NSLog(@"----发送文件失败消息2----%@",localtime);
  1694. // self.ismyTurn = YES;
  1695. //[GWebSocket.shareInstance sendMsg:jsonString];
  1696. }
  1697. }
  1698. }
  1699. } fail:^(NSString * _Nullable error) {
  1700. ;
  1701. }];
  1702. }
  1703. -(void)Ossupdatajidu:(NSString *)localtime uploadProgress:(NSInteger )Progress{
  1704. [self updateProgress:Progress localtime:localtime];
  1705. }
  1706. - (void)updateProgress:(NSInteger )Progress localtime:(NSString *)localtime {
  1707. for (chatCellView *cell in self._tableView.visibleCells) {
  1708. ChatMessageModel *message = cell.messageModel;
  1709. if(message.localtime==localtime.integerValue){
  1710. [cell fileUploadProgressDidChanged:Progress localtime:localtime.integerValue];
  1711. }
  1712. }
  1713. }
  1714. #pragma mark 录音发送
  1715. -(void)longTarget{
  1716. NSLog(@"longTarget----------");
  1717. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeGreen).CGColor;
  1718. [_AVRecordBt setTitle:@" 松开 发送" forState:UIControlStateNormal];
  1719. NSDate *now = [NSDate date];
  1720. NSTimeInterval trt = [now timeIntervalSince1970];
  1721. NSInteger time = trt*1000;
  1722. _AudiofileName = [NSString stringWithFormat:@"%ld.mp4",(long)time];
  1723. _AudiofilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:_AudiofileName];
  1724. NSError *error = nil;
  1725. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  1726. [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
  1727. //[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
  1728. [audioSession setActive:YES error:nil];
  1729. NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  1730. [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
  1731. [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; //采样率
  1732. [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
  1733. [recordSetting setValue:[NSNumber numberWithInt: AVAudioQualityMedium] forKey:AVEncoderAudioQualityKey];
  1734. NSURL *fileURL = [NSURL fileURLWithPath:_AudiofilePath];
  1735. _recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:recordSetting error:&error];
  1736. if (error) {
  1737. NSLog(@"Error creating recorder: %@", error);
  1738. } else {
  1739. [_recorder prepareToRecord];
  1740. [_recorder record];
  1741. }
  1742. _rcdL=0;
  1743. self.heatBeat = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(heartbeatAction) userInfo:nil repeats:YES];
  1744. [self.heatBeat setFireDate:[NSDate distantPast]];
  1745. [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
  1746. }
  1747. -(void)heartbeatAction{
  1748. if(_rcdL==60){
  1749. [_recorder stop];
  1750. _recorder=nil;
  1751. return;
  1752. }
  1753. _rcdL=_rcdL+1;
  1754. }
  1755. -(void)UpInside{
  1756. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeDark2).CGColor;
  1757. [_AVRecordBt setTitle:@" 按住 说话" forState:UIControlStateNormal];
  1758. NSLog(@"UpInside----------");
  1759. [_recorder stop];
  1760. _recorder=nil;
  1761. NSURL *yuanfileURL = [NSURL fileURLWithPath:_AudiofilePath];
  1762. if(_rcdL<2){//语音太短
  1763. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1764. [self.heatBeat invalidate];
  1765. self.heatBeat = nil;
  1766. [MBProgressHUD showWithText:@"語音太短"];
  1767. return;
  1768. }
  1769. NSLog(@"_AudiofilePath:%@",_AudiofilePath);
  1770. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1771. NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:yuanfileURL.lastPathComponent]; // 目标文件路径
  1772. NSFileManager *fileManager = [NSFileManager defaultManager];
  1773. NSError *error = nil;
  1774. BOOL success = [fileManager copyItemAtPath:_AudiofilePath toPath:destinationPath error:&error];
  1775. if (success) {
  1776. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1777. NSLog(@"文件成功复制到本地");
  1778. } else {
  1779. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1780. NSLog(@"文件复制失败: %@", error.localizedDescription);
  1781. [MBProgressHUD showWithText:@"語音發送異常請重試"];
  1782. return;
  1783. }
  1784. NSLog(@"destinationPath:%@",destinationPath);
  1785. NSURL *fileURL = [NSURL fileURLWithPath:destinationPath];
  1786. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileURL];
  1787. model.fileURL = fileURL;
  1788. model.filePath = destinationPath;
  1789. NSString *strtime = [self getLocalTime];
  1790. [self sendYuyinMsg:model.fileURL.lastPathComponent filePth:destinationPath localtime:strtime state:0];
  1791. [self OSSuploadFile:model thrid:strtime];
  1792. [self.heatBeat invalidate];
  1793. self.heatBeat = nil;
  1794. }
  1795. -(void)sendYuyinMsg:(NSString *)fileName filePth:(NSString *)filePtah localtime:(NSString *)loacaltime state:(NSInteger)index{
  1796. NSString *filePath;
  1797. if([fileName containsString:@"http"]){
  1798. filePath=fileName;
  1799. }
  1800. else{
  1801. filePath = [[OSSManager sharedManager] fullUploadURLByAppendPath:fileName];
  1802. }
  1803. NSString *content=@"【语音】";
  1804. NSString *messageType=[NSString stringWithFormat:@"%@",MessageType_voice];
  1805. content= [CryptoAES.shareInstance encryptStringL:content];
  1806. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1807. NSString *localId =loacaltime;
  1808. if(index==1){
  1809. localId=@"";
  1810. }
  1811. NSDictionary *dic =@{
  1812. @"id":localId,
  1813. @"messageType":messageType,
  1814. @"chatId":self.chatId,
  1815. @"fromId":self.userId,
  1816. @"fromName":self.username,
  1817. @"fromAvatar":self.useravatar,
  1818. @"reSend":[NSNumber numberWithBool:false],
  1819. @"content":content,
  1820. @"type":type,
  1821. @"localtime":loacaltime,
  1822. @"timestamp":loacaltime,
  1823. @"mine":[NSNumber numberWithBool:YES],
  1824. @"extend":@{
  1825. @"url":@"",
  1826. @"time":[NSString stringWithFormat:@"%ld",self->_rcdL],
  1827. @"localurl":filePtah
  1828. }
  1829. };
  1830. if(index==0){
  1831. [ChatsStore.shareInstance reciveMsg:dic];
  1832. }
  1833. NSDictionary *sendInfo = @{
  1834. @"code":@"2",
  1835. @"message":dic,
  1836. };
  1837. NSError *error;
  1838. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1839. if (!jsonData) {
  1840. NSLog(@"Got an error: %@", error);
  1841. } else {
  1842. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1843. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1844. NSLog(@"----发送语音----");
  1845. if(index==1){
  1846. [GWebSocket.shareInstance sendMsg:jsonString];
  1847. }
  1848. }
  1849. }
  1850. -(void)showWebRtcVidio:(NSInteger)state{
  1851. if(self.type==1){
  1852. [MBProgressHUD showWithText:@"群聊暂时不支持该功能"];
  1853. return;
  1854. }
  1855. BOOL audioOnly=YES;
  1856. if(state==4){
  1857. audioOnly = YES;
  1858. }
  1859. else{
  1860. audioOnly = NO;
  1861. }
  1862. [[AppDelegate sharedInstance] startJSCall:self.chatId room:@"" isCaller:YES audioOnly:audioOnly];
  1863. }
  1864. #pragma mark take photo or video
  1865. - (void)takePhoto{
  1866. // 检查设备是否支持相机
  1867. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  1868. CameraViewController *cameraVC = [[CameraViewController alloc] init];
  1869. cameraVC.modalPresentationStyle = UIModalPresentationFullScreen;
  1870. [self presentViewController:cameraVC animated:YES completion:nil];
  1871. weakSelf(self);
  1872. cameraVC.takePhotoFinishBlock = ^(UIImage * _Nonnull image) {
  1873. // 保存图片到本地
  1874. NSString *savedPath = [self saveImageToSandbox:image];
  1875. dispatch_async(dispatch_get_main_queue(), ^{
  1876. // 4. 更新UI或处理保存结果
  1877. if (savedPath) {
  1878. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1879. NSString *strtime = [self getLocalTime];
  1880. //展示自己发的本地图片
  1881. [self uploadFile:[NSString stringWithFormat:@"%@",fileUrl] fpath:savedPath state:1 act:1 localtime:strtime];
  1882. [FileNetApi uploadWithFilePath:fileUrl thrid:strtime progress:^(NSString *_Nullable thrid,NSProgress * _Nullable uploadProgress) {
  1883. } succ:^(int code,NSString *_Nullable thrid, NSDictionary * _Nullable dis) {
  1884. NSString *reCode =dis[@"code"];
  1885. if(reCode.intValue==200){
  1886. NSLog(@"上传成功:%@",dis[@"url"]);
  1887. [weakself uploadFile:dis[@"url"] fpath:savedPath state:1 act:2 localtime:thrid];
  1888. }
  1889. else{
  1890. NSLog(@"上传失败");
  1891. }
  1892. } fail:^(NSString *_Nullable thrid,NSError * _Nonnull error) {
  1893. NSLog(@"上传失败");
  1894. }];
  1895. } else {
  1896. NSLog(@"图片保存失败");
  1897. }
  1898. });
  1899. };
  1900. cameraVC.takeVideoFinishBlock = ^(NSURL * _Nonnull videoUrl) {
  1901. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:videoUrl];
  1902. // ChatFileModel * model = [[ChatFileModel alloc] initWithName:[FileInfoUtils getFileNameWithURL:videoUrl] size:[FileInfoUtils getFileSizeStringWithURL:videoUrl error:nil] isOversize:[FileInfoUtils isFileGreaterThan100MB:videoUrl error:nil]];
  1903. model.fileURL = videoUrl;
  1904. model.filePath = [videoUrl path];
  1905. // [weakself handleMediaData:@[model]];
  1906. dispatch_async(dispatch_get_main_queue(), ^{
  1907. [weakself handleMediaData:@[model]];
  1908. });
  1909. };
  1910. } else {
  1911. NSLog(@"设备不支持相机");
  1912. [MBProgressHUD showWithText:@"设备不支持相机"];
  1913. }
  1914. }
  1915. #pragma mark menu Actoin
  1916. - (void)copyMessageContent:(NSString *)content{
  1917. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1918. pasteboard.string = content;
  1919. [MBProgressHUD showWithText:NSLocalizedString(@"cellact-copysuccese", @"")];
  1920. }
  1921. - (void)addFavorites:(NSDictionary *)dict{
  1922. NSLog(@"----收藏的消息:%@",dict);
  1923. NSMutableDictionary * favoritesDict = [dict mutableCopy];
  1924. NSString *extend = @"";
  1925. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:favoritesDict[@"extend"] options:0 error:nil];
  1926. if (!jsonData) {
  1927. NSLog(@"Got an error:");
  1928. } else {
  1929. extend = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1930. }
  1931. [favoritesDict setValue:extend forKey:@"extend"];
  1932. [UserNetApi addFavorites:favoritesDict succ:^(int code, NSDictionary * _Nullable res) {
  1933. // NSLog(@"------result:%@",res);
  1934. NSString *ecode = res[@"code"];
  1935. if(ecode.intValue==200){
  1936. if ([res jk_hasKey:@"msg"] && ![res[@"msg"] isKindOfClass:NSNull.class]) {
  1937. [MBProgressHUD showWithText:res[@"msg"]];
  1938. }
  1939. }
  1940. else{
  1941. [MBProgressHUD showWithText:NSLocalizedString(@"AppLock_fail", @"收藏失败")];
  1942. }
  1943. } fail:^(NSError * _Nonnull error) {
  1944. NSLog(@"error:%@",error);
  1945. }];
  1946. }
  1947. - (void)deleteMyMsg:(NSDictionary *)dict{
  1948. NSMutableDictionary * msgDict = [NSMutableDictionary dictionaryWithDictionary:dict];
  1949. [msgDict setValue:@"12" forKey:@"messageType"];
  1950. [msgDict setValue:@"删除了一条消息" forKey:@"content"];
  1951. [ChatsStore.shareInstance reciveMsg:msgDict];
  1952. [ChatListStore.shareInstance reciveMsg:msgDict];
  1953. // [self cutDataSource:@[dict]];
  1954. // [ChatsStore.shareInstance deleteMyLocalMsg:dict];
  1955. }
  1956. //转发
  1957. - (void)forwardMsg:(NSArray *)msgArray isMultiple:(BOOL)isMultiple{
  1958. // [MBProgressHUD showWithText:@"功能待完善"];
  1959. // return;
  1960. ForwardViewController * forwordVc = [[ForwardViewController alloc] init];
  1961. forwordVc.fromChatId = self.chatId;
  1962. forwordVc.isMultiple = isMultiple;
  1963. forwordVc.msgArray = msgArray;
  1964. forwordVc.userName = self.username;
  1965. forwordVc.userAvatar = self.useravatar;
  1966. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:forwordVc];
  1967. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  1968. [self presentViewController:navi animated:YES completion:nil];
  1969. }
  1970. - (void)batchProcess{
  1971. self.isBatchMode = YES;
  1972. [UIView animateWithDuration:0.5 animations:^{
  1973. self.batchView.frame = CGRectMake(0, SCREEN_HEIGHT-SCREEN_X_BTM-64, SCREEN_WIDTH, SCREEN_X_BTM+64);
  1974. }];
  1975. weakSelf(self);
  1976. __weak typeof(self.batchView) weakView = self.batchView;
  1977. self.batchView.indexOfBatchClicked = ^(NSInteger index) {
  1978. weakself.isBatchMode = NO;
  1979. if (index == 0) {//关闭
  1980. }else if (index == 1) {
  1981. //合并
  1982. if (weakself.forwordMsgArray.count == 0) {
  1983. [MBProgressHUD showWithText:@"请选择转发的消息"];
  1984. return;
  1985. }
  1986. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  1987. [weakself forwardMsg:tempForwardArray isMultiple:YES];
  1988. [weakself.forwordMsgArray removeAllObjects];
  1989. }else if (index == 2) {
  1990. //逐条
  1991. if (weakself.forwordMsgArray.count == 0) {
  1992. [MBProgressHUD showWithText:@"请选择转发的消息"];
  1993. return;
  1994. }
  1995. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  1996. [weakself forwardMsg:tempForwardArray isMultiple:NO];
  1997. [weakself.forwordMsgArray removeAllObjects];
  1998. }else if (index == 3) {
  1999. //删除
  2000. if (weakself.forwordMsgArray.count == 0) {
  2001. [MBProgressHUD showWithText:@"请选择删除的消息"];
  2002. return;
  2003. }
  2004. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  2005. for (NSDictionary * msg in tempForwardArray) {
  2006. [weakself deleteMyMsg:msg];
  2007. }
  2008. [weakself.forwordMsgArray removeAllObjects];
  2009. }
  2010. [UIView animateWithDuration:0.5 animations:^{
  2011. weakView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_X_BTM+64);
  2012. }];
  2013. [weakself.forwordMsgArray removeAllObjects];
  2014. [weakself._tableView reloadData];
  2015. };
  2016. [self._tableView reloadData];
  2017. }
  2018. - (void)messageCallback:(NSDictionary *)dict{
  2019. // [MBProgressHUD showWithText:@"功能待完善"];
  2020. // return;
  2021. NSMutableDictionary * msgDict = [NSMutableDictionary dictionaryWithDictionary:dict];
  2022. NSDate *now = [NSDate date];
  2023. NSTimeInterval trt = [now timeIntervalSince1970];
  2024. NSInteger time = trt*1000;
  2025. [msgDict setValue:@"11" forKey:@"messageType"];
  2026. [msgDict setValue:@"撤回了一条消息" forKey:@"content"];
  2027. [msgDict setValue:[NSString stringWithFormat:@"%ld",time] forKey:@"id"];
  2028. // self.msgList = [ChatsStore.shareInstance replaydisData:[msgDict copy] inarray:self.msgList];
  2029. [ChatsStore.shareInstance reciveMsg:[msgDict copy]];//预先展示聊天窗信息
  2030. [ChatListStore.shareInstance reciveMsg:msgDict];
  2031. NSLog(@"撤回---:%@",msgDict);
  2032. NSDictionary *sendInfo = @{
  2033. @"code":@"2",
  2034. @"message":msgDict,
  2035. };
  2036. NSError *error;
  2037. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  2038. if (!jsonData) {
  2039. NSLog(@"Got an error: %@", error);
  2040. } else {
  2041. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  2042. //NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  2043. NSLog(@"----撤回消息----");
  2044. [GWebSocket.shareInstance sendMsg:jsonString];
  2045. }
  2046. [self ifisfileMsg:dict];
  2047. }
  2048. //撤回文件消息,同时取消上传
  2049. -(void)ifisfileMsg:(NSDictionary *)msg{
  2050. NSString *messageType = msg[@"messageType"];
  2051. if ([messageType isEqualToString:MessageType_file]||[messageType isEqualToString:MessageType_video]||[messageType isEqualToString:MessageType_image]) {
  2052. NSString *lcotime = msg[@"localtime"];
  2053. [FileNetApi stopUploadTanck:lcotime];
  2054. }
  2055. }
  2056. - (void)quoteMessage:(ChatMessageModel *)message{
  2057. if (self.isQuoteMessage) {
  2058. self.quoteView.model = message;
  2059. [self.inputView becomeFirstResponder];
  2060. return;
  2061. }
  2062. self.isQuoteMessage = YES;
  2063. self.quoteView.model = message;
  2064. self.quoteView.hidden = NO;
  2065. CGRect buttonViewFrame = self.bottonView.frame;
  2066. self.bottonView.frame = CGRectMake(buttonViewFrame.origin.x, buttonViewFrame.origin.y-kQuoteViewHeight, buttonViewFrame.size.width, buttonViewFrame.size.height+kQuoteViewHeight);
  2067. // CGRect inputViewFrame = self.inputView.frame;
  2068. // self.inputView.frame = CGRectMake(inputViewFrame.origin.x, inputViewFrame.origin.y-kQuoteViewHeight, inputViewFrame.size.width, inputViewFrame.size.height);
  2069. CGRect audioBtnFrame = self.yuyinctr.frame;
  2070. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y-kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  2071. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  2072. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y-kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  2073. CGRect sendBtnFrame = self.fasngBt.frame;
  2074. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y-kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  2075. [self.inputView becomeFirstResponder];
  2076. }
  2077. - (void)closeQuoteView{
  2078. self.isQuoteMessage = NO;
  2079. self.quoteView.hidden = YES;
  2080. CGRect buttonViewFrame = self.bottonView.frame;
  2081. self.bottonView.frame = CGRectMake(buttonViewFrame.origin.x, buttonViewFrame.origin.y+kQuoteViewHeight, buttonViewFrame.size.width, buttonViewFrame.size.height-kQuoteViewHeight);
  2082. self.inputView.frame = CGRectMake(54, 10, self.view.frame.size.width - 180, 40);
  2083. CGRect audioBtnFrame = self.yuyinctr.frame;
  2084. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y+kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  2085. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  2086. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y+kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  2087. CGRect sendBtnFrame = self.fasngBt.frame;
  2088. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y+kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  2089. CGRect tframe = self._tableView.frame;
  2090. tframe.size.height = self.bottonView.frame.origin.y-tframe.origin.y;
  2091. self._tableView.frame = tframe;
  2092. [self movetoBotton];
  2093. }
  2094. - (void)cutDataSource:(NSArray *)msgArray{
  2095. NSMutableArray * indexPathArray = [NSMutableArray array];
  2096. NSMutableArray * tempArray = [NSMutableArray arrayWithArray:self.messageArray];
  2097. for (NSDictionary * msg in msgArray) {
  2098. for (ChatMessageModel * message in tempArray) {
  2099. if ([message.formerMessage[@"id"] isEqualToString:msg[@"id"]]) {
  2100. NSInteger index = [tempArray indexOfObject:message];
  2101. [self.messageArray removeObjectAtIndex:index];
  2102. NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
  2103. [indexPathArray addObject:deleteIndexPath];
  2104. }
  2105. }
  2106. }
  2107. [CATransaction begin];
  2108. [CATransaction setDisableActions:YES];
  2109. [self._tableView beginUpdates];
  2110. [self._tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
  2111. [self._tableView endUpdates];
  2112. [CATransaction commit];
  2113. }
  2114. #pragma mark @相关
  2115. - (void)showAtMemberView{
  2116. ChatAtMemberView * atView = [[ChatAtMemberView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-200)];
  2117. atView.memberArray = [ChatsStore shareInstance].groupUserList;
  2118. if (self.groupInfo && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  2119. atView.isGroupMaster = YES;
  2120. }else{
  2121. atView.isGroupMaster = NO;
  2122. }
  2123. //[atView jk_setRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:10.f];
  2124. PopupView * popup = [[PopupView alloc] init];
  2125. popup.customView = atView;
  2126. popup.position = PopupPositionBottom;
  2127. popup.animationType = PopupAnimationTypeFromBottom; // 从下往上动画
  2128. popup.dismissOnBackgroundTap = YES; // 点击背景关闭
  2129. popup.containerType = PopupContainerTypeWindow; // 添加到window
  2130. [popup showInView:self.view];
  2131. weakSelf(self);
  2132. atView.closeAtViewBlock = ^{
  2133. [popup dismiss];
  2134. };
  2135. atView.atMembersBlock = ^(NSArray * _Nonnull selectedArray) {
  2136. [popup dismiss];
  2137. for (int i = 0; i < selectedArray.count; i++) {
  2138. NSDictionary * member = selectedArray[i];
  2139. [weakself.inputView insertText:[NSString stringWithFormat:@"@%@ ",member[@"name"]]];
  2140. }
  2141. [weakself.atSomeoneArray addObjectsFromArray:selectedArray];
  2142. [weakself.inputView becomeFirstResponder];
  2143. };
  2144. atView.atSingleMemberBlock = ^(NSDictionary * _Nonnull member) {
  2145. [popup dismiss];
  2146. [weakself.inputView insertText:[NSString stringWithFormat:@"@%@ ",member[@"name"]]];
  2147. [weakself.atSomeoneArray addObject:member];
  2148. [weakself.inputView becomeFirstResponder];
  2149. };
  2150. atView.atEveryoneBlock = ^{
  2151. [popup dismiss];
  2152. [weakself.inputView insertText:@"@所有人 "];
  2153. [weakself.inputView becomeFirstResponder];
  2154. };
  2155. }
  2156. -(void)removeAtList:(NSInteger)index{
  2157. if(self.atSomeoneArray.count>index){
  2158. [self.atSomeoneArray removeObjectAtIndex:index];
  2159. [self textViewDidChange:_inputView];
  2160. }
  2161. }
  2162. #pragma mark 文件大小排序
  2163. -(NSArray *_Nullable)fileArraysort:(NSArray *_Nullable)array{
  2164. NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(ChatFileModel *obj1, ChatFileModel *obj2) {
  2165. if(obj1.bySize<obj2.bySize){
  2166. return NSOrderedAscending;
  2167. }
  2168. else if(obj1.bySize==obj2.bySize){
  2169. return NSOrderedSame;
  2170. }
  2171. else{
  2172. return NSOrderedDescending;
  2173. }
  2174. }];
  2175. return sortedArray;
  2176. }
  2177. #pragma mark 其他聊天室的消息弹窗
  2178. - (void)othersChatMessageAlert:(NSNotification *)notification {
  2179. // NSLog(@"othersChatMessageAlert---1");
  2180. if ([self isViewLoaded] && self.view.window) {
  2181. NSDictionary * msgDict = notification.object;
  2182. NSMutableDictionary * mutablemsg = msgDict.mutableCopy;
  2183. NSLog(@"othersChatMessageAlert---2:%@",mutablemsg);
  2184. if (msgDict) {
  2185. ChatMessageModel *message = [ChatMessageModel modelWithDictionary:mutablemsg];
  2186. if ([message.chatId isEqualToString:self.chatId] || message.isSender ) {
  2187. return;
  2188. }
  2189. if ([message.chatId isEqualToString:self.userId] && message.type == 0) {
  2190. return;
  2191. }
  2192. if (message.nickName.length==0) {
  2193. return;
  2194. }
  2195. if (message.content.length==0) {
  2196. if (message.messageType==7) {
  2197. message.content=NSLocalizedString(@"ChatVtr-guaduan", @"");
  2198. }
  2199. else{
  2200. return;
  2201. }
  2202. }
  2203. NSLog(@"othersChatMessageAlert---3:%@",message.avatar);
  2204. // weakSelf(self);
  2205. [TopPopupView showWithNickname:message.nickName avatar:message.avatar message:message.content chatId:message.chatId type:message.type clickBlock:^{
  2206. // weakself.chatId = message.chatId;
  2207. // weakself.type = message.type;
  2208. // weakself.titlename = message.nickName;
  2209. // weakself.avatar = message.avatar;
  2210. // [weakself reloadAllData];
  2211. }];
  2212. }
  2213. }
  2214. }
  2215. -(NSString *)getLocalTime{
  2216. if(self.messageArray.count>0){
  2217. ChatMessageModel *lastObj = self.messageArray.lastObject;
  2218. NSDate *now = [NSDate date];
  2219. NSTimeInterval trt = [now timeIntervalSince1970];
  2220. NSInteger time = trt*1000;
  2221. if(time<lastObj.timestamp){
  2222. time =lastObj.timestamp+1;
  2223. }
  2224. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  2225. return strtime;
  2226. }
  2227. else{
  2228. NSDate *now = [NSDate date];
  2229. NSTimeInterval trt = [now timeIntervalSince1970];
  2230. NSInteger time = trt*1000;
  2231. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  2232. return strtime;
  2233. }
  2234. }
  2235. @end