ChatController.m 96 KB

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