ChatController.m 93 KB

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