ChatController.m 94 KB

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