ChatController.m 93 KB

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