ChatController.m 97 KB

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