ChatController.m 96 KB

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