ChatController.m 92 KB

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