ChatController.m 96 KB

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