2
0

WFCUMessageListViewController.m 176 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781
  1. //
  2. // MessageListViewController.m
  3. // WFChat UIKit
  4. //
  5. // Created by WF Chat on 2017/8/31.
  6. // Copyright © 2017年 WildFireChat. All rights reserved.
  7. //
  8. #import "WFCUMessageListViewController.h"
  9. #import <AVFoundation/AVFoundation.h>
  10. #import "WFCUImagePreviewViewController.h"
  11. #import "WFCUVoiceRecordView.h"
  12. #import "WFCUImageCell.h"
  13. #import "WFCUTextCell.h"
  14. #import "WFCUVoiceCell.h"
  15. #import "WFCULocationCell.h"
  16. #import "WFCUFileCell.h"
  17. #import "WFCUInformationCell.h"
  18. #import "WFCUCallSummaryCell.h"
  19. #import "WFCUStickerCell.h"
  20. #import "WFCUVideoCell.h"
  21. #import "WFCURecallCell.h"
  22. #import "WFCUConferenceInviteCell.h"
  23. #import "WFCUCardCell.h"
  24. #import "WFCUCompositeCell.h"
  25. #import "WFCULinkCell.h"
  26. #import "WFCURichNotificationCell.h"
  27. #import "WFCUStreamingTextCell.h"
  28. #import "WFCUBrowserViewController.h"
  29. #import <WFChatClient/WFCChatClient.h>
  30. #import "WFCUProfileTableViewController.h"
  31. #import "WFCUMultiVideoViewController.h"
  32. #import "WFCUChatInputBar.h"
  33. #import "UIView+Toast.h"
  34. #import "WFCUConversationSettingViewController.h"
  35. #import "WFCULocationViewController.h"
  36. #import "WFCULocationPoint.h"
  37. #import "WFCUVideoViewController.h"
  38. #import "WFCUContactListViewController.h"
  39. #import "WFCUBrowserViewController.h"
  40. #import "MBProgressHUD.h"
  41. #import "WFCUMediaMessageDownloader.h"
  42. #import "VideoPlayerKit.h"
  43. #import "WFCUForwardViewController.h"
  44. #import <WFChatClient/WFCChatClient.h>
  45. #if WFCU_SUPPORT_VOIP
  46. #import <WFAVEngineKit/WFAVEngineKit.h>
  47. #endif
  48. #import "WFCUConfigManager.h"
  49. #import "WFCUSeletedUserViewController.h"
  50. #import "WFCUReceiptViewController.h"
  51. #import "UIColor+YH.h"
  52. #import "WFCUConversationTableViewController.h"
  53. #import "WFCUConversationSearchTableViewController.h"
  54. #import "WFCUConferenceViewController.h"
  55. #import "WFCUGroupInfoViewController.h"
  56. #import "WFCUChannelProfileViewController.h"
  57. #import "WFCUQuoteViewController.h"
  58. #import "WFCUCompositeMessageViewController.h"
  59. #import "WFCUFavoriteItem.h"
  60. #import "WFCUUtilities.h"
  61. #import "WFCUMultiCallOngoingCell.h"
  62. #import "WFCUMultiCallOngoingExpendedCell.h"
  63. #import "WFCUArticlesCell.h"
  64. #import "WFCUImage.h"
  65. #import "WFZConferenceInfoViewController.h"
  66. #import "WFZConferenceInfo.h"
  67. #import "MWPhotoBrowser.h"
  68. @interface WFCUMessageListViewController () <UITextFieldDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate, UINavigationControllerDelegate, WFCUMessageCellDelegate, AVAudioPlayerDelegate, WFCUChatInputBarDelegate, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource, WFCUMultiCallOngoingExpendedCellDelegate, MWPhotoBrowserDelegate>
  69. @property (nonatomic, strong)NSMutableArray<WFCUMessageModel *> *modelList;
  70. @property (nonatomic, strong)NSMutableArray<WFCCMessage *> *mentionedMsgs;
  71. @property (nonatomic, strong)NSMutableDictionary<NSNumber *, Class> *cellContentDict;
  72. @property(nonatomic) AVAudioPlayer *player;
  73. @property(nonatomic) NSTimer *playTimer;
  74. @property(nonatomic, assign)long playingMessageId;
  75. @property(nonatomic, assign)BOOL loadingMore;
  76. @property(nonatomic, assign)BOOL hasMoreOld;
  77. @property(nonatomic, strong)WFCCUserInfo *targetUser;
  78. @property(nonatomic, strong)WFCCGroupInfo *targetGroup;
  79. @property(nonatomic, strong)WFCCChannelInfo *targetChannel;
  80. @property(nonatomic, strong)WFCCChatroomInfo *targetChatroom;
  81. @property(nonatomic, strong)WFCCSecretChatInfo *secretChatInfo;
  82. @property(nonatomic, strong)WFCUChatInputBar *chatInputBar;
  83. @property(nonatomic, strong)VideoPlayerKit *videoPlayerViewController;
  84. @property (strong, nonatomic) UICollectionView *collectionView;
  85. @property (strong, nonatomic)NSArray<WFCCMessage *> *imageMsgs;
  86. @property (strong, nonatomic)NSString *orignalDraft;
  87. @property (nonatomic, strong)id<UIGestureRecognizerDelegate> scrollBackDelegate;
  88. @property (nonatomic, strong)UIView *backgroundView;
  89. @property (nonatomic, assign)BOOL showAlias;
  90. @property (nonatomic, strong)WFCUMessageCellBase *cell4Menu;
  91. @property (nonatomic, assign)BOOL firstAppear;
  92. @property (nonatomic, assign)BOOL hasNewMessage;
  93. @property (nonatomic, assign)BOOL loadingNew;
  94. @property (nonatomic, strong)UICollectionReusableView *headerView;
  95. @property (nonatomic, strong)UICollectionReusableView *footerView;
  96. @property (nonatomic, strong)UIActivityIndicatorView *headerActivityView;
  97. @property (nonatomic, strong)UIActivityIndicatorView *footerActivityView;
  98. @property (nonatomic, strong)NSTimer *showTypingTimer;
  99. @property (nonatomic, assign)BOOL isShowingKeyboard;
  100. @property (nonatomic, strong)NSMutableDictionary<NSString *, NSNumber *> *deliveryDict;
  101. @property (nonatomic, strong)NSMutableDictionary<NSString *, NSNumber *> *readDict;
  102. @property (nonatomic, strong)NSMutableSet<NSNumber *> *nMsgSet;
  103. @property (nonatomic, strong)UIView *multiSelectPanel;
  104. @property (nonatomic, assign)long firstUnreadMessageId;
  105. @property (nonatomic, assign)int unreadMessageCount;
  106. @property (nonatomic, strong)UIButton *unreadButton;
  107. @property (nonatomic, strong)UIButton *mentionedButton;
  108. @property (nonatomic, strong)UIButton *newMsgTipButton;
  109. @property (nonatomic, assign)int64_t lastUid;
  110. @property (nonatomic, strong)NSMutableDictionary<NSString *, WFCCMessage *> *ongoingCallDict;
  111. @property (nonatomic, strong)UITableView *ongoingCallTableView;
  112. @property (nonatomic, assign)int focusedOngoingCellIndex;
  113. @property (nonatomic, strong)NSTimer *checkOngoingCallTimer;
  114. @property (nonatomic, assign)BOOL isAtButtom;
  115. @property (nonatomic, strong)NSMutableDictionary<NSString*, NSDictionary*> *typingDict;
  116. @end
  117. @implementation WFCUMessageListViewController
  118. - (void)viewDidLoad {
  119. [super viewDidLoad];
  120. [self removeControllerStackIfNeed];
  121. self.isAtButtom = YES;
  122. self.cellContentDict = [[NSMutableDictionary alloc] init];
  123. self.ongoingCallDict = [[NSMutableDictionary alloc] init];
  124. self.typingDict = [[NSMutableDictionary alloc] init];
  125. self.focusedOngoingCellIndex = -1;
  126. [self initializedSubViews];
  127. self.firstAppear = YES;
  128. self.hasMoreOld = YES;
  129. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onResetKeyboard:)];
  130. [self.collectionView addGestureRecognizer:tap];
  131. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceiveMessages:) name:kReceiveMessages object:nil];
  132. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRecallMessages:) name:kRecallMessages object:nil];
  133. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeleteMessages:) name:kDeleteMessages object:nil];
  134. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageDelivered:) name:kMessageDelivered object:nil];
  135. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReaded:) name:kMessageReaded object:nil];
  136. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSendingMessage:) name:kSendingMessageStatusUpdated object:nil];
  137. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageListChanged:) name:kMessageListChanged object:nil];
  138. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageUpdated:) name:kMessageUpdated object:nil];
  139. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMenuHidden:) name:UIMenuControllerDidHideMenuNotification object:nil];
  140. #if WFCU_SUPPORT_VOIP
  141. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCallStateChanged:) name:kCallStateUpdated object:nil];
  142. #endif
  143. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSettingUpdated:) name:kSettingUpdated object:nil];
  144. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTitle) name:kUserOnlineStateUpdated object:nil];
  145. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSecretChatStateChanged:) name:kSecretChatStateUpdated object:nil];
  146. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSecretMessageStartBurning:) name:kSecretMessageStartBurning object:nil];
  147. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSecretMessageBurned:) name:kSecretMessageBurned object:nil];
  148. self.chatInputBar = [[WFCUChatInputBar alloc] initWithSuperView:self.backgroundView conversation:self.conversation delegate:self];
  149. __weak typeof(self)ws = self;
  150. if(self.conversation.type == Single_Type) {
  151. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.conversation.target refresh:YES];
  152. self.targetUser = userInfo;
  153. } else if(self.conversation.type == Group_Type) {
  154. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.conversation.target refresh:YES];
  155. self.targetGroup = groupInfo;
  156. } else if (self.conversation.type == Channel_Type) {
  157. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:YES];
  158. self.targetChannel = channelInfo;
  159. } else if(self.conversation.type == Chatroom_Type) {
  160. [[WFCCIMService sharedWFCIMService] getChatroomInfo:self.conversation.target upateDt:ws.targetChatroom.updateDt success:^(WFCCChatroomInfo *chatroomInfo) {
  161. ws.targetChatroom = chatroomInfo;
  162. } error:^(int error_code) {
  163. }];
  164. } else if(self.conversation.type == SecretChat_Type) {
  165. self.secretChatInfo = [[WFCCIMService sharedWFCIMService] getSecretChatInfo:self.conversation.target];
  166. }
  167. if(self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  168. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoUpdated:) name:kUserInfoUpdated object:nil];
  169. } else if(self.conversation.type == Group_Type) {
  170. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGroupInfoUpdated:) name:kGroupInfoUpdated object:nil];
  171. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onGroupMemberUpdated:) name:kGroupMemberUpdated object:nil];
  172. } else if(self.conversation.type == Channel_Type) {
  173. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChannelInfoUpdated:) name:kChannelInfoUpdated object:nil];
  174. }
  175. [self setupNavigationItem];
  176. self.orignalDraft = [[WFCCIMService sharedWFCIMService] getConversationInfo:self.conversation].draft;
  177. if (self.conversation.type == Chatroom_Type) {
  178. NSString *joinedChatroomId = [[WFCCIMService sharedWFCIMService] getJoinedChatroomId];
  179. if(![ws.conversation.target isEqualToString:joinedChatroomId]) {
  180. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
  181. hud.label.text = WFCString(@"JoinChatroom");
  182. [hud showAnimated:YES];
  183. [[WFCCIMService sharedWFCIMService] joinChatroom:ws.conversation.target success:^{
  184. NSLog(@"join chatroom successs");
  185. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  186. [ws sendChatroomWelcomeMessage];
  187. });
  188. [hud hideAnimated:YES];
  189. } error:^(int error_code) {
  190. NSLog(@"join chatroom error");
  191. hud.mode = MBProgressHUDModeText;
  192. hud.label.text = WFCString(@"JoinChatroomFailure");
  193. // hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
  194. [hud hideAnimated:YES afterDelay:1.f];
  195. hud.completionBlock = ^{
  196. [ws.navigationController popViewControllerAnimated:YES];
  197. };
  198. }];
  199. } else {
  200. [[WFCCIMService sharedWFCIMService] joinChatroom:ws.conversation.target success:^{
  201. //需要拉取历史消息
  202. [ws loadMoreMessage:YES completion:nil];
  203. } error:^(int error_code) {
  204. }];
  205. }
  206. }
  207. if(self.conversation.type == Channel_Type) {
  208. WFCCEnterChannelChatMessageContent *enterContent = [[WFCCEnterChannelChatMessageContent alloc] init];
  209. [[WFCCIMService sharedWFCIMService] send:self.conversation content:enterContent success:nil error:nil];
  210. }
  211. WFCCConversationInfo *info = [[WFCCIMService sharedWFCIMService] getConversationInfo:self.conversation];
  212. self.chatInputBar.draft = info.draft;
  213. if (self.conversation.type == Group_Type) {
  214. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  215. NSArray<WFCCGroupMember *> *groupMembers = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  216. NSMutableArray *memberIds = [[NSMutableArray alloc] init];
  217. for (WFCCGroupMember *member in groupMembers) {
  218. [memberIds addObject:member.memberId];
  219. if (memberIds.count >= 100) {
  220. //预加载100名群成员
  221. break;
  222. }
  223. }
  224. [[WFCCIMService sharedWFCIMService] getUserInfos:memberIds inGroup:self.conversation.target];
  225. });
  226. }
  227. if (self.multiSelecting) {
  228. self.multiSelectPanel.hidden = NO;
  229. }
  230. self.nMsgSet = [[NSMutableSet alloc] init];
  231. if(self.conversation.type == Single_Type || self.conversation.type == Group_Type || self.conversation.type == SecretChat_Type) {
  232. if([[WFCCIMService sharedWFCIMService] isEnableUserOnlineState]) {
  233. BOOL isFriend = false;
  234. if(self.conversation.type == Single_Type) {
  235. isFriend = [[WFCCIMService sharedWFCIMService] isMyFriend:self.conversation.target];
  236. } else if(self.conversation.type == SecretChat_Type) {
  237. isFriend = [[WFCCIMService sharedWFCIMService] isMyFriend:self.secretChatInfo.userId];
  238. }
  239. if(!isFriend) { //如果不是好友才需要watch他的在线状态
  240. __weak typeof(self)ws = self;
  241. [[WFCCIMService sharedWFCIMService] watchOnlineState:self.conversation.type targets:@[self.conversation.target] duration:3600 success:^(NSArray<WFCCUserOnlineState *> *states) {
  242. [ws updateTitle];
  243. } error:^(int error_code) {
  244. NSLog(@"watch online state failure");
  245. }];
  246. }
  247. }
  248. }
  249. [self reloadMessageList];
  250. }
  251. - (void)onUserInfoUpdated:(NSNotification *)notification {
  252. NSArray<WFCCUserInfo *> *userInfoList = notification.userInfo[@"userInfoList"];
  253. for (WFCCUserInfo *userInfo in userInfoList) {
  254. if ([self.conversation.target isEqualToString:userInfo.userId]) {
  255. self.targetUser = userInfo;
  256. break;
  257. }
  258. }
  259. }
  260. - (void)onGroupInfoUpdated:(NSNotification *)notification {
  261. NSArray<WFCCGroupInfo *> *groupInfoList = notification.userInfo[@"groupInfoList"];
  262. for (WFCCGroupInfo *groupInfo in groupInfoList) {
  263. if ([self.conversation.target isEqualToString:groupInfo.target]) {
  264. self.targetGroup = groupInfo;
  265. break;
  266. }
  267. }
  268. }
  269. - (void)onGroupMemberUpdated:(NSNotification *)notification {
  270. if ([self.conversation.target isEqualToString:notification.object]) {
  271. self.targetGroup = self.targetGroup;
  272. }
  273. }
  274. - (void)onChannelInfoUpdated:(NSNotification *)notification {
  275. NSArray<WFCCChannelInfo *> *channelInfoList = notification.userInfo[@"channelInfoList"];
  276. for (WFCCChannelInfo *channelInfo in channelInfoList) {
  277. if ([self.conversation.target isEqualToString:channelInfo.channelId]) {
  278. self.targetChannel = channelInfo;
  279. break;
  280. }
  281. }
  282. }
  283. //The VC maybe pushed from search VC, so no need go back to search VC, need remove all the VC between current VC to WFCUConversationTableViewController
  284. - (void)removeControllerStackIfNeed {
  285. //highlightMessageId will be positive if the VC pushed from search VC
  286. if (self.highlightMessageId > 0) {
  287. if (self.navigationController.viewControllers.count < 3) {
  288. return;
  289. }
  290. NSMutableArray *controllers = [self.navigationController.viewControllers mutableCopy];
  291. BOOL foundParent = NO;
  292. NSMutableArray *tobeDeleteVCs = [[NSMutableArray alloc] init];
  293. for (int i = (int)controllers.count - 2; i >=0; i--) {
  294. UIViewController *controller = controllers[i];
  295. if ([controller isKindOfClass:[WFCUConversationTableViewController class]]) {
  296. foundParent = YES;
  297. break;
  298. } else {
  299. [tobeDeleteVCs addObject:controller];
  300. }
  301. }
  302. if (foundParent) {
  303. [controllers removeObjectsInArray:tobeDeleteVCs];
  304. self.navigationController.viewControllers = [controllers copy];
  305. }
  306. }
  307. }
  308. - (void)setupNavigationItem {
  309. if (self.multiSelecting) {
  310. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"search"] style:UIBarButtonItemStyleDone target:self action:@selector(onSearchBarBtn:)];
  311. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:WFCString(@"Cancel") style:UIBarButtonItemStyleDone target:self action:@selector(onMultiSelectCancel:)];
  312. } else {
  313. if(self.conversation.type == Single_Type) {
  314. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"nav_chat_single"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  315. } else if(self.conversation.type == Group_Type) {
  316. if(!self.targetGroup || self.targetGroup.deleted || self.targetGroup.memberDt < 0) {
  317. self.navigationItem.rightBarButtonItem = nil;
  318. } else {
  319. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"nav_chat_group"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  320. }
  321. } else if(self.conversation.type == Channel_Type) {
  322. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"nav_chat_channel"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  323. } else if(self.conversation.type == SecretChat_Type) {
  324. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[WFCUImage imageNamed:@"nav_chat_single"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightBarBtn:)];
  325. }
  326. if(self.presented) {
  327. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:WFCString(@"Close") style:UIBarButtonItemStyleDone target:self action:@selector(onCloseBtn:)];
  328. } else {
  329. self.navigationItem.leftBarButtonItem = nil;
  330. }
  331. }
  332. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] init];
  333. }
  334. - (void)onMultiSelectCancel:(id)sender {
  335. self.multiSelecting = !self.multiSelecting;
  336. }
  337. - (void)setLoadingMore:(BOOL)loadingMore {
  338. _loadingMore = loadingMore;
  339. if (_loadingMore) {
  340. [self.headerActivityView startAnimating];
  341. } else {
  342. [self.headerActivityView stopAnimating];
  343. }
  344. }
  345. - (UIActivityIndicatorView *)headerActivityView {
  346. if (!_headerActivityView) {
  347. _headerActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  348. }
  349. return _headerActivityView;
  350. }
  351. - (UIActivityIndicatorView *)footerActivityView {
  352. if (!_footerActivityView) {
  353. _footerActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  354. }
  355. return _footerActivityView;
  356. }
  357. - (void)setLoadingNew:(BOOL)loadingNew {
  358. _loadingNew = loadingNew;
  359. if (loadingNew) {
  360. [self.footerActivityView startAnimating];
  361. } else {
  362. [self.footerActivityView stopAnimating];
  363. }
  364. }
  365. - (void)setHasNewMessage:(BOOL)hasNewMessage {
  366. _hasNewMessage = hasNewMessage;
  367. UICollectionViewFlowLayout *_customFlowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
  368. if (hasNewMessage) {
  369. _customFlowLayout.footerReferenceSize = CGSizeMake(320.0f, 20.0f);
  370. } else {
  371. _customFlowLayout.footerReferenceSize = CGSizeZero;
  372. }
  373. }
  374. - (void)loadRemoteHistoryMessages:(void (^ __nullable)(BOOL more))completion {
  375. __weak typeof(self) weakSelf = self;
  376. if(!self.lastUid) {
  377. self.lastUid = self.modelList.lastObject.message.messageUid;
  378. }
  379. for (WFCUMessageModel *model in self.modelList) {
  380. if (model.message.messageUid > 0 && model.message.messageUid < self.lastUid) {
  381. self.lastUid = model.message.messageUid;
  382. }
  383. }
  384. [[WFCCIMService sharedWFCIMService] getRemoteMessages:weakSelf.conversation before:self.lastUid count:10 contentTypes:nil success:^(NSArray<WFCCMessage *> *messages) {
  385. NSMutableArray *reversedMsgs = [[NSMutableArray alloc] init];
  386. for (WFCCMessage *msg in messages) {
  387. [reversedMsgs insertObject:msg atIndex:0];
  388. if (msg.messageUid > 0 && msg.messageUid < self.lastUid) {
  389. self.lastUid = msg.messageUid;
  390. }
  391. }
  392. if (!reversedMsgs.count) {
  393. weakSelf.hasMoreOld = NO;
  394. } else {
  395. [weakSelf appendMessages:reversedMsgs newMessage:NO highlightId:0 forceButtom:NO];
  396. }
  397. weakSelf.loadingMore = NO;
  398. if (completion) {
  399. completion(messages.count > 0);
  400. }
  401. } error:^(int error_code) {
  402. dispatch_async(dispatch_get_main_queue(), ^{
  403. weakSelf.hasMoreOld = NO;
  404. weakSelf.loadingMore = NO;
  405. });
  406. }];
  407. }
  408. - (void)loadMoreMessage:(BOOL)isHistory completion:(void (^ __nullable)(BOOL more))completion {
  409. __weak typeof(self) weakSelf = self;
  410. if (isHistory) {
  411. if (self.loadingMore) {
  412. return;
  413. }
  414. self.loadingMore = YES;
  415. __block long lastIndex = 0;
  416. __block long maxTime = 0;
  417. if (weakSelf.modelList.count) {
  418. lastIndex = [weakSelf.modelList firstObject].message.messageId;
  419. maxTime = [weakSelf.modelList firstObject].message.serverTime;
  420. [weakSelf.modelList enumerateObjectsUsingBlock:^(WFCUMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  421. if(obj.message.serverTime < maxTime) {
  422. lastIndex = obj.message.messageId;
  423. maxTime = obj.message.serverTime;
  424. }
  425. }];
  426. }
  427. [[WFCCIMService sharedWFCIMService] getMessagesV2:weakSelf.conversation contentTypes:nil from:lastIndex count:10 withUser:self.privateChatUser success:^(NSArray<WFCCMessage *> *messageList) {
  428. if(messageList.count) {
  429. [weakSelf appendMessages:messageList newMessage:NO highlightId:0 forceButtom:NO];
  430. weakSelf.loadingMore = NO;
  431. if (completion) {
  432. completion(messageList.count > 0);
  433. }
  434. } else {
  435. [weakSelf loadRemoteHistoryMessages:completion];
  436. }
  437. } error:^(int error_code) {
  438. weakSelf.loadingMore = NO;
  439. }];
  440. } else {
  441. if (weakSelf.loadingNew || !weakSelf.hasNewMessage) {
  442. return;
  443. }
  444. weakSelf.loadingNew = YES;
  445. long lastIndex = 0;
  446. if (self.modelList.count) {
  447. lastIndex = [self.modelList lastObject].message.messageId;
  448. }
  449. dispatch_async(dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{
  450. NSArray *messageList = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:lastIndex count:-10 withUser:self.privateChatUser];
  451. if (!messageList.count || messageList.count < 10) {
  452. self.hasNewMessage = NO;
  453. }
  454. NSMutableArray *mutableMessages = [messageList mutableCopy];
  455. for (int i = 0; i < mutableMessages.count/2; i++) {
  456. int j = (int)mutableMessages.count - 1 - i;
  457. WFCCMessage *msg = [mutableMessages objectAtIndex:i];
  458. [mutableMessages insertObject:[mutableMessages objectAtIndex:j] atIndex:i];
  459. [mutableMessages removeObjectAtIndex:i+1];
  460. [mutableMessages insertObject:msg atIndex:j];
  461. [mutableMessages removeObjectAtIndex:j+1];
  462. }
  463. [NSThread sleepForTimeInterval:0.5];
  464. dispatch_async(dispatch_get_main_queue(), ^{
  465. [weakSelf appendMessages:mutableMessages newMessage:YES highlightId:0 forceButtom:NO];
  466. weakSelf.loadingNew = NO;
  467. if (completion) {
  468. completion(messageList.count > 0);
  469. }
  470. });
  471. });
  472. }
  473. }
  474. - (void)sendChatroomWelcomeMessage {
  475. if(!self.silentJoinChatroom) {
  476. WFCCTipNotificationContent *tip = [[WFCCTipNotificationContent alloc] init];
  477. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];
  478. tip.tip = [NSString stringWithFormat:WFCString(@"WelcomeJoinChatroomHint"), userInfo.displayName];
  479. [self sendMessage:tip];
  480. }
  481. }
  482. - (void)sendChatroomLeaveMessage {
  483. __block WFCCConversation *strongConv = self.conversation;
  484. if(!self.silentJoinChatroom) {
  485. dispatch_async(dispatch_get_main_queue(), ^{
  486. WFCCTipNotificationContent *tip = [[WFCCTipNotificationContent alloc] init];
  487. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];
  488. tip.tip = [NSString stringWithFormat:WFCString(@"LeaveChatroomHint"), userInfo.displayName];
  489. [[WFCCIMService sharedWFCIMService] send:strongConv content:tip success:^(long long messageUid, long long timestamp) {
  490. [[WFCCIMService sharedWFCIMService] quitChatroom:strongConv.target success:nil error:nil];
  491. } error:^(int error_code) {
  492. [[WFCCIMService sharedWFCIMService] quitChatroom:strongConv.target success:nil error:nil];
  493. }];
  494. });
  495. } else {
  496. dispatch_async(dispatch_get_main_queue(), ^{
  497. [[WFCCIMService sharedWFCIMService] quitChatroom:strongConv.target success:nil error:nil];
  498. });
  499. }
  500. }
  501. - (void)onCloseBtn:(id)sender {
  502. [self.navigationController dismissViewControllerAnimated:YES completion:nil];
  503. }
  504. - (void)onLeftBtnPressed:(id)sender {
  505. [self.navigationController popViewControllerAnimated:YES];
  506. }
  507. - (void)didMoveToParentViewController:(UIViewController*)parent
  508. {
  509. [super didMoveToParentViewController:parent];
  510. if(!parent){
  511. [self leftMessageVC];
  512. }
  513. }
  514. - (void)leftMessageVC {
  515. if (self.conversation.type == Chatroom_Type && !self.keepInChatroom) {
  516. [self sendChatroomLeaveMessage];
  517. }
  518. if(self.conversation.type == Channel_Type) {
  519. WFCCLeaveChannelChatMessageContent *leaveContent = [[WFCCLeaveChannelChatMessageContent alloc] init];
  520. [[WFCCIMService sharedWFCIMService] send:self.conversation content:leaveContent success:nil error:nil];
  521. }
  522. if(self.conversation.type == Single_Type || self.conversation.type == Group_Type || self.conversation.type == SecretChat_Type) {
  523. if([[WFCCIMService sharedWFCIMService] isEnableUserOnlineState]) {
  524. BOOL isFriend = false;
  525. if(self.conversation.type == Single_Type) {
  526. isFriend = [[WFCCIMService sharedWFCIMService] isMyFriend:self.conversation.target];
  527. } else if(self.conversation.type == SecretChat_Type) {
  528. isFriend = [[WFCCIMService sharedWFCIMService] isMyFriend:self.secretChatInfo.userId];
  529. }
  530. if(!isFriend) { //如果不是好友才需要unwatch他的在线状态
  531. [[WFCCIMService sharedWFCIMService] unwatchOnlineState:self.conversation.type targets:@[self.conversation.target] success:^{
  532. NSLog(@"unwatch online statue success");
  533. } error:^(int error_code) {
  534. NSLog(@"unwatch online statue failure");
  535. }];
  536. }
  537. }
  538. }
  539. if(self.checkOngoingCallTimer) {
  540. [self.checkOngoingCallTimer invalidate];
  541. self.checkOngoingCallTimer = nil;
  542. }
  543. }
  544. - (void)onRightBarBtn:(UIBarButtonItem *)sender {
  545. WFCUConversationSettingViewController *gvc = [[WFCUConversationSettingViewController alloc] init];
  546. gvc.conversation = self.conversation;
  547. [self.navigationController pushViewController:gvc animated:YES];
  548. }
  549. - (void)onSearchBarBtn:(id)sender {
  550. if (self.multiSelecting) {
  551. for (WFCUMessageModel *model in self.modelList) {
  552. if (model.selected && ![self.selectedMessageIds containsObject:@(model.message.messageId)]) {
  553. [self.selectedMessageIds addObject:@(model.message.messageId)];
  554. }
  555. }
  556. WFCUConversationSearchTableViewController *mvc = [[WFCUConversationSearchTableViewController alloc] init];
  557. mvc.conversation = self.conversation;
  558. mvc.hidesBottomBarWhenPushed = YES;
  559. mvc.messageSelecting = YES;
  560. mvc.selectedMessageIds = self.selectedMessageIds;
  561. [self.navigationController pushViewController:mvc animated:YES];
  562. }
  563. }
  564. - (void)updateTitle {
  565. if(self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  566. if(self.targetUser.friendAlias.length) {
  567. self.title = self.targetUser.friendAlias;
  568. } else if(self.targetUser.displayName.length == 0) {
  569. self.title = [NSString stringWithFormat:@"%@<%@>", WFCString(@"User"), self.conversation.target];
  570. } else {
  571. self.title = self.targetUser.displayName;
  572. }
  573. /*
  574. int Platform_UNSET = 0;
  575. int Platform_iOS = 1;
  576. int Platform_Android = 2;
  577. int Platform_Windows = 3;
  578. int Platform_OSX = 4;
  579. int Platform_WEB = 5;
  580. int Platform_WX = 6;
  581. int Platform_LINUX = 7;
  582. int Platform_iPad = 8;
  583. int Platform_APad = 9;
  584. */
  585. if([[WFCCIMService sharedWFCIMService] isEnableUserOnlineState] && ![WFCCUtilities isExternalTarget:self.conversation.target]) {
  586. NSString *userId = self.conversation.target;
  587. if(self.conversation.type == SecretChat_Type) {
  588. userId = self.secretChatInfo.userId;
  589. }
  590. WFCCUserOnlineState *onlineState = [[WFCCIMService sharedWFCIMService] getUserOnlineState:userId];
  591. if([onlineState.clientStates count]) {
  592. int pcState = -1;
  593. int mobileState = -1;
  594. int webState = -1;
  595. int wxState = -1;
  596. int padState = -1;
  597. BOOL hasOnline = NO;
  598. BOOL hasMobileSession = NO;
  599. long long mobileLastSeen = 0;
  600. for (WFCCClientState *cs in onlineState.clientStates) {
  601. if(cs.platform >= 1 && cs.platform <= 9 && cs.state == 0) {
  602. hasOnline = YES;
  603. }
  604. if(cs.platform == 1 || cs.platform == 2) {
  605. mobileState = cs.state;
  606. if(cs.state == 1) {
  607. hasMobileSession = YES;
  608. if(mobileLastSeen < cs.lastSeen) {
  609. mobileLastSeen = cs.lastSeen;
  610. }
  611. }
  612. } else if(cs.platform == 3 || cs.platform == 4 || cs.platform == 7) {
  613. pcState = cs.state;
  614. } else if(cs.platform == 5) {
  615. webState = cs.state;
  616. } else if(cs.platform == 6) {
  617. wxState = cs.state;
  618. } else if(cs.platform == 8 || cs.platform == 9) {
  619. padState = cs.state;
  620. }
  621. }
  622. if(hasOnline) {
  623. //0,未设置,1 忙碌,2 离开(主动设置),3 离开(长时间不操作),4 隐身,其它可以自主扩展。
  624. if(onlineState.customState.state == 0) {
  625. if(pcState == 0) {
  626. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"电脑在线"];
  627. } else if(padState == 0) {
  628. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"平板在线"];
  629. } else if(webState == 0) {
  630. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"网页在线"];
  631. } else if(wxState == 0) {
  632. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"小程序在线"];
  633. } else if(mobileState == 0) {
  634. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"手机在线"];
  635. }
  636. } else if(onlineState.customState.state == 1) {
  637. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"忙碌"];
  638. } else if(onlineState.customState.state == 2 || onlineState.customState.state == 3) {
  639. self.title = [NSString stringWithFormat:@"%@(%@)", self.title, @"离开"];
  640. } else {
  641. //其它情况需要客户自己开发。。。
  642. }
  643. } else if(hasMobileSession && mobileLastSeen) {
  644. long long duration = [[[NSDate alloc] init] timeIntervalSince1970] - (mobileLastSeen/1000);
  645. int days = (int)(duration / 86400);
  646. if(days) {
  647. self.title = [NSString stringWithFormat:@"%@(%d天前手机在线)", self.title, days];
  648. } else {
  649. int hours = (int)(duration/3600);
  650. if(hours) {
  651. self.title = [NSString stringWithFormat:@"%@(%d小时前手机在线)", self.title, hours];
  652. } else {
  653. int mins = (int)(duration/60);
  654. if(mins) {
  655. self.title = [NSString stringWithFormat:@"%@(%d分钟前手机在线)", self.title, mins];
  656. } else {
  657. self.title = [NSString stringWithFormat:@"%@(不久前手机在线)", self.title];
  658. }
  659. }
  660. }
  661. }
  662. }
  663. }
  664. self.navigationItem.backBarButtonItem.title = self.title;
  665. } else if(self.conversation.type == Group_Type) {
  666. if(self.targetGroup.displayName.length == 0) {
  667. self.title = WFCString(@"GroupChat");
  668. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  669. } else {
  670. if(self.targetGroup.deleted) {
  671. self.title = [NSString stringWithFormat:@"%@(%@)", self.targetGroup.displayName, @"已删除"];
  672. } else if(self.targetGroup.memberDt < 0) {
  673. self.title = [NSString stringWithFormat:@"%@(%@)", self.targetGroup.displayName, @"已退出"];
  674. } else {
  675. self.title = [NSString stringWithFormat:@"%@(%d)", self.targetGroup.displayName, (int)self.targetGroup.memberCount];
  676. }
  677. self.navigationItem.backBarButtonItem.title = self.targetGroup.displayName;
  678. }
  679. } else if(self.conversation.type == Channel_Type) {
  680. if(self.targetChannel.name.length == 0) {
  681. self.title = WFCString(@"Channel");
  682. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  683. } else {
  684. self.title = self.targetChannel.name;
  685. self.navigationItem.backBarButtonItem.title = self.targetChannel.name;
  686. }
  687. } else if (self.conversation.type == Chatroom_Type) {
  688. if(self.targetChatroom.title.length == 0) {
  689. self.title = WFCString(@"Chatroom");
  690. self.navigationItem.backBarButtonItem.title = WFCString(@"Message");
  691. } else {
  692. self.title = self.targetChatroom.title;
  693. self.navigationItem.backBarButtonItem.title = self.targetChatroom.title;
  694. }
  695. }
  696. if([WFCCUtilities isExternalTarget:self.conversation.target]) {
  697. NSString *domainId = [WFCCUtilities getExternalDomain:self.conversation.target];
  698. UIView *titleContainer = [[UIView alloc] initWithFrame:CGRectMake(80, 0, self.view.bounds.size.width - 160, 36)];
  699. UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 160, 24)];
  700. UILabel *domainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 24, self.view.bounds.size.width - 160, 12)];
  701. titleLabel.textAlignment = NSTextAlignmentCenter;
  702. titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
  703. titleLabel.text = self.title;
  704. domainLabel.textAlignment = NSTextAlignmentCenter;
  705. domainLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
  706. domainLabel.font = [UIFont systemFontOfSize:12];
  707. domainLabel.attributedText = [WFCCUtilities getExternal:domainId withName:nil withColor:[WFCUConfigManager globalManager].externalNameColor withSize:10];
  708. [titleContainer addSubview:titleLabel];
  709. [titleContainer addSubview:domainLabel];
  710. self.navigationItem.titleView = titleContainer;
  711. }
  712. }
  713. - (void)setTargetUser:(WFCCUserInfo *)targetUser {
  714. _targetUser = targetUser;
  715. [self updateTitle];
  716. }
  717. - (void)setTargetGroup:(WFCCGroupInfo *)targetGroup {
  718. _targetGroup = targetGroup;
  719. [self updateTitle];
  720. [self setupNavigationItem];
  721. ChatInputBarStatus defaultStatus = ChatInputBarDefaultStatus;
  722. WFCCGroupMember *member = [[WFCCIMService sharedWFCIMService] getGroupMember:targetGroup.target memberId:[WFCCNetworkService sharedInstance].userId];
  723. if(targetGroup.deleted || targetGroup.memberDt < 0) {
  724. self.chatInputBar.inputBarStatus = ChatInputBarMuteStatus;
  725. } else if (targetGroup.mute || member.type == Member_Type_Muted) {
  726. if ([targetGroup.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  727. self.chatInputBar.inputBarStatus = defaultStatus;
  728. } else if(targetGroup.mute && member.type == Member_Type_Allowed) {
  729. self.chatInputBar.inputBarStatus = defaultStatus;
  730. } else {
  731. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:targetGroup.target memberId:[WFCCNetworkService sharedInstance].userId];
  732. if (gm.type == Member_Type_Manager) {
  733. self.chatInputBar.inputBarStatus = defaultStatus;
  734. } else {
  735. self.chatInputBar.inputBarStatus = ChatInputBarMuteStatus;
  736. }
  737. }
  738. } else {
  739. if(self.chatInputBar.inputBarStatus == ChatInputBarMuteStatus) {
  740. self.chatInputBar.inputBarStatus = defaultStatus;
  741. }
  742. }
  743. }
  744. - (void)setTargetChannel:(WFCCChannelInfo *)targetChannel {
  745. _targetChannel = targetChannel;
  746. [self updateTitle];
  747. }
  748. - (void)setTargetChatroom:(WFCCChatroomInfo *)targetChatroom {
  749. _targetChatroom = targetChatroom;
  750. [self updateTitle];
  751. }
  752. - (void)setSecretChatInfo:(WFCCSecretChatInfo *)secretChatInfo {
  753. _secretChatInfo = secretChatInfo;
  754. NSString *userId = self.secretChatInfo.userId;
  755. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:userId refresh:YES];
  756. self.targetUser = userInfo;
  757. }
  758. - (void)setShowAlias:(BOOL)showAlias {
  759. _showAlias = showAlias;
  760. if (self.modelList) {
  761. for (WFCUMessageModel *model in self.modelList) {
  762. if (showAlias && model.message.direction == MessageDirection_Receive) {
  763. model.showNameLabel = YES;
  764. } else {
  765. model.showNameLabel = NO;
  766. }
  767. }
  768. }
  769. }
  770. - (void)setMultiSelecting:(BOOL)multiSelecting {
  771. _multiSelecting = multiSelecting;
  772. if (multiSelecting) {
  773. for (WFCUMessageModel *model in self.modelList) {
  774. model.selecting = YES;
  775. model.selected = NO;
  776. }
  777. if (!self.selectedMessageIds) {
  778. self.selectedMessageIds = [[NSMutableArray alloc] init];
  779. }
  780. self.multiSelectPanel.hidden = NO;
  781. } else {
  782. for (WFCUMessageModel *model in self.modelList) {
  783. model.selecting = NO;
  784. model.selected = NO;
  785. }
  786. self.selectedMessageIds = nil;
  787. self.multiSelectPanel.hidden = YES;
  788. }
  789. [self setupNavigationItem];
  790. [self.collectionView reloadData];
  791. }
  792. - (UIView *)multiSelectPanel {
  793. if (!_multiSelectPanel) {
  794. if (!self.backgroundView) {
  795. return nil;
  796. }
  797. _multiSelectPanel = [[UIView alloc] initWithFrame:CGRectMake(0, self.backgroundView.bounds.size.height - CHAT_INPUT_BAR_HEIGHT, self.backgroundView.bounds.size.width, CHAT_INPUT_BAR_HEIGHT)];
  798. _multiSelectPanel.backgroundColor = [UIColor colorWithHexString:@"0xf7f7f7"];
  799. UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _multiSelectPanel.bounds.size.width/2, _multiSelectPanel.bounds.size.height)];
  800. [deleteBtn setTitle:WFCString(@"Delete") forState:UIControlStateNormal];
  801. [deleteBtn addTarget:self action:@selector(onDeleteMultiSelectedMessage:) forControlEvents:UIControlEventTouchDown];
  802. [deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  803. [_multiSelectPanel addSubview:deleteBtn];
  804. UIButton *forwardBtn = [[UIButton alloc] initWithFrame:CGRectMake(_multiSelectPanel.bounds.size.width/2, 0, _multiSelectPanel.bounds.size.width/2, _multiSelectPanel.bounds.size.height)];
  805. [forwardBtn setTitle:WFCString(@"Forward") forState:UIControlStateNormal];
  806. [forwardBtn addTarget:self action:@selector(onForwardMultiSelectedMessage:) forControlEvents:UIControlEventTouchDown];
  807. [forwardBtn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
  808. [_multiSelectPanel addSubview:forwardBtn];
  809. [self.backgroundView addSubview:_multiSelectPanel];
  810. }
  811. return _multiSelectPanel;
  812. }
  813. - (void)onDeleteMultiSelectedMessage:(id)sender {
  814. NSMutableArray *deletedModels = [[NSMutableArray alloc] init];
  815. for (WFCUMessageModel *model in self.modelList) {
  816. if (model.selected) {
  817. [[WFCCIMService sharedWFCIMService] deleteMessage:model.message.messageId];
  818. [deletedModels addObject:model];
  819. [self.selectedMessageIds removeObject:@(model.message.messageId)];
  820. }
  821. }
  822. [self.modelList removeObjectsInArray:deletedModels];
  823. //有可能是经过多次搜索,选中了当前model列表中没有包含的
  824. for (NSNumber *IDS in self.selectedMessageIds) {
  825. [[WFCCIMService sharedWFCIMService] deleteMessage:[IDS longValue]];
  826. }
  827. self.multiSelecting = NO;
  828. }
  829. - (void)onForwardMultiSelectedMessage:(id)sender {
  830. NSMutableArray *messages = [[NSMutableArray alloc] init];
  831. for (WFCUMessageModel *model in self.modelList) {
  832. if (model.selected) {
  833. [messages addObject:model.message];
  834. }
  835. }
  836. [self.selectedMessageIds removeAllObjects];
  837. self.multiSelecting = NO;
  838. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  839. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
  840. UIAlertAction *oneByOneAction = [UIAlertAction actionWithTitle:@"逐条转发" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  841. WFCUForwardViewController *controller = [[WFCUForwardViewController alloc] init];
  842. controller.messages = messages;
  843. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
  844. [self.navigationController presentViewController:navi animated:YES completion:nil];
  845. }];
  846. UIAlertAction *AllInOneAction = [UIAlertAction actionWithTitle:@"合并转发" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  847. WFCCCompositeMessageContent *compositeContent = [[WFCCCompositeMessageContent alloc] init];
  848. if (self.conversation.type == Single_Type) {
  849. NSString *title = nil;
  850. if(self.targetUser.friendAlias.length) {
  851. title = self.targetUser.friendAlias;
  852. } else if(self.targetUser.displayName.length == 0) {
  853. title = [NSString stringWithFormat:@"%@<%@>", WFCString(@"User"), self.conversation.target];
  854. } else {
  855. title = self.targetUser.displayName;
  856. }
  857. WFCCUserInfo *myself = [[WFCCIMService sharedWFCIMService] getUserInfo:[WFCCNetworkService sharedInstance].userId refresh:NO];
  858. compositeContent.title = [NSString stringWithFormat:@"%@和%@ 的聊天记录", title, myself.displayName];
  859. } else if (self.conversation.type == Group_Type) {
  860. compositeContent.title = WFCString(@"GroupChatHistory");
  861. } else if (self.conversation.type == Channel_Type) {
  862. compositeContent.title = WFCString(@"ChannelChatHistory");
  863. } else if(self.conversation.type == SecretChat_Type) {
  864. compositeContent.title = WFCString(@"SecretChatHistory");
  865. } else {
  866. compositeContent.title = WFCString(@"ChatHistory");
  867. }
  868. compositeContent.messages = messages;
  869. WFCCMessage *msg = [[WFCCMessage alloc] init];
  870. msg.content = compositeContent;
  871. WFCUForwardViewController *controller = [[WFCUForwardViewController alloc] init];
  872. controller.message = msg;
  873. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
  874. [self.navigationController presentViewController:navi animated:YES completion:nil];
  875. }];
  876. [alertController addAction:cancelAction];
  877. [alertController addAction:oneByOneAction];
  878. [alertController addAction:AllInOneAction];
  879. [self presentViewController:alertController animated:YES completion:nil];
  880. }
  881. - (void)scrollToBottom:(BOOL)animated {
  882. NSUInteger rowCount = [self.collectionView numberOfItemsInSection:0];
  883. if (rowCount == 0) {
  884. return;
  885. }
  886. NSUInteger finalRow = rowCount - 1;
  887. for (int i = 0; i < self.modelList.count; i++) {
  888. if ([self.modelList objectAtIndex:i].highlighted) {
  889. finalRow = i;
  890. break;
  891. }
  892. }
  893. __block BOOL noNeedScroll = NO;
  894. if (finalRow == rowCount -1) {
  895. [[self.collectionView indexPathsForVisibleItems] enumerateObjectsUsingBlock:^(NSIndexPath * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  896. if(obj.row > finalRow) {
  897. *stop = YES;
  898. noNeedScroll = YES;
  899. }
  900. }];
  901. }
  902. if (!noNeedScroll) {
  903. NSIndexPath *finalIndexPath = [NSIndexPath indexPathForItem:finalRow inSection:0];
  904. [self.collectionView scrollToItemAtIndexPath:finalIndexPath
  905. atScrollPosition:UICollectionViewScrollPositionBottom
  906. animated:animated];
  907. }
  908. [self dismissNewMsgTip];
  909. }
  910. - (void)initializedSubViews {
  911. UICollectionViewFlowLayout *_customFlowLayout = [[UICollectionViewFlowLayout alloc] init];
  912. _customFlowLayout.minimumLineSpacing = 0.0f;
  913. _customFlowLayout.sectionInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
  914. _customFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
  915. _customFlowLayout.headerReferenceSize = CGSizeMake(320.0f, 20.0f);
  916. CGRect frame = self.view.bounds;
  917. frame.origin.y += [WFCUUtilities wf_navigationFullHeight];
  918. frame.size.height -= ([WFCUUtilities wf_safeDistanceBottom] + [WFCUUtilities wf_navigationFullHeight]);
  919. self.backgroundView = [[UIView alloc] initWithFrame:frame];
  920. [self.view addSubview:self.backgroundView];
  921. self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.backgroundView.bounds.size.width, self.backgroundView.bounds.size.height - CHAT_INPUT_BAR_HEIGHT) collectionViewLayout:_customFlowLayout];
  922. [self.backgroundView addSubview:self.collectionView];
  923. self.backgroundView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
  924. self.collectionView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
  925. self.collectionView.showsHorizontalScrollIndicator = NO;
  926. self.collectionView.showsVerticalScrollIndicator = NO;
  927. self.collectionView.alwaysBounceVertical = YES;
  928. self.view.backgroundColor = self.collectionView.backgroundColor;
  929. [self registerCell:[WFCUTextCell class] forContent:[WFCCTextMessageContent class]];
  930. [self registerCell:[WFCUTextCell class] forContent:[WFCCPTextMessageContent class]];
  931. [self registerCell:[WFCUImageCell class] forContent:[WFCCImageMessageContent class]];
  932. [self registerCell:[WFCUVoiceCell class] forContent:[WFCCSoundMessageContent class]];
  933. [self registerCell:[WFCUVoiceCell class] forContent:[WFCCPTTSoundMessageContent class]];
  934. [self registerCell:[WFCUVideoCell class] forContent:[WFCCVideoMessageContent class]];
  935. [self registerCell:[WFCULocationCell class] forContent:[WFCCLocationMessageContent class]];
  936. [self registerCell:[WFCUFileCell class] forContent:[WFCCFileMessageContent class]];
  937. [self registerCell:[WFCUStickerCell class] forContent:[WFCCStickerMessageContent class]];
  938. [self registerCell:[WFCUInformationCell class] forContent:[WFCCCreateGroupNotificationContent class]];
  939. [self registerCell:[WFCUInformationCell class] forContent:[WFCCAddGroupeMemberNotificationContent class]];
  940. [self registerCell:[WFCUInformationCell class] forContent:[WFCCKickoffGroupMemberNotificationContent class]];
  941. [self registerCell:[WFCUInformationCell class] forContent:[WFCCQuitGroupNotificationContent class]];
  942. [self registerCell:[WFCUInformationCell class] forContent:[WFCCKickoffGroupMemberVisibleNotificationContent class]];
  943. [self registerCell:[WFCUInformationCell class] forContent:[WFCCQuitGroupVisibleNotificationContent class]];
  944. [self registerCell:[WFCUInformationCell class] forContent:[WFCCDismissGroupNotificationContent class]];
  945. [self registerCell:[WFCUInformationCell class] forContent:[WFCCTransferGroupOwnerNotificationContent class]];
  946. [self registerCell:[WFCUInformationCell class] forContent:[WFCCModifyGroupAliasNotificationContent class]];
  947. [self registerCell:[WFCUInformationCell class] forContent:[WFCCChangeGroupNameNotificationContent class]];
  948. [self registerCell:[WFCUInformationCell class] forContent:[WFCCChangeGroupPortraitNotificationContent class]];
  949. [self registerCell:[WFCUInformationCell class] forContent:[WFCCFriendAddedMessageContent class]];
  950. [self registerCell:[WFCUInformationCell class] forContent:[WFCCFriendGreetingMessageContent class]];
  951. [self registerCell:[WFCUInformationCell class] forContent:[WFCCNotDeliveredMessageContent class]];
  952. [self registerCell:[WFCUCallSummaryCell class] forContent:[WFCCCallStartMessageContent class]];
  953. [self registerCell:[WFCUInformationCell class] forContent:[WFCCTipNotificationContent class]];
  954. [self registerCell:[WFCUInformationCell class] forContent:[WFCCUnknownMessageContent class]];
  955. [self registerCell:[WFCURecallCell class] forContent:[WFCCRecallMessageContent class]];
  956. [self registerCell:[WFCUConferenceInviteCell class] forContent:[WFCCConferenceInviteMessageContent class]];
  957. [self registerCell:[WFCUCardCell class] forContent:[WFCCCardMessageContent class]];
  958. [self registerCell:[WFCUCompositeCell class] forContent:[WFCCCompositeMessageContent class]];
  959. [self registerCell:[WFCULinkCell class] forContent:[WFCCLinkMessageContent class]];
  960. [self registerCell:[WFCURichNotificationCell class] forContent:[WFCCRichNotificationMessageContent class]];
  961. [self registerCell:[WFCUArticlesCell class] forContent:[WFCCArticlesMessageContent class]];
  962. [self registerCell:[WFCUStreamingTextCell class] forContent:[WFCCStreamingTextGeneratedMessageContent class]];
  963. [self registerCell:[WFCUStreamingTextCell class] forContent:[WFCCStreamingTextGeneratingMessageContent class]];
  964. [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
  965. [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView"];
  966. self.collectionView.dataSource = self;
  967. self.collectionView.delegate = self;
  968. self.ongoingCallTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
  969. self.ongoingCallTableView.delegate = self;
  970. self.ongoingCallTableView.dataSource = self;
  971. self.ongoingCallTableView.backgroundColor = [UIColor clearColor];
  972. [self.view addSubview:self.ongoingCallTableView];
  973. }
  974. - (void)registerCell:(Class)cellCls forContent:(Class)msgContentCls {
  975. [self.collectionView registerClass:cellCls
  976. forCellWithReuseIdentifier:[NSString stringWithFormat:@"%d", [msgContentCls getContentType]]];
  977. [self.cellContentDict setObject:cellCls forKey:@([msgContentCls getContentType])];
  978. }
  979. - (void)removeUserTyping:(NSString *)userId {
  980. [self.typingDict removeObjectForKey:userId];
  981. [self showTyping];
  982. }
  983. - (void)showUser:(NSString *)userId typing:(WFCCTypingType)typingType {
  984. int64_t now = [[[NSDate alloc] init] timeIntervalSince1970];
  985. [self.typingDict setValue:@{@"timestamp":@(now), @"type":@(typingType)} forKey:userId];
  986. [self showTyping];
  987. }
  988. - (void)showTyping {
  989. if(self.conversation.type == Channel_Type || self.conversation.type == Chatroom_Type) {
  990. return;
  991. }
  992. if (self.showTypingTimer) {
  993. [self.showTypingTimer invalidate];
  994. }
  995. self.showTypingTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(checkUserTyping) userInfo:nil repeats:NO];
  996. [[NSRunLoop mainRunLoop] addTimer:self.showTypingTimer forMode:NSDefaultRunLoopMode];
  997. if(self.typingDict.count == 1) {
  998. NSString *userId = self.typingDict.allKeys[0];
  999. NSDictionary *dict = self.typingDict[userId];
  1000. WFCCTypingType typingType = [dict[@"type"] intValue];
  1001. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:userId inGroup:self.conversation.type == Group_Type?self.conversation.target:nil refresh:NO];
  1002. NSString *name = @"有人";
  1003. if(userInfo.friendAlias.length) {
  1004. name = userInfo.friendAlias;
  1005. } else if(userInfo.groupAlias.length) {
  1006. name = userInfo.groupAlias;
  1007. } else if(userInfo.displayName.length) {
  1008. name = userInfo.displayName;
  1009. }
  1010. NSString *title;
  1011. if(typingType == Typing_VOICE) {
  1012. title = WFCString(@"RecordingHint");
  1013. } else if(typingType == Typing_CAMERA) {
  1014. title = WFCString(@"PhotographingHint");
  1015. } else if(typingType == Typing_LOCATION) {
  1016. title = WFCString(@"GetLocationHint");
  1017. } else if(typingType == Typing_FILE) {
  1018. title = WFCString(@"SelectingFileHint");
  1019. } else {
  1020. title = WFCString(@"TypingHint");
  1021. }
  1022. self.title = [NSString stringWithFormat:@"%@ %@", name, title];
  1023. } else if(self.typingDict.count > 1) {
  1024. self.title = [NSString stringWithFormat:@"%ld人正在输入", self.typingDict.count];
  1025. }
  1026. }
  1027. - (void)checkUserTyping {
  1028. NSMutableArray<NSString *> *expiredKeys = [[NSMutableArray alloc] init];
  1029. int64_t now = [[[NSDate alloc] init] timeIntervalSince1970];
  1030. [self.typingDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSDictionary * _Nonnull obj, BOOL * _Nonnull stop) {
  1031. int64_t timestamp = [obj[@"timestamp"] longLongValue];
  1032. if(now - timestamp > 5) {
  1033. [expiredKeys addObject:key];
  1034. }
  1035. }];
  1036. [self.typingDict removeObjectsForKeys:expiredKeys];
  1037. if(self.typingDict.count) {
  1038. [self showTyping];
  1039. } else {
  1040. [self stopShowTyping];
  1041. }
  1042. }
  1043. - (void)stopShowTyping {
  1044. if(self.showTypingTimer != nil) {
  1045. [self.showTypingTimer invalidate];
  1046. self.showTypingTimer = nil;
  1047. if (self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  1048. self.targetUser = self.targetUser;
  1049. } else if(self.conversation.type == Group_Type) {
  1050. self.targetGroup = self.targetGroup;
  1051. } else if(self.conversation.type == Channel_Type) {
  1052. self.targetChannel = self.targetChannel;
  1053. } else if(self.conversation.type == Group_Type) {
  1054. self.targetGroup = self.targetGroup;
  1055. }
  1056. }
  1057. }
  1058. - (void)onResetKeyboard:(id)sender {
  1059. [self.chatInputBar resetInputBarStatue];
  1060. }
  1061. - (void)didReceiveMemoryWarning {
  1062. [super didReceiveMemoryWarning];
  1063. }
  1064. - (void)viewWillAppear:(BOOL)animated {
  1065. [super viewWillAppear:animated];
  1066. if (!self.firstAppear) {
  1067. [self.chatInputBar willAppear];
  1068. }
  1069. self.tabBarController.tabBar.hidden = YES;
  1070. [self.collectionView reloadData];
  1071. if (self.navigationController.viewControllers.count > 1) { // 记录系统返回手势的代理
  1072. _scrollBackDelegate = self.navigationController.interactivePopGestureRecognizer.delegate; // 设置系统返回手势的代理为当前控制器
  1073. self.navigationController.interactivePopGestureRecognizer.delegate = self;
  1074. }
  1075. if (self.conversation.type == Group_Type) {
  1076. self.showAlias = ![[WFCCIMService sharedWFCIMService] isHiddenGroupMemberName:self.targetGroup.target];
  1077. }
  1078. if (self.firstAppear) {
  1079. self.firstAppear = NO;
  1080. [self scrollToBottom:NO];
  1081. }
  1082. [self updateTitle];
  1083. }
  1084. - (void)viewDidAppear:(BOOL)animated {
  1085. [super viewDidAppear:animated];
  1086. }
  1087. - (void)viewWillDisappear:(BOOL)animated {
  1088. [super viewWillDisappear:animated];
  1089. NSString *newDraft = self.chatInputBar.draft;
  1090. if (![self.orignalDraft isEqualToString:newDraft]) {
  1091. self.orignalDraft = newDraft;
  1092. [[WFCCIMService sharedWFCIMService] setConversation:self.conversation draft:newDraft];
  1093. }
  1094. // 设置系统返回手势的代理为我们刚进入控制器的时候记录的系统的返回手势代理
  1095. self.navigationController.interactivePopGestureRecognizer.delegate = _scrollBackDelegate;
  1096. [self.chatInputBar resetInputBarStatue];
  1097. }
  1098. - (void)sendMessage:(WFCCMessageContent *)content {
  1099. //发送消息时,client会发出"kSendingMessageStatusUpdated“的通知,消息界面收到通知后加入到列表中。
  1100. __weak typeof(self) ws = self;
  1101. NSMutableArray *tousers = nil;
  1102. if (self.privateChatUser) {
  1103. tousers = [[NSMutableArray alloc] init];
  1104. [tousers addObject:self.privateChatUser];
  1105. }
  1106. [[WFCCIMService sharedWFCIMService] send:self.conversation content:content toUsers:tousers expireDuration:0 success:^(long long messageUid, long long timestamp) {
  1107. NSLog(@"send message success");
  1108. if ([content isKindOfClass:[WFCCStickerMessageContent class]]) {
  1109. [ws saveStickerRemoteUrl:(WFCCStickerMessageContent *)content];
  1110. }
  1111. if(![content isKindOfClass:[WFCCTypingMessageContent class]]) {
  1112. [ws.chatInputBar resetTyping];
  1113. }
  1114. } error:^(int error_code) {
  1115. NSLog(@"send message fail(%d)", error_code);
  1116. }];
  1117. }
  1118. - (void)onReceiveCallOngoingNotifications:(NSArray<WFCCMessage *> *)messages {
  1119. [messages enumerateObjectsUsingBlock:^(WFCCMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1120. WFCCMultiCallOngoingMessageContent *ongoing = (WFCCMultiCallOngoingMessageContent *)obj.content;
  1121. self.ongoingCallDict[ongoing.callId] = obj;
  1122. }];
  1123. [[self.ongoingCallDict allKeys] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1124. WFCCMessage *msg = self.ongoingCallDict[obj];
  1125. if(([[NSDate date] timeIntervalSince1970] - (msg.serverTime - [WFCCNetworkService sharedInstance].serverDeltaTime)/1000) > 3) {
  1126. [self.ongoingCallDict removeObjectForKey:obj];
  1127. }
  1128. }];
  1129. if(![WFCUConfigManager globalManager].enableMultiCallAutoJoin) {
  1130. [self.ongoingCallDict removeAllObjects];
  1131. }
  1132. if(self.ongoingCallDict.count) {
  1133. self.ongoingCallTableView.frame = CGRectMake(0, [WFCUUtilities wf_navigationFullHeight], self.view.bounds.size.width, MIN(200, self.ongoingCallDict.count * 28 + 28));
  1134. [self.ongoingCallTableView reloadData];
  1135. if(!self.checkOngoingCallTimer) {
  1136. if (@available(iOS 10.0, *)) {
  1137. __weak typeof(self)ws = self;
  1138. self.checkOngoingCallTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
  1139. [ws onReceiveCallOngoingNotifications:@[]];
  1140. }];
  1141. } else {
  1142. // Fallback on earlier versions
  1143. }
  1144. }
  1145. } else {
  1146. self.ongoingCallTableView.frame = CGRectMake(0, [WFCUUtilities wf_navigationFullHeight], self.view.bounds.size.width, 0);
  1147. if(self.checkOngoingCallTimer) {
  1148. [self.checkOngoingCallTimer invalidate];
  1149. self.checkOngoingCallTimer = nil;
  1150. }
  1151. self.focusedOngoingCellIndex = -1;
  1152. }
  1153. }
  1154. - (void)onReceiveMessages:(NSNotification *)notification {
  1155. NSArray<WFCCMessage *> *messages = notification.object;
  1156. [self appendMessages:messages newMessage:YES highlightId:0 forceButtom:NO];
  1157. NSMutableArray<WFCCMessage *> *ongoingCalls = [[NSMutableArray alloc] init];
  1158. for (WFCCMessage *msg in messages) {
  1159. if([msg.content isKindOfClass:WFCCMultiCallOngoingMessageContent.class] && [msg.conversation isEqual:self.conversation]) {
  1160. [ongoingCalls addObject:msg];
  1161. }
  1162. }
  1163. if(ongoingCalls.count) {
  1164. [self onReceiveCallOngoingNotifications:ongoingCalls];
  1165. }
  1166. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:self.conversation];
  1167. }
  1168. - (void)updateQuotedMessageWhenRecall:(long long)messageUid {
  1169. for (int i = 0; i < self.modelList.count; i++) {
  1170. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1171. if ([model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  1172. WFCCTextMessageContent *txtMsg = (WFCCTextMessageContent *)model.message.content;
  1173. if(txtMsg.quoteInfo.messageUid == messageUid) {
  1174. [model loadQuotedMessage];
  1175. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1176. }
  1177. }
  1178. }
  1179. }
  1180. - (void)onRecallMessages:(NSNotification *)notification {
  1181. long long messageUid = [notification.object longLongValue];
  1182. if (self.conversation.type != Chatroom_Type) {
  1183. WFCCMessage *msg = [[WFCCIMService sharedWFCIMService] getMessageByUid:messageUid];
  1184. if (msg != nil) {
  1185. for (int i = 0; i < self.modelList.count; i++) {
  1186. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1187. if (model.message.messageUid == messageUid) {
  1188. model.message = msg;
  1189. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1190. break;
  1191. }
  1192. }
  1193. } else {
  1194. for (int i = 0; i < self.modelList.count; i++) {
  1195. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1196. if (model.message.messageUid == messageUid) {
  1197. [self.modelList removeObject:model];
  1198. [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1199. break;
  1200. }
  1201. }
  1202. }
  1203. } else {
  1204. for (int i = 0; i < self.modelList.count; i++) {
  1205. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1206. if (model.message.messageUid == messageUid) {
  1207. WFCCRecallMessageContent *recallContent = [[WFCCRecallMessageContent alloc] init];
  1208. recallContent.messageUid = messageUid;
  1209. recallContent.operatorId = model.message.fromUser;
  1210. recallContent.originalSender = model.message.fromUser;
  1211. model.message.content = recallContent;
  1212. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1213. break;
  1214. }
  1215. }
  1216. }
  1217. [self updateQuotedMessageWhenRecall:messageUid];
  1218. }
  1219. - (void)onDeleteMessages:(NSNotification *)notification {
  1220. long long messageUid = [notification.object longLongValue];
  1221. for (int i = 0; i < self.modelList.count; i++) {
  1222. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1223. if (model.message.messageUid == messageUid) {
  1224. [self.modelList removeObject:model];
  1225. [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1226. break;
  1227. }
  1228. }
  1229. }
  1230. - (void)onMessageUpdated:(NSNotification *)notification {
  1231. long messageId = [notification.object longValue];
  1232. BOOL isUpdated = NO;
  1233. for (WFCUMessageModel *model in self.modelList) {
  1234. if(model.message.messageId == messageId) {
  1235. if(model.message.conversation.type != Chatroom_Type) {
  1236. model.message = [[WFCCIMService sharedWFCIMService] getMessage:messageId];
  1237. if(!model.message) {
  1238. [self.modelList removeObject:model];
  1239. isUpdated = YES;
  1240. break;
  1241. }
  1242. }
  1243. isUpdated = YES;
  1244. break;
  1245. }
  1246. }
  1247. if(isUpdated) {
  1248. [self.modelList sortUsingComparator:^NSComparisonResult(WFCUMessageModel *obj1, WFCUMessageModel *obj2) {
  1249. if (obj1.message.serverTime > obj2.message.serverTime) {
  1250. return NSOrderedDescending;
  1251. } else if(obj1.message.serverTime == obj2.message.serverTime) {
  1252. return NSOrderedSame;
  1253. } else {
  1254. return NSOrderedAscending;
  1255. }
  1256. }];
  1257. [self.collectionView reloadData];
  1258. }
  1259. }
  1260. - (void)onMessageDelivered:(NSNotification *)notification {
  1261. if (self.conversation.type != Single_Type && self.conversation.type != Group_Type && self.conversation.type != SecretChat_Type) {
  1262. return;
  1263. }
  1264. NSArray<WFCCGroupMember *> *members = nil;
  1265. if (self.conversation.type == Group_Type) {
  1266. members = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  1267. }
  1268. NSArray<WFCCDeliveryReport *> *delivereds = notification.object;
  1269. __block BOOL refresh = NO;
  1270. [delivereds enumerateObjectsUsingBlock:^(WFCCDeliveryReport * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1271. if (self.conversation.type == Single_Type) {
  1272. if ([self.conversation.target isEqualToString:obj.userId]) {
  1273. *stop = YES;
  1274. refresh = YES;
  1275. }
  1276. } else if (self.conversation.type == Group_Type) {
  1277. for (WFCCGroupMember *member in members) {
  1278. if ([member.memberId isEqualToString:obj.userId]) {
  1279. *stop = YES;
  1280. refresh = YES;
  1281. }
  1282. }
  1283. } else if(self.conversation.type == SecretChat_Type) {
  1284. NSString *userId = self.secretChatInfo.userId;
  1285. if ([userId isEqualToString:obj.userId]) {
  1286. *stop = YES;
  1287. refresh = YES;
  1288. }
  1289. }
  1290. }];
  1291. if (refresh) {
  1292. self.deliveryDict = [[WFCCIMService sharedWFCIMService] getMessageDelivery:self.conversation];
  1293. WFCCGroupInfo *groupInfo = nil;
  1294. for (int i = 0; i < self.modelList.count; i++) {
  1295. WFCUMessageModel *model = self.modelList[i];
  1296. model.deliveryDict = self.deliveryDict;
  1297. if (model.message.direction == MessageDirection_Receive || model.deliveryRate == 1.f) {
  1298. continue;
  1299. }
  1300. if (self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  1301. NSString *userId = model.message.conversation.target;
  1302. if(self.conversation.type == SecretChat_Type) {
  1303. userId = self.secretChatInfo.userId;
  1304. }
  1305. if (model.message.serverTime <= [[model.deliveryDict objectForKey:userId] longLongValue]) {
  1306. float rate = 1.f;
  1307. if (rate != model.deliveryRate) {
  1308. model.deliveryRate = rate;
  1309. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1310. }
  1311. }
  1312. } else { //group
  1313. long long messageTS = model.message.serverTime;
  1314. __block int delieveriedCount = 0;
  1315. [model.deliveryDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
  1316. if ([obj longLongValue] >= messageTS) {
  1317. delieveriedCount++;
  1318. }
  1319. }];
  1320. if (!groupInfo) {
  1321. groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:model.message.conversation.target refresh:NO];
  1322. }
  1323. float rate = (float)delieveriedCount/(groupInfo.memberCount - 1);
  1324. if (rate != model.deliveryRate) {
  1325. model.deliveryRate = rate;
  1326. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1327. }
  1328. }
  1329. }
  1330. }
  1331. }
  1332. - (void)onMessageReaded:(NSNotification *)notification {
  1333. if (self.conversation.type != Single_Type && self.conversation.type != Group_Type && self.conversation.type != SecretChat_Type) {
  1334. return;
  1335. }
  1336. NSArray<WFCCReadReport *> *readeds = notification.object;
  1337. __block BOOL refresh = NO;
  1338. [readeds enumerateObjectsUsingBlock:^(WFCCReadReport * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1339. if ([obj.conversation isEqual:self.conversation]) {
  1340. *stop = YES;
  1341. refresh = YES;
  1342. }
  1343. }];
  1344. if (refresh) {
  1345. self.readDict = [[WFCCIMService sharedWFCIMService] getConversationRead:self.conversation];
  1346. if(self.conversation.type == Group_Type) {
  1347. NSArray<WFCCGroupMember *> *members = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  1348. NSMutableArray<NSString *> *tobeRemoveKeys = [[NSMutableArray alloc] init];
  1349. [self.readDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
  1350. BOOL exist = NO;
  1351. for (WFCCGroupMember *member in members) {
  1352. if([member.memberId isEqualToString:key]) {
  1353. exist = YES;
  1354. }
  1355. }
  1356. if(!exist) {
  1357. [tobeRemoveKeys addObject:key];
  1358. }
  1359. }];
  1360. [self.readDict removeObjectsForKeys:tobeRemoveKeys];
  1361. }
  1362. WFCCGroupInfo *groupInfo = nil;
  1363. for (int i = 0; i < self.modelList.count; i++) {
  1364. WFCUMessageModel *model = self.modelList[i];
  1365. model.readDict = self.readDict;
  1366. if (model.message.direction == MessageDirection_Receive || model.readRate == 1.f) {
  1367. continue;
  1368. }
  1369. if (self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  1370. NSString *userId = model.message.conversation.target;
  1371. if(self.conversation.type == SecretChat_Type) {
  1372. userId = self.secretChatInfo.userId;
  1373. }
  1374. if (model.message.serverTime <= [[model.readDict objectForKey:userId] longLongValue]) {
  1375. float rate = 1.f;
  1376. if (rate != model.readRate) {
  1377. model.readRate = rate;
  1378. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1379. }
  1380. }
  1381. } else { //group
  1382. long long messageTS = model.message.serverTime;
  1383. __block int delieveriedCount = 0;
  1384. [model.readDict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSNumber * _Nonnull obj, BOOL * _Nonnull stop) {
  1385. if ([obj longLongValue] >= messageTS) {
  1386. delieveriedCount++;
  1387. }
  1388. }];
  1389. if (!groupInfo) {
  1390. groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:model.message.conversation.target refresh:NO];
  1391. }
  1392. float rate = (float)delieveriedCount/(groupInfo.memberCount - 1);
  1393. if (rate != model.readRate) {
  1394. model.readRate = rate;
  1395. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  1396. }
  1397. }
  1398. }
  1399. }
  1400. }
  1401. #if WFCU_SUPPORT_VOIP
  1402. - (void)onCallStateChanged:(NSNotification *)notification {
  1403. long long messageUid = [[notification.userInfo objectForKey:@"messageUid"] longLongValue];
  1404. WFCCMessage *msg = [[WFCCIMService sharedWFCIMService] getMessageByUid:messageUid];
  1405. for (int i = 0; i < self.modelList.count; i++) {
  1406. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1407. if (model.message.messageUid == messageUid) {
  1408. model.message.content = msg.content;
  1409. [self.collectionView reloadData];
  1410. break;
  1411. }
  1412. }
  1413. if ([[notification.userInfo objectForKey:@"state"] intValue] == kWFAVEngineStateIncomming) {
  1414. if ([[[UIDevice currentDevice] systemVersion] rangeOfString:@"10."].location == 0) {
  1415. [self.chatInputBar resetInputBarStatue];
  1416. }
  1417. }
  1418. }
  1419. #endif
  1420. - (void)onSendingMessage:(NSNotification *)notification {
  1421. WFCCMessage *message = [notification.userInfo objectForKey:@"message"];
  1422. WFCCMessageStatus status = [[notification.userInfo objectForKey:@"status"] integerValue];
  1423. if ((status == Message_Status_Sending || status == Message_Status_Sent) && message.messageId != 0) {
  1424. if ([message.conversation isEqual:self.conversation]) {
  1425. [self appendMessages:@[message] newMessage:YES highlightId:0 forceButtom:YES];
  1426. }
  1427. }
  1428. }
  1429. - (void)onMessageListChanged:(NSNotification *)notification {
  1430. if([notification.object isEqual:self.conversation]) {
  1431. [self reloadMessageList];
  1432. }
  1433. }
  1434. - (void)onSettingUpdated:(NSNotification *)notification {
  1435. WFCCConversationInfo *info = [[WFCCIMService sharedWFCIMService] getConversationInfo:self.conversation];
  1436. NSString *orignalDraftText = [self.chatInputBar getDraftText:self.orignalDraft];
  1437. NSString *draftText = [self.chatInputBar getDraftText:info.draft];
  1438. if(![orignalDraftText isEqualToString:draftText]) {
  1439. self.orignalDraft = info.draft;
  1440. self.chatInputBar.draft = info.draft;
  1441. }
  1442. }
  1443. - (void)onSecretChatStateChanged:(NSNotification *)notification {
  1444. if(self.conversation.type == SecretChat_Type && [self.conversation.target isEqualToString:notification.object]) {
  1445. self.secretChatInfo = [[WFCCIMService sharedWFCIMService] getSecretChatInfo:self.conversation.target];
  1446. WFCCSecretChatState state = (WFCCSecretChatState)[notification.userInfo[@"state"] intValue];
  1447. if(state == SecretChatState_Canceled) {
  1448. [self.navigationController popToRootViewControllerAnimated:YES];
  1449. } else {
  1450. [self reloadMessageList];
  1451. }
  1452. }
  1453. }
  1454. - (void)onSecretMessageBurned:(NSNotification *)notification {
  1455. if(self.conversation.type == SecretChat_Type) {
  1456. NSArray *messageIds = notification.userInfo[@"messageIds"];
  1457. NSMutableArray *deletedModels = [[NSMutableArray alloc] init];
  1458. NSMutableArray *deletedItems = [[NSMutableArray alloc] init];
  1459. [self.modelList enumerateObjectsUsingBlock:^(WFCUMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1460. if([messageIds containsObject:@(obj.message.messageId)]) {
  1461. [deletedModels addObject:obj];
  1462. [deletedItems addObject:[NSIndexPath indexPathForRow:idx inSection:0]];
  1463. }
  1464. }];
  1465. [self.modelList removeObjectsInArray:deletedModels];
  1466. [self.collectionView deleteItemsAtIndexPaths:deletedItems];
  1467. }
  1468. }
  1469. - (void)onSecretMessageStartBurning:(NSNotification *)notification {
  1470. if(self.conversation.type == SecretChat_Type) {
  1471. NSString *targetId = (NSString *)notification.object;
  1472. if(targetId.length) {
  1473. //普通消息开始计时阅后即焚
  1474. } else {
  1475. long long playedMsgUid = [notification.userInfo[@"messageId"] longLongValue];
  1476. for (int i = 0; i < self.modelList.count; ++i) {
  1477. WFCUMessageModel *model = self.modelList[i];
  1478. if(model.message.messageUid == playedMsgUid) {
  1479. //媒体类消息开始阅后即焚
  1480. }
  1481. }
  1482. }
  1483. }
  1484. }
  1485. - (void)reloadMessageList {
  1486. self.deliveryDict = [[WFCCIMService sharedWFCIMService] getMessageDelivery:self.conversation];
  1487. self.readDict = [[WFCCIMService sharedWFCIMService] getConversationRead:self.conversation];
  1488. NSArray *messageList;
  1489. WFCCMessage *highlightMessage;
  1490. if (self.highlightMessageId > 0) {
  1491. highlightMessage = [[WFCCIMService sharedWFCIMService] getMessage:self.highlightMessageId];
  1492. }
  1493. if (self.highlightMessageId > 0 && highlightMessage) {
  1494. NSArray *messageListOld = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:self.highlightMessageId count:15 withUser:self.privateChatUser];
  1495. NSArray *messageListNew = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:nil from:self.highlightMessageId count:-15 withUser:self.privateChatUser];
  1496. NSMutableArray *list = [[NSMutableArray alloc] init];
  1497. [list addObjectsFromArray:messageListNew];
  1498. [list addObject:highlightMessage];
  1499. [list addObjectsFromArray:messageListOld];
  1500. messageList = [list copy];
  1501. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:self.conversation];
  1502. if (messageListNew.count == 15) {
  1503. self.hasNewMessage = YES;
  1504. }
  1505. self.modelList = [[NSMutableArray alloc] init];
  1506. [self appendMessages:messageList newMessage:NO highlightId:self.highlightMessageId forceButtom:NO];
  1507. self.highlightMessageId = 0;
  1508. if(self.conversation.type == SecretChat_Type) {
  1509. WFCCSecretChatInfo *secretChatInfo = [[WFCCIMService sharedWFCIMService] getSecretChatInfo:self.conversation.target];
  1510. if(secretChatInfo.state == SecretChatState_Established) {
  1511. if(self.chatInputBar.inputBarStatus == ChatInputBarMuteStatus) {
  1512. self.chatInputBar.inputBarStatus = ChatInputBarDefaultStatus;
  1513. }
  1514. } else {
  1515. if(self.chatInputBar.inputBarStatus != ChatInputBarMuteStatus) {
  1516. self.chatInputBar.inputBarStatus = ChatInputBarMuteStatus;
  1517. }
  1518. }
  1519. }
  1520. } else {
  1521. BOOL firstIn = NO;
  1522. int count = (int)self.modelList.count;
  1523. if(count == 0) {
  1524. firstIn = YES;
  1525. }
  1526. count = 15;
  1527. __weak typeof(self)ws = self;
  1528. [[WFCCIMService sharedWFCIMService] getMessagesV2:self.conversation contentTypes:nil from:0 count:count withUser:self.privateChatUser success:^(NSArray<WFCCMessage *> *messages) {
  1529. [[WFCCIMService sharedWFCIMService] getMessagesV2:ws.conversation messageStatus:@[@(Message_Status_Mentioned), @(Message_Status_AllMentioned)] from:0 count:100 withUser:ws.privateChatUser success:^(NSArray<WFCCMessage *> *messages) {
  1530. ws.mentionedMsgs = [messages mutableCopy];
  1531. if (ws.mentionedMsgs.count) {
  1532. [ws showMentionedLabel];
  1533. }
  1534. } error:^(int error_code) {
  1535. }];
  1536. if (firstIn) {
  1537. WFCCConversationInfo *info = [[WFCCIMService sharedWFCIMService] getConversationInfo:ws.conversation];
  1538. if (info.unreadCount.unread >= 10 && info.unreadCount.unread < 300) { //如果消息太多了就没有必要显示新消息了
  1539. ws.unreadMessageCount = info.unreadCount.unread;
  1540. ws.firstUnreadMessageId = [[WFCCIMService sharedWFCIMService] getFirstUnreadMessageId:ws.conversation];
  1541. [ws showUnreadLabel];
  1542. }
  1543. [[WFCCIMService sharedWFCIMService] clearUnreadStatus:ws.conversation];
  1544. }
  1545. ws.modelList = [[NSMutableArray alloc] init];
  1546. [ws appendMessages:messages newMessage:NO highlightId:ws.highlightMessageId forceButtom:NO];
  1547. ws.highlightMessageId = 0;
  1548. if(ws.conversation.type == SecretChat_Type) {
  1549. WFCCSecretChatInfo *secretChatInfo = [[WFCCIMService sharedWFCIMService] getSecretChatInfo:ws.conversation.target];
  1550. if(secretChatInfo.state == SecretChatState_Established) {
  1551. if(ws.chatInputBar.inputBarStatus == ChatInputBarMuteStatus) {
  1552. ws.chatInputBar.inputBarStatus = ChatInputBarDefaultStatus;
  1553. }
  1554. } else {
  1555. if(ws.chatInputBar.inputBarStatus != ChatInputBarMuteStatus) {
  1556. ws.chatInputBar.inputBarStatus = ChatInputBarMuteStatus;
  1557. }
  1558. }
  1559. }
  1560. } error:^(int error_code) {
  1561. }];
  1562. return;
  1563. }
  1564. }
  1565. - (void)showMentionedLabel {
  1566. if (!self.mentionedButton) {
  1567. CGRect bount = self.view.bounds;
  1568. self.mentionedButton = [[UIButton alloc] initWithFrame:CGRectMake(bount.size.width+15, 240, 0, 30)];
  1569. self.mentionedButton.titleLabel.font = [UIFont systemFontOfSize:12];
  1570. [self.mentionedButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
  1571. self.mentionedButton.backgroundColor = [UIColor whiteColor];
  1572. self.mentionedButton.layer.cornerRadius = 15;
  1573. self.mentionedButton.layer.borderColor = [UIColor blackColor].CGColor;
  1574. [self.mentionedButton addTarget:self action:@selector(onMentionedBtn:) forControlEvents:UIControlEventTouchUpInside];
  1575. [self.view addSubview:self.mentionedButton];
  1576. [UIView animateWithDuration:0.8 animations:^{
  1577. self.mentionedButton.frame = CGRectMake(bount.size.width - 85, 240, 100, 30);
  1578. }];
  1579. }
  1580. [self.mentionedButton setTitle:[NSString stringWithFormat:@"%d 条@消息", self.mentionedMsgs.count] forState:UIControlStateNormal];
  1581. }
  1582. - (void)dismissMentionedLabel {
  1583. CGRect bount = self.view.bounds;
  1584. [UIView animateWithDuration:0.5 animations:^{
  1585. self.mentionedButton.frame = CGRectMake(bount.size.width+15, 240, 0, 30);
  1586. } completion:^(BOOL finished) {
  1587. [self.mentionedButton removeFromSuperview];
  1588. self.mentionedButton = nil;
  1589. }];
  1590. }
  1591. - (void)onMentionedBtn:(id)sender {
  1592. if (![self checkLastMentionedMsgLoaded]) {
  1593. [self loadMoreToLastMention];
  1594. } else {
  1595. [self scrollToLastMentionedMessage];
  1596. }
  1597. }
  1598. - (void)loadMoreToLastMention {
  1599. __weak typeof(self)ws = self;
  1600. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
  1601. [self loadMoreMessage:YES completion:^(BOOL more){
  1602. if (more && ![ws checkLastMentionedMsgLoaded]) {
  1603. [ws loadMoreToLastMention];
  1604. } else {
  1605. [ws scrollToLastMentionedMessage];
  1606. }
  1607. }];
  1608. }
  1609. - (void)scrollToLastMentionedMessage {
  1610. for (int i = 0; i < self.modelList.count; i++) {
  1611. if (self.modelList[i].message.messageId == self.mentionedMsgs.firstObject.messageId) {
  1612. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
  1613. }
  1614. }
  1615. }
  1616. - (BOOL)checkLastMentionedMsgLoaded {
  1617. for (WFCUMessageModel *model in self.modelList) {
  1618. if (model.message.messageId == self.mentionedMsgs.firstObject.messageId) {
  1619. return YES;
  1620. }
  1621. }
  1622. return NO;
  1623. }
  1624. - (void)showUnreadLabel {
  1625. CGRect bount = self.view.bounds;
  1626. self.unreadButton = [[UIButton alloc] initWithFrame:CGRectMake(bount.size.width+15, 200, 0, 30)];
  1627. [self.unreadButton setTitle:[NSString stringWithFormat:@"%d 条新消息", self.unreadMessageCount] forState:UIControlStateNormal];
  1628. self.unreadButton.titleLabel.font = [UIFont systemFontOfSize:12];
  1629. [self.unreadButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
  1630. self.unreadButton.backgroundColor = [UIColor whiteColor];
  1631. self.unreadButton.layer.cornerRadius = 15;
  1632. self.unreadButton.layer.borderColor = [UIColor blackColor].CGColor;
  1633. [self.unreadButton addTarget:self action:@selector(onUnreadBtn:) forControlEvents:UIControlEventTouchUpInside];
  1634. [self.view addSubview:self.unreadButton];
  1635. [UIView animateWithDuration:0.6 animations:^{
  1636. self.unreadButton.frame = CGRectMake(bount.size.width - 85, 200, 100, 30);
  1637. }];
  1638. }
  1639. - (void)dismissUnreadLabel {
  1640. CGRect bount = self.view.bounds;
  1641. [UIView animateWithDuration:0.5 animations:^{
  1642. self.unreadButton.frame = CGRectMake(bount.size.width+15, 200, 0, 30);
  1643. } completion:^(BOOL finished) {
  1644. [self.unreadButton removeFromSuperview];
  1645. self.unreadButton = nil;
  1646. }];
  1647. }
  1648. - (void)onUnreadBtn:(id)sender {
  1649. [self dismissUnreadLabel];
  1650. if (![self checkFirstUnreadMsgLoaded]) {
  1651. [self loadMoreToFirstUnread];
  1652. } else {
  1653. [self scrollToFirstUnreadMessage];
  1654. }
  1655. }
  1656. - (BOOL)checkFirstUnreadMsgLoaded {
  1657. for (WFCUMessageModel *model in self.modelList) {
  1658. if (model.message.messageId <= self.firstUnreadMessageId) {
  1659. return YES;
  1660. }
  1661. }
  1662. return NO;
  1663. }
  1664. - (void)loadMoreToFirstUnread {
  1665. __weak typeof(self)ws = self;
  1666. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
  1667. [self loadMoreMessage:YES completion:^(BOOL more){
  1668. if (more && ![ws checkFirstUnreadMsgLoaded]) {
  1669. [ws loadMoreToFirstUnread];
  1670. } else {
  1671. [ws scrollToFirstUnreadMessage];
  1672. }
  1673. }];
  1674. }
  1675. - (void)scrollToFirstUnreadMessage {
  1676. for (int i = 0; i < self.modelList.count; i++) {
  1677. if (self.modelList[i].message.messageId == self.firstUnreadMessageId) {
  1678. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
  1679. }
  1680. }
  1681. }
  1682. - (void)appendMessages:(NSArray<WFCCMessage *> *)messages newMessage:(BOOL)newMessage highlightId:(long)highlightId forceButtom:(BOOL)forceButtom {
  1683. if (messages.count == 0) {
  1684. return;
  1685. }
  1686. if (newMessage && self.conversation.type == Group_Type && [WFCCIMService sharedWFCIMService].isCommercialServer) {
  1687. __block BOOL hasUnloadMsg = NO;
  1688. [messages enumerateObjectsUsingBlock:^(WFCCMessage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1689. if(obj.content.notLoaded) {
  1690. hasUnloadMsg = YES;
  1691. *stop = YES;
  1692. }
  1693. }];
  1694. if(hasUnloadMsg) {
  1695. messages = [messages subarrayWithRange:NSMakeRange(messages.count-15, 15)];
  1696. [self.modelList removeAllObjects];
  1697. self.isAtButtom = YES;
  1698. }
  1699. }
  1700. int count = 0;
  1701. NSMutableArray *modifiedAliasUsers = [[NSMutableArray alloc] init];
  1702. for (int i = 0; i < messages.count; i++) {
  1703. WFCCMessage *message = [messages objectAtIndex:i];
  1704. if (![message.conversation isEqual:self.conversation]) {
  1705. continue;
  1706. }
  1707. if ([message.content isKindOfClass:[WFCCTypingMessageContent class]] && message.direction == MessageDirection_Receive) {
  1708. WFCCTypingMessageContent *content = (WFCCTypingMessageContent *)message.content;
  1709. [self showUser:message.fromUser typing:content.type];
  1710. continue;
  1711. }
  1712. if(message.direction == MessageDirection_Receive) {
  1713. [self removeUserTyping:message.fromUser];
  1714. }
  1715. if (message.messageId == 0 && ![message.content isKindOfClass:[WFCCStreamingTextGeneratingMessageContent class]]) {
  1716. continue;
  1717. }
  1718. BOOL duplcated = NO;
  1719. for (WFCUMessageModel *model in self.modelList) {
  1720. if(message.messageId && message.messageId == model.message.messageId) {
  1721. model.message.content = message.content;
  1722. duplcated = YES;
  1723. break;
  1724. }
  1725. if (model.message.messageUid !=0 && model.message.messageUid == message.messageUid) {
  1726. model.message.content = message.content;
  1727. duplcated = YES;
  1728. break;
  1729. }
  1730. if(([message.content isKindOfClass:[WFCCStreamingTextGeneratingMessageContent class]] || [message.content isKindOfClass:[WFCCStreamingTextGeneratedMessageContent class]]) && [model.message.content isKindOfClass:[WFCCStreamingTextGeneratingMessageContent class]]) {
  1731. WFCCStreamingTextGeneratingMessageContent *existStreamingTextContent = (WFCCStreamingTextGeneratingMessageContent *)model.message.content;
  1732. if([message.content isKindOfClass:[WFCCStreamingTextGeneratingMessageContent class]]) {
  1733. WFCCStreamingTextGeneratingMessageContent *streamingTextContent = (WFCCStreamingTextGeneratingMessageContent *)message.content;
  1734. if([existStreamingTextContent.streamId isEqualToString:streamingTextContent.streamId]) {
  1735. model.message.content = message.content;
  1736. duplcated = YES;
  1737. break;
  1738. }
  1739. } else {
  1740. WFCCStreamingTextGeneratedMessageContent *streamingTextContent = (WFCCStreamingTextGeneratedMessageContent *)message.content;
  1741. if([existStreamingTextContent.streamId isEqualToString:streamingTextContent.streamId]) {
  1742. model.message.content = message.content;
  1743. duplcated = YES;
  1744. break;
  1745. }
  1746. }
  1747. }
  1748. }
  1749. if (duplcated) {
  1750. continue;
  1751. }
  1752. count++;
  1753. if (newMessage) {
  1754. BOOL showTime = YES;
  1755. if (self.modelList.count > 0 && (message.serverTime - (self.modelList[self.modelList.count - 1]).message.serverTime < 60 * 1000)) {
  1756. showTime = NO;
  1757. }
  1758. WFCUMessageModel *model = [WFCUMessageModel modelOf:message showName:message.direction == MessageDirection_Receive && self.showAlias showTime:showTime];
  1759. model.selecting = self.multiSelecting;
  1760. model.selected = [self.selectedMessageIds containsObject:@(message.messageId)];
  1761. model.deliveryDict = self.deliveryDict;
  1762. model.readDict = self.readDict;
  1763. [self.modelList addObject:model];
  1764. if (self.conversation.type == Group_Type && [message.content isKindOfClass:[WFCCModifyGroupAliasNotificationContent class]]) {
  1765. [modifiedAliasUsers addObject:message.fromUser];
  1766. }
  1767. [self.nMsgSet addObject:@(message.messageId)];
  1768. } else {
  1769. if (self.modelList.count > 0 && (self.modelList[0].message.serverTime - message.serverTime < 60 * 1000) && i != 0) {
  1770. self.modelList[0].showTimeLabel = NO;
  1771. }
  1772. WFCUMessageModel *model = [WFCUMessageModel modelOf:message showName:message.direction == MessageDirection_Receive&&self.showAlias showTime:YES];
  1773. if (self.firstUnreadMessageId && message.messageId == self.firstUnreadMessageId) {
  1774. model.lastReadMessage = YES;
  1775. }
  1776. model.selecting = self.multiSelecting;
  1777. model.selected = [self.selectedMessageIds containsObject:@(message.messageId)];
  1778. model.deliveryDict = self.deliveryDict;
  1779. model.readDict = self.readDict;
  1780. [self.modelList insertObject:model atIndex:0];
  1781. }
  1782. }
  1783. NSUInteger dupCount = 0;
  1784. if(self.modelList.count > 1) {
  1785. NSMutableArray *dupArr = [[NSMutableArray alloc] init];
  1786. for (int i = 0; i < self.modelList.count; ++i) {
  1787. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  1788. if (!model.message.messageUid) {
  1789. continue;
  1790. }
  1791. for (int j = i+1; j < self.modelList.count; ++j) {
  1792. WFCUMessageModel *m = [self.modelList objectAtIndex:j];
  1793. if(model.message.messageUid == m.message.messageUid) {
  1794. [dupArr addObject:m];
  1795. model.message = [[WFCCIMService sharedWFCIMService] getMessageByUid:model.message.messageUid];
  1796. }
  1797. }
  1798. }
  1799. dupCount = dupArr.count;
  1800. if(dupCount) {
  1801. [self.modelList removeObjectsInArray:dupArr];
  1802. count -= dupArr.count;
  1803. }
  1804. }
  1805. if (count > 0) {
  1806. [self stopShowTyping];
  1807. }
  1808. [self.collectionView reloadData];
  1809. if(dupCount == messages.count) {
  1810. return;
  1811. }
  1812. if (newMessage || self.modelList.count == messages.count) {
  1813. if(self.isAtButtom) {
  1814. forceButtom = true;
  1815. }
  1816. } else {
  1817. CGFloat offset = 0;
  1818. for (int i = 0; i < count; i++) {
  1819. CGSize size = [self collectionView:self.collectionView layout:self.collectionView.collectionViewLayout sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
  1820. offset += size.height;
  1821. }
  1822. self.collectionView.contentOffset = CGPointMake(0, offset);
  1823. [UIView animateWithDuration:0.2 animations:^{
  1824. self.collectionView.contentOffset = CGPointMake(0, offset - 20);
  1825. }];
  1826. }
  1827. if (highlightId > 0) {
  1828. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1829. int row = 0;
  1830. for (int i = 0; i < self.modelList.count; i++) {
  1831. WFCUMessageModel *model = self.modelList[i];
  1832. if (model.message.messageId == highlightId) {
  1833. row = i;
  1834. model.highlighted = YES;
  1835. break;
  1836. }
  1837. }
  1838. if ([self.collectionView.indexPathsForVisibleItems containsObject:[NSIndexPath indexPathForRow:row inSection:0]]) {
  1839. [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:0]]];
  1840. } else {
  1841. [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
  1842. }
  1843. });
  1844. } else if (forceButtom) {
  1845. [self scrollToBottom:YES];
  1846. }
  1847. if (modifiedAliasUsers.count) {
  1848. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1849. NSArray<NSIndexPath *> *visibleItems = self.collectionView.indexPathsForVisibleItems;
  1850. NSMutableArray *needUpdateItems = [[NSMutableArray alloc] init];
  1851. for (NSIndexPath *item in visibleItems) {
  1852. WFCUMessageModel *model = [self.modelList objectAtIndex:item.row];
  1853. if ([modifiedAliasUsers containsObject:model.message.fromUser]) {
  1854. [needUpdateItems addObject:item];
  1855. }
  1856. }
  1857. if (needUpdateItems.count) {
  1858. [self.collectionView reloadItemsAtIndexPaths:needUpdateItems];
  1859. }
  1860. });
  1861. }
  1862. if (newMessage && !self.isAtButtom && self.nMsgSet.count > 0) {
  1863. [self showNewMsgTip];
  1864. } else {
  1865. [self dismissNewMsgTip];
  1866. }
  1867. }
  1868. - (void)showNewMsgTip {
  1869. [self.newMsgTipButton setTitle:[NSString stringWithFormat:@"%ld", self.nMsgSet.count] forState:UIControlStateNormal];
  1870. self.newMsgTipButton.hidden = NO;
  1871. }
  1872. - (void)dismissNewMsgTip {
  1873. [self.nMsgSet removeAllObjects];
  1874. _newMsgTipButton.hidden = YES;
  1875. }
  1876. - (UIButton *)newMsgTipButton {
  1877. if (!_newMsgTipButton) {
  1878. _newMsgTipButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 36, self.chatInputBar.frame.origin.y - 40, 24, 24)];
  1879. _newMsgTipButton.layer.cornerRadius = 12;
  1880. _newMsgTipButton.titleLabel.font = [UIFont systemFontOfSize:8];
  1881. _newMsgTipButton.layer.borderColor = [UIColor blackColor].CGColor;
  1882. _newMsgTipButton.backgroundColor = [UIColor blueColor];
  1883. [_newMsgTipButton addTarget:self action:@selector(onNewMsgTipBtn:) forControlEvents:UIControlEventTouchUpInside];
  1884. [_newMsgTipButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  1885. [self.backgroundView addSubview:_newMsgTipButton];
  1886. }
  1887. return _newMsgTipButton;;
  1888. }
  1889. - (void)onNewMsgTipBtn:(id)sender {
  1890. self.isAtButtom = YES;
  1891. [self scrollToBottom:YES];
  1892. }
  1893. - (WFCUMessageModel *)modelOfMessage:(long)messageId {
  1894. if (messageId == 0) {
  1895. return nil;
  1896. }
  1897. for (WFCUMessageModel *model in self.modelList) {
  1898. if (model.message.messageId == messageId) {
  1899. return model;
  1900. }
  1901. }
  1902. return nil;
  1903. }
  1904. - (void)stopPlayer {
  1905. if (self.player && [self.player isPlaying]) {
  1906. [self.player stop];
  1907. if ([self.playTimer isValid]) {
  1908. [self.playTimer invalidate];
  1909. self.playTimer = nil;
  1910. }
  1911. }
  1912. WFCUMessageModel *model = [self modelOfMessage:self.playingMessageId];
  1913. model.voicePlaying = NO;
  1914. self.playingMessageId = 0;
  1915. [[NSNotificationCenter defaultCenter] postNotificationName:kVoiceMessagePlayStoped object:nil];
  1916. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
  1917. [self removeProximityMonitoringObserver];
  1918. [self.modelList enumerateObjectsUsingBlock:^(WFCUMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1919. if (obj.message.serverTime > model.message.serverTime && [obj.message.content isKindOfClass:[WFCCSoundMessageContent class]]) {
  1920. if (obj.message.status != Message_Status_Played && obj.message.direction == MessageDirection_Receive) {
  1921. WFCUMessageCellBase *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathWithIndex:idx]];
  1922. [self prepardToPlay:obj cell:cell];
  1923. *stop = YES;
  1924. }
  1925. }
  1926. }];
  1927. }
  1928. -(void)prepardToPlay:(WFCUMessageModel *)model cell:(WFCUMessageCellBase *)cell {
  1929. if (model.message.direction == MessageDirection_Receive && model.message.status != Message_Status_Played) {
  1930. if(model.message.conversation.type != SecretChat_Type) {
  1931. [[WFCCIMService sharedWFCIMService] setMediaMessagePlayed:model.message.messageId];
  1932. model.message.status = Message_Status_Played;
  1933. if (cell) {
  1934. [self.collectionView reloadItemsAtIndexPaths:@[[self.collectionView indexPathForCell:cell]]];
  1935. }
  1936. }
  1937. }
  1938. if (self.playingMessageId == model.message.messageId) {
  1939. [self stopPlayer];
  1940. } else {
  1941. if (self.playingMessageId) {
  1942. [self stopPlayer];
  1943. }
  1944. self.playingMessageId = model.message.messageId;
  1945. WFCCSoundMessageContent *soundContent = (WFCCSoundMessageContent *)model.message.content;
  1946. if (soundContent.localPath.length == 0 || ![WFCUUtilities isFileExist:soundContent.localPath]) {
  1947. __weak typeof(self) weakSelf = self;
  1948. BOOL isDownloading = [[WFCUMediaMessageDownloader sharedDownloader] tryDownload:model.message success:^(long long messageUid, NSString *localPath) {
  1949. model.mediaDownloading = NO;
  1950. [weakSelf startPlay:model];
  1951. } error:^(long long messageUid, int error_code) {
  1952. model.mediaDownloading = NO;
  1953. }];
  1954. if (isDownloading) {
  1955. model.mediaDownloading = YES;
  1956. }
  1957. } else {
  1958. [self startPlay:model];
  1959. }
  1960. }
  1961. }
  1962. - (BOOL)isPluginHeadPhonesOrConnectedBluetooth {
  1963. for(AVAudioSessionPortDescription *output in [AVAudioSession sharedInstance].currentRoute.outputs) {
  1964. if(output.portType == AVAudioSessionPortHeadphones || output.portType == AVAudioSessionPortBluetoothA2DP || output.portType == AVAudioSessionPortBluetoothLE || output.portType == AVAudioSessionPortBluetoothHFP) {
  1965. return YES;
  1966. }
  1967. }
  1968. return false;
  1969. }
  1970. - (void)handleRouteChange:(NSNotification*)notification {
  1971. AVAudioSessionRouteChangeReason reason = [notification.userInfo[@"AVAudioSessionRouteChangeReasonKey"] intValue];
  1972. switch (reason) {
  1973. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  1974. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  1975. {
  1976. AVAudioSession *session = [AVAudioSession sharedInstance];
  1977. UIDevice *device = [UIDevice currentDevice];
  1978. if([self isPluginHeadPhonesOrConnectedBluetooth] || device.proximityState) {
  1979. [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone
  1980. error:nil];
  1981. } else {
  1982. [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
  1983. error:nil];
  1984. }
  1985. }
  1986. break;
  1987. default:
  1988. break;
  1989. }
  1990. }
  1991. - (void)addProximityMonitoringObserver {
  1992. [[NSNotificationCenter defaultCenter] addObserver:self
  1993. selector:@selector(proximityStatueChanged:)
  1994. name:UIDeviceProximityStateDidChangeNotification
  1995. object:nil];
  1996. [UIDevice currentDevice].proximityMonitoringEnabled = YES;
  1997. }
  1998. - (void)removeProximityMonitoringObserver {
  1999. [[NSNotificationCenter defaultCenter] removeObserver:self
  2000. name:UIDeviceProximityStateDidChangeNotification
  2001. object:nil];
  2002. [UIDevice currentDevice].proximityMonitoringEnabled = NO;
  2003. }
  2004. - (void)proximityStatueChanged:(NSNotificationCenter *)notification {
  2005. }
  2006. -(void)startPlay:(WFCUMessageModel *)model {
  2007. if(model.message.conversation.type == SecretChat_Type) {
  2008. [[WFCCIMService sharedWFCIMService] setMediaMessagePlayed:model.message.messageId];
  2009. model.message.status = Message_Status_Played;
  2010. [self.collectionView reloadData];
  2011. }
  2012. if ([model.message.content isKindOfClass:[WFCCSoundMessageContent class]]) {
  2013. AVAudioSession *session = [AVAudioSession sharedInstance];
  2014. [session setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
  2015. UIDevice *device = [UIDevice currentDevice];
  2016. if([self isPluginHeadPhonesOrConnectedBluetooth] || device.proximityState) {
  2017. [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
  2018. } else {
  2019. [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
  2020. }
  2021. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:nil];
  2022. [self addProximityMonitoringObserver];
  2023. WFCCSoundMessageContent *snc = (WFCCSoundMessageContent *)model.message.content;
  2024. NSError *error = nil;
  2025. if(model.message.conversation.type == SecretChat_Type) {
  2026. NSData *data = [NSData dataWithContentsOfFile:snc.localPath];
  2027. data = [[WFCCIMService sharedWFCIMService] decodeSecretChat:model.message.conversation.target mediaData:data];
  2028. if (![@"mp3" isEqualToString:[snc.localPath pathExtension]]) {
  2029. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:model.message.conversation mediaType:0];
  2030. NSString *savedPath = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"media_%lld_tmp", model.message.messageUid]];
  2031. [data writeToFile:savedPath atomically:YES];
  2032. data = [[WFCCIMService sharedWFCIMService] getWavData:savedPath];
  2033. [[NSFileManager defaultManager] removeItemAtPath:savedPath error:nil];
  2034. }
  2035. self.player = [[AVAudioPlayer alloc] initWithData:data error:&error];
  2036. } else {
  2037. self.player = [[AVAudioPlayer alloc] initWithData:[snc getWavData] error:&error];
  2038. }
  2039. [self.player setDelegate:self];
  2040. [self.player prepareToPlay];
  2041. [self.player play];
  2042. model.voicePlaying = YES;
  2043. [[NSNotificationCenter defaultCenter] postNotificationName:kVoiceMessageStartPlaying object:@(self.playingMessageId)];
  2044. } else if([model.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  2045. WFCCVideoMessageContent *videoMsg = (WFCCVideoMessageContent *)model.message.content;
  2046. NSURL *url = [NSURL URLWithString:videoMsg.remoteUrl];
  2047. if (!url) {
  2048. [self.view makeToast:@"无法播放"];
  2049. return;
  2050. }
  2051. if (!self.videoPlayerViewController) {
  2052. self.videoPlayerViewController = [VideoPlayerKit videoPlayerWithContainingView:self.view optionalTopView:nil hideTopViewWithControls:YES];
  2053. self.videoPlayerViewController.allowPortraitFullscreen = YES;
  2054. } else {
  2055. [self.videoPlayerViewController.view removeFromSuperview];
  2056. }
  2057. [self.view addSubview:self.videoPlayerViewController.view];
  2058. [self.videoPlayerViewController playVideoWithTitle:@" " URL:url videoID:nil shareURL:nil isStreaming:NO playInFullScreen:YES];
  2059. }
  2060. }
  2061. #pragma mark - UICollectionViewDataSource
  2062. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  2063. return self.modelList.count;
  2064. }
  2065. // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
  2066. - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  2067. WFCUMessageModel *model = nil;
  2068. if(indexPath.row < self.modelList.count) {
  2069. model = self.modelList[indexPath.row];
  2070. }
  2071. NSString *objName = [NSString stringWithFormat:@"%d", [model.message.content.class getContentType]];
  2072. WFCUMessageCellBase *cell = nil;
  2073. if(![self.cellContentDict objectForKey:@([model.message.content.class getContentType])]) {
  2074. cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"%d", [WFCCUnknownMessageContent getContentType]] forIndexPath:indexPath];
  2075. } else {
  2076. cell = [collectionView dequeueReusableCellWithReuseIdentifier:objName forIndexPath:indexPath];
  2077. }
  2078. cell.delegate = self;
  2079. [[NSNotificationCenter defaultCenter] removeObserver:cell];
  2080. cell.model = model;
  2081. return cell;
  2082. }
  2083. - (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
  2084. {
  2085. if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
  2086. self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
  2087. self.headerActivityView.center = CGPointMake(self.headerView.bounds.size.width/2, self.headerView.bounds.size.height/2);
  2088. [self.headerView addSubview:self.headerActivityView];
  2089. return self.headerView;
  2090. } else {
  2091. self.footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
  2092. self.footerActivityView.center = CGPointMake(self.footerView.bounds.size.width/2, self.footerView.bounds.size.height/2);
  2093. [self.footerView addSubview:self.footerActivityView];
  2094. return self.footerView;
  2095. }
  2096. }
  2097. #pragma mark -UICollectionViewDelegate
  2098. - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
  2099. WFCUMessageModel *model = self.modelList[indexPath.row];
  2100. if (self.mentionedMsgs.count) {
  2101. for (WFCCMessage *msg in self.mentionedMsgs) {
  2102. if (msg.messageId == model.message.messageId) {
  2103. [self.mentionedMsgs removeObject:msg];
  2104. if (!self.mentionedMsgs.count) {
  2105. [self dismissMentionedLabel];
  2106. } else {
  2107. [self showMentionedLabel];
  2108. }
  2109. break;
  2110. }
  2111. }
  2112. }
  2113. if (self.unreadMessageCount) {
  2114. if (self.firstUnreadMessageId >= model.message.messageId) {
  2115. self.unreadMessageCount = 0;
  2116. self.firstUnreadMessageId = 0;
  2117. [self dismissUnreadLabel];
  2118. }
  2119. }
  2120. if (self.nMsgSet.count) {
  2121. if ([self.nMsgSet containsObject:@(model.message.messageId)]) {
  2122. [self.nMsgSet removeObject:@(model.message.messageId)];
  2123. if (self.nMsgSet.count) {
  2124. [self showNewMsgTip];
  2125. } else {
  2126. [self dismissNewMsgTip];
  2127. }
  2128. }
  2129. }
  2130. }
  2131. #pragma mark - UICollectionViewDelegateFlowLayout
  2132. - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
  2133. WFCUMessageModel *model = self.modelList[indexPath.row];
  2134. Class cellCls = self.cellContentDict[@([[model.message.content class] getContentType])];
  2135. if (!cellCls) {
  2136. cellCls = self.cellContentDict[@([[WFCCUnknownMessageContent class] getContentType])];
  2137. }
  2138. return [cellCls sizeForCell:model withViewWidth:self.collectionView.frame.size.width];
  2139. }
  2140. #pragma mark - MessageCellDelegate
  2141. - (void)didTapMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2142. if ([model.message.content isKindOfClass:[WFCCImageMessageContent class]] || [model.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  2143. if(self.conversation.type == SecretChat_Type) {
  2144. typeof(self) ws = self;
  2145. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  2146. hud.label.text = WFCString(@"Loading");
  2147. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2148. WFCCMediaMessageContent *mediaContent = (WFCCMediaMessageContent *)model.message.content;
  2149. NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:mediaContent.remoteUrl]];
  2150. data = [[WFCCIMService sharedWFCIMService] decodeSecretChat:model.message.conversation.target mediaData:data];
  2151. if([model.message.content isKindOfClass:[WFCCImageMessageContent class]]) {
  2152. UIImage *image = [UIImage imageWithData:data];
  2153. dispatch_async(dispatch_get_main_queue(), ^{
  2154. if(image) {
  2155. [[WFCCIMService sharedWFCIMService] setMediaMessagePlayed:model.message.messageId];
  2156. [hud hideAnimated:YES];
  2157. WFCUImagePreviewViewController *previewVC = [[WFCUImagePreviewViewController alloc] init];
  2158. previewVC.image = image;
  2159. [ws.navigationController presentViewController:previewVC animated:YES completion:nil];
  2160. } else {
  2161. hud.mode = MBProgressHUDModeText;
  2162. hud.label.text = WFCString(@"LoadFailure");
  2163. [hud hideAnimated:YES afterDelay:1.f];
  2164. }
  2165. });
  2166. } else {
  2167. //Todo play video
  2168. }
  2169. });
  2170. } else {
  2171. if (self.conversation.type == Chatroom_Type) {
  2172. NSMutableArray *imageMsgs = [[NSMutableArray alloc] init];
  2173. for (WFCUMessageModel *msgModle in self.modelList) {
  2174. if ([msgModle.message.content isKindOfClass:[WFCCImageMessageContent class]] || [msgModle.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  2175. [imageMsgs addObject:msgModle.message];
  2176. }
  2177. }
  2178. self.imageMsgs = imageMsgs;
  2179. } else {
  2180. self.imageMsgs = [[WFCCIMService sharedWFCIMService] getMessages:self.conversation contentTypes:@[@(MESSAGE_CONTENT_TYPE_IMAGE), @(MESSAGE_CONTENT_TYPE_VIDEO)] from:0 count:100 withUser:self.privateChatUser];
  2181. }
  2182. int i;
  2183. for (i = 0; i < self.imageMsgs.count; i++) {
  2184. if ([self.imageMsgs objectAtIndex:i].messageId == model.message.messageId) {
  2185. break;
  2186. }
  2187. }
  2188. if (i == self.imageMsgs.count) {
  2189. i = 0;
  2190. }
  2191. MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  2192. browser.displayActionButton = YES;
  2193. browser.displayNavArrows = NO;
  2194. browser.displaySelectionButtons = NO;
  2195. browser.alwaysShowControls = NO;
  2196. browser.zoomPhotosToFill = NO;
  2197. browser.enableGrid = YES;
  2198. browser.startOnGrid = NO;
  2199. browser.enableSwipeToDismiss = NO;
  2200. if([model.message.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  2201. browser.autoPlayOnAppear = YES;
  2202. } else {
  2203. browser.autoPlayOnAppear = NO;
  2204. }
  2205. [browser setCurrentPhotoIndex:i];
  2206. [self.navigationController pushViewController:browser animated:YES];
  2207. }
  2208. } else if([model.message.content isKindOfClass:[WFCCSoundMessageContent class]]) {
  2209. [self prepardToPlay:model cell:cell];
  2210. } else if([model.message.content isKindOfClass:[WFCCLocationMessageContent class]]) {
  2211. WFCCLocationMessageContent *locContent = (WFCCLocationMessageContent *)model.message.content;
  2212. WFCULocationViewController *vc = [[WFCULocationViewController alloc] initWithLocationPoint:[[WFCULocationPoint alloc] initWithCoordinate:locContent.coordinate andTitle:locContent.title]];
  2213. [self.navigationController pushViewController:vc animated:YES];
  2214. } else if ([model.message.content isKindOfClass:[WFCCFileMessageContent class]]) {
  2215. WFCCFileMessageContent *fileContent = (WFCCFileMessageContent *)model.message.content;
  2216. __weak typeof(self)ws = self;
  2217. [[WFCCIMService sharedWFCIMService] getAuthorizedMediaUrl:model.message.messageUid mediaType:Media_Type_FILE mediaPath:fileContent.remoteUrl success:^(NSString *authorizedUrl, NSString *backupUrl) {
  2218. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2219. bvc.url = authorizedUrl;
  2220. [ws.navigationController pushViewController:bvc animated:YES];
  2221. } error:^(int error_code) {
  2222. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2223. bvc.url = fileContent.remoteUrl;
  2224. [ws.navigationController pushViewController:bvc animated:YES];
  2225. }];
  2226. } else if ([model.message.content isKindOfClass:[WFCCCallStartMessageContent class]]) {
  2227. WFCCCallStartMessageContent *callStartMsg = (WFCCCallStartMessageContent *)model.message.content;
  2228. #if WFCU_SUPPORT_VOIP
  2229. [self didTouchVideoBtn:callStartMsg.isAudioOnly];
  2230. #endif
  2231. } else if([model.message.content isKindOfClass:[WFCCConferenceInviteMessageContent class]]) {
  2232. #if WFCU_SUPPORT_VOIP
  2233. __weak typeof(self)ws = self;
  2234. __block MBProgressHUD *hud = [self startProgress:@"会议加载中"];
  2235. if ([WFAVEngineKit sharedEngineKit].supportConference) {
  2236. WFCCConferenceInviteMessageContent *invite = (WFCCConferenceInviteMessageContent *)model.message.content;
  2237. [[WFCUConfigManager globalManager].appServiceProvider queryConferenceInfo:invite.callId password:invite.password success:^(WFZConferenceInfo * _Nonnull conferenceInfo) {
  2238. [ws stopProgress:hud finishText:nil];
  2239. WFZConferenceInfoViewController *vc = [[WFZConferenceInfoViewController alloc] init];
  2240. vc.conferenceId = conferenceInfo.conferenceId;
  2241. vc.password = conferenceInfo.password;
  2242. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
  2243. nav.modalPresentationStyle = UIModalPresentationFullScreen;
  2244. [self.navigationController presentViewController:nav animated:YES completion:nil];
  2245. } error:^(int errorCode, NSString * _Nonnull message) {
  2246. if (errorCode == 16) {
  2247. [ws stopProgress:hud finishText:@"会议已结束!"];
  2248. } else {
  2249. [ws stopProgress:hud finishText:@"网络错误"];
  2250. }
  2251. }];
  2252. } else {
  2253. [ws stopProgress:hud finishText:@"不支持会议"];
  2254. }
  2255. #endif
  2256. } else if([model.message.content isKindOfClass:[WFCCCardMessageContent class]]) {
  2257. WFCCCardMessageContent *card = (WFCCCardMessageContent *)model.message.content;
  2258. if (card.type == CardType_User) {
  2259. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:card.targetId refresh:NO];
  2260. if (!userInfo.deleted) {
  2261. WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
  2262. vc.userId = card.targetId;
  2263. vc.sourceType = FriendSource_Card;
  2264. vc.sourceTargetId = card.fromUser;
  2265. vc.hidesBottomBarWhenPushed = YES;
  2266. [self.navigationController pushViewController:vc animated:YES];
  2267. }
  2268. } else if(card.type == CardType_Group) {
  2269. WFCUGroupInfoViewController *vc2 = [[WFCUGroupInfoViewController alloc] init];
  2270. vc2.groupId = card.targetId;
  2271. vc2.sourceType = GroupMemberSource_Card;
  2272. vc2.sourceTargetId = model.message.fromUser;
  2273. vc2.hidesBottomBarWhenPushed = YES;
  2274. [self.navigationController pushViewController:vc2 animated:YES];
  2275. } else if(card.type == CardType_Channel) {
  2276. WFCUChannelProfileViewController *pvc = [[WFCUChannelProfileViewController alloc] init];
  2277. pvc.channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:card.targetId refresh:NO];
  2278. if (pvc.channelInfo) {
  2279. pvc.hidesBottomBarWhenPushed = YES;
  2280. [self.navigationController pushViewController:pvc animated:YES];
  2281. }
  2282. }
  2283. } else if([model.message.content isKindOfClass:[WFCCCompositeMessageContent class]]) {
  2284. WFCUCompositeMessageViewController *vc = [[WFCUCompositeMessageViewController alloc] init];
  2285. vc.message = model.message;
  2286. [self.navigationController pushViewController:vc animated:YES];
  2287. } else if([model.message.content isKindOfClass:[WFCCLinkMessageContent class]]) {
  2288. WFCCLinkMessageContent *content = (WFCCLinkMessageContent *)model.message.content;
  2289. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2290. bvc.url = content.url;
  2291. [self.navigationController pushViewController:bvc animated:YES];
  2292. } else if([model.message.content isKindOfClass:WFCCRichNotificationMessageContent.class]) {
  2293. WFCCRichNotificationMessageContent *richNotification = (WFCCRichNotificationMessageContent *)model.message.content;
  2294. if(richNotification.exUrl.length) {
  2295. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2296. bvc.url = richNotification.exUrl;
  2297. [self.navigationController pushViewController:bvc animated:YES];
  2298. }
  2299. }
  2300. }
  2301. - (MBProgressHUD *)startProgress:(NSString *)text {
  2302. MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  2303. hud.label.text = text;
  2304. [hud showAnimated:YES];
  2305. return hud;
  2306. }
  2307. - (MBProgressHUD *)stopProgress:(MBProgressHUD *)hud finishText:(NSString *)text {
  2308. [hud hideAnimated:YES];
  2309. if(text) {
  2310. hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  2311. hud.mode = MBProgressHUDModeText;
  2312. hud.label.text = text;
  2313. [hud hideAnimated:YES afterDelay:1.f];
  2314. }
  2315. return hud;
  2316. }
  2317. - (void)didDoubleTapMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2318. if ([model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  2319. WFCCTextMessageContent *txtMsgContent = (WFCCTextMessageContent *)model.message.content;
  2320. [self.chatInputBar resetInputBarStatue];
  2321. UIView *textContainer = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  2322. textContainer.backgroundColor = self.view.backgroundColor;
  2323. UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, [WFCUUtilities wf_navigationFullHeight], [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [WFCUUtilities wf_navigationFullHeight] - [WFCUUtilities wf_safeDistanceBottom])];
  2324. textView.text = txtMsgContent.text;
  2325. textView.textAlignment = NSTextAlignmentCenter;
  2326. textView.font = [UIFont systemFontOfSize:28];
  2327. textView.editable = NO;
  2328. textView.backgroundColor = self.view.backgroundColor;
  2329. [textContainer addSubview:textView];
  2330. [textView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapTextMessageDetailView:)]];
  2331. [[UIApplication sharedApplication].keyWindow addSubview:textContainer];
  2332. }
  2333. }
  2334. - (void)didTapArticleCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model withArticle:(WFCCArticle *)article {
  2335. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2336. bvc.url = article.url;
  2337. [self.navigationController pushViewController:bvc animated:YES];
  2338. }
  2339. - (void)didTapTextMessageDetailView:(id)sender {
  2340. if ([sender isKindOfClass:[UIGestureRecognizer class]]) {
  2341. UIGestureRecognizer *gesture = (UIGestureRecognizer *)sender;
  2342. [gesture.view.superview removeFromSuperview];
  2343. }
  2344. NSLog(@"close windows");
  2345. }
  2346. - (void)didTapMessagePortrait:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2347. if(self.conversation.type == Group_Type) {
  2348. if (self.targetGroup.privateChat) {
  2349. if (![self.targetGroup.owner isEqualToString:model.message.fromUser] && ![self.targetGroup.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  2350. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:self.conversation.target memberId:[WFCCNetworkService sharedInstance].userId];
  2351. if (gm.type != Member_Type_Manager) {
  2352. WFCCGroupMember *gm = [[WFCCIMService sharedWFCIMService] getGroupMember:self.conversation.target memberId:model.message.fromUser];
  2353. if (gm.type != Member_Type_Manager) {
  2354. [self.view makeToast:WFCString(@"NotAllowTemporarySession") duration:1 position:CSToastPositionCenter];
  2355. return;
  2356. }
  2357. }
  2358. }
  2359. }
  2360. } else if(self.conversation.type == Channel_Type && model.message.direction == MessageDirection_Receive) {
  2361. WFCUConversationSettingViewController *gvc = [[WFCUConversationSettingViewController alloc] init];
  2362. gvc.conversation = self.conversation;
  2363. [self.navigationController pushViewController:gvc animated:YES];
  2364. return;
  2365. }
  2366. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:model.message.fromUser refresh:NO];
  2367. if (!userInfo.deleted) {
  2368. WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
  2369. vc.userId = model.message.fromUser;
  2370. vc.fromConversation = self.conversation;
  2371. if(self.conversation.type == Group_Type) {
  2372. vc.sourceType = FriendSource_Group;
  2373. vc.sourceTargetId = self.conversation.target;
  2374. }
  2375. vc.hidesBottomBarWhenPushed = YES;
  2376. [self.navigationController pushViewController:vc animated:YES];
  2377. }
  2378. }
  2379. - (void)didLongPressMessageCell:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2380. if ([cell isKindOfClass:[WFCUMessageCellBase class]]) {
  2381. // if (!self.isFirstResponder) {
  2382. // [self becomeFirstResponder];
  2383. // }
  2384. [self displayMenu:(WFCUMessageCellBase *)cell];
  2385. }
  2386. }
  2387. - (void)didLongPressMessagePortrait:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2388. if (self.conversation.type == Group_Type) {
  2389. if (model.message.direction == MessageDirection_Receive) {
  2390. WFCCUserInfo *sender = [[WFCCIMService sharedWFCIMService] getUserInfo:model.message.fromUser inGroup:self.conversation.target refresh:NO];
  2391. NSString *userName = sender.groupAlias.length ? sender.groupAlias : sender.displayName;
  2392. [self.chatInputBar appendMention:model.message.fromUser name:userName];
  2393. }
  2394. } else if(self.conversation.type == Channel_Type) {
  2395. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:NO];
  2396. if ([channelInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  2397. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2398. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
  2399. UIAlertAction *okAction = [UIAlertAction actionWithTitle:WFCString(@"ChatWithSubscriber") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  2400. if (model.message.direction == MessageDirection_Receive) {
  2401. WFCCChannelInfo *channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.conversation.target refresh:NO];
  2402. if ([channelInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  2403. WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
  2404. mvc.conversation = [WFCCConversation conversationWithType:self.conversation.type target:self.conversation.target line:self.conversation.line];
  2405. mvc.privateChatUser = model.message.fromUser;
  2406. [self.navigationController pushViewController:mvc animated:YES];
  2407. }
  2408. }
  2409. }];
  2410. [alertController addAction:cancelAction];
  2411. [alertController addAction:okAction];
  2412. [self presentViewController:alertController animated:YES completion:nil];
  2413. }
  2414. }
  2415. }
  2416. - (void)didTapResendBtn:(WFCUMessageModel *)model {
  2417. NSInteger index = [self.modelList indexOfObject:model];
  2418. if (index >= 0) {
  2419. NSIndexPath *path = [NSIndexPath indexPathForRow:index inSection:0];
  2420. [self.modelList removeObjectAtIndex:index];
  2421. [self.collectionView deleteItemsAtIndexPaths:@[path]];
  2422. [[WFCCIMService sharedWFCIMService] deleteMessage:model.message.messageId];
  2423. [self sendMessage:model.message.content];
  2424. }
  2425. }
  2426. - (void)didSelectUrl:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model withUrl:(NSString *)urlString {
  2427. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2428. bvc.url = urlString;
  2429. [self.navigationController pushViewController:bvc animated:YES];
  2430. }
  2431. - (void)didSelectPhoneNumber:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model withPhoneNumber:(NSString *)phoneNumber {
  2432. if(self.chatInputBar.inputBarStatus == ChatInputBarKeyboardStatus || self.chatInputBar.inputBarStatus == ChatInputBarEmojiStatus || self.chatInputBar.inputBarStatus == ChatInputBarPluginStatus) {
  2433. self.chatInputBar.inputBarStatus = ChatInputBarDefaultStatus;
  2434. }
  2435. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:WFCString(@"PhoneNumberHint"), phoneNumber] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2436. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
  2437. UIAlertAction *callAction = [UIAlertAction actionWithTitle:WFCString(@"Call") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  2438. NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"telprompt:%@", phoneNumber]];
  2439. if (@available(iOS 10, *)) {
  2440. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  2441. } else {
  2442. [[UIApplication sharedApplication] openURL:url];
  2443. }
  2444. }];
  2445. UIAlertAction *copyAction = [UIAlertAction actionWithTitle:WFCString(@"CopyNumber") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  2446. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2447. pasteboard.string = phoneNumber;
  2448. }];
  2449. [alertController addAction:cancelAction];
  2450. [alertController addAction:callAction];
  2451. [alertController addAction:copyAction];
  2452. // [alertController addAction:addContactAction];
  2453. [self presentViewController:alertController animated:YES completion:nil];
  2454. }
  2455. - (void)reeditRecalledMessage:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2456. WFCCRecallMessageContent *recall = (WFCCRecallMessageContent *)model.message.content;
  2457. [self.chatInputBar appendText:recall.originalSearchableContent];
  2458. }
  2459. - (void)didTapReceiptView:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2460. WFCUReceiptViewController *receipt = [[WFCUReceiptViewController alloc] init];
  2461. receipt.message = model.message;
  2462. [self.navigationController pushViewController:receipt animated:YES];
  2463. }
  2464. - (void)showQuote:(WFCCQuoteInfo *)quoteInfo ofMessage:(WFCCMessage *)msg {
  2465. if ([msg.content isKindOfClass:[WFCCTextMessageContent class]]) {
  2466. WFCCTextMessageContent *txtContent = (WFCCTextMessageContent *)msg.content;
  2467. [self.chatInputBar resetInputBarStatue];
  2468. UIView *textContainer = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  2469. textContainer.backgroundColor = self.view.backgroundColor;
  2470. UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, [WFCUUtilities wf_navigationFullHeight], [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [WFCUUtilities wf_navigationFullHeight] - [WFCUUtilities wf_safeDistanceBottom])];
  2471. textView.text = txtContent.text;
  2472. textView.textAlignment = NSTextAlignmentCenter;
  2473. textView.font = [UIFont systemFontOfSize:28];
  2474. textView.editable = NO;
  2475. textView.backgroundColor = self.view.backgroundColor;
  2476. [textContainer addSubview:textView];
  2477. [textView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapTextMessageDetailView:)]];
  2478. [[UIApplication sharedApplication].keyWindow addSubview:textContainer];
  2479. } else if ([msg.content isKindOfClass:[WFCCImageMessageContent class]]) {
  2480. self.imageMsgs = @[msg];
  2481. MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
  2482. browser.displayActionButton = YES;
  2483. browser.displayNavArrows = NO;
  2484. browser.displaySelectionButtons = NO;
  2485. browser.alwaysShowControls = NO;
  2486. browser.zoomPhotosToFill = YES;
  2487. browser.enableGrid = NO;
  2488. browser.startOnGrid = NO;
  2489. browser.enableSwipeToDismiss = NO;
  2490. browser.autoPlayOnAppear = NO;
  2491. [browser setCurrentPhotoIndex:0];
  2492. [self.navigationController pushViewController:browser animated:YES];
  2493. } else if ([msg.content isKindOfClass:[WFCCLocationMessageContent class]]) {
  2494. WFCCLocationMessageContent *locContent = (WFCCLocationMessageContent *)msg.content;
  2495. WFCULocationViewController *vc = [[WFCULocationViewController alloc] initWithLocationPoint:[[WFCULocationPoint alloc] initWithCoordinate:locContent.coordinate andTitle:locContent.title]];
  2496. [self.navigationController pushViewController:vc animated:YES];
  2497. } else if ([msg.content isKindOfClass:[WFCCFileMessageContent class]]) {
  2498. WFCCFileMessageContent *fileContent = (WFCCFileMessageContent *)msg.content;
  2499. __weak typeof(self)ws = self;
  2500. [[WFCCIMService sharedWFCIMService] getAuthorizedMediaUrl:msg.messageUid mediaType:Media_Type_FILE mediaPath:fileContent.remoteUrl success:^(NSString *authorizedUrl, NSString *backupUrl) {
  2501. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2502. bvc.url = authorizedUrl;
  2503. [ws.navigationController pushViewController:bvc animated:YES];
  2504. } error:^(int error_code) {
  2505. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2506. bvc.url = fileContent.remoteUrl;
  2507. [ws.navigationController pushViewController:bvc animated:YES];
  2508. }];
  2509. } else if ([msg.content isKindOfClass:[WFCCCardMessageContent class]]) {
  2510. WFCCCardMessageContent *card = (WFCCCardMessageContent *)msg.content;
  2511. if (card.type == CardType_User) {
  2512. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:card.targetId refresh:NO];
  2513. if (!userInfo.deleted) {
  2514. WFCUProfileTableViewController *vc = [[WFCUProfileTableViewController alloc] init];
  2515. vc.userId = card.targetId;
  2516. vc.sourceType = FriendSource_Card;
  2517. vc.sourceTargetId = card.fromUser;
  2518. vc.hidesBottomBarWhenPushed = YES;
  2519. [self.navigationController pushViewController:vc animated:YES];
  2520. }
  2521. } else if(card.type == CardType_Group) {
  2522. WFCUGroupInfoViewController *vc2 = [[WFCUGroupInfoViewController alloc] init];
  2523. vc2.groupId = card.targetId;
  2524. vc2.hidesBottomBarWhenPushed = YES;
  2525. [self.navigationController pushViewController:vc2 animated:YES];
  2526. } else if(card.type == CardType_Channel) {
  2527. WFCUChannelProfileViewController *pvc = [[WFCUChannelProfileViewController alloc] init];
  2528. pvc.channelInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:card.targetId refresh:NO];
  2529. if (pvc.channelInfo) {
  2530. pvc.hidesBottomBarWhenPushed = YES;
  2531. [self.navigationController pushViewController:pvc animated:YES];
  2532. }
  2533. }
  2534. } else {
  2535. //有些消息内容不能在当前页面显示,跳转到新的页面显示
  2536. // if ([msg.content isKindOfClass:[WFCCSoundMessageContent class]])
  2537. // if ([msg.content isKindOfClass:[WFCCStickerMessageContent class]])
  2538. // if ([msg.content isKindOfClass:[WFCCVideoMessageContent class]])
  2539. WFCUQuoteViewController *vc = [[WFCUQuoteViewController alloc] init];
  2540. vc.messageUid = msg.messageUid;
  2541. [self.navigationController pushViewController:vc animated:YES];
  2542. }
  2543. }
  2544. - (void)didTapQuoteLabel:(WFCUMessageCellBase *)cell withModel:(WFCUMessageModel *)model {
  2545. if ([model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  2546. WFCCTextMessageContent *txtContent = (WFCCTextMessageContent *)model.message.content;
  2547. if (txtContent.quoteInfo) {
  2548. __block WFCCMessage *msg = [[WFCCIMService sharedWFCIMService] getMessageByUid:txtContent.quoteInfo.messageUid];
  2549. if ([msg.content isKindOfClass:[WFCCRecallMessageContent class]]) {
  2550. [self.view makeToast:@"消息不存在了!"];
  2551. NSLog(@"msg not exist");
  2552. return;
  2553. }
  2554. if(msg) {
  2555. [self showQuote:txtContent.quoteInfo ofMessage:msg];
  2556. } else {
  2557. [self.modelList enumerateObjectsUsingBlock:^(WFCUMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2558. if(obj.message.messageUid == txtContent.quoteInfo.messageUid) {
  2559. msg = obj.message;
  2560. *stop = YES;
  2561. }
  2562. }];
  2563. if(msg) {
  2564. [self showQuote:txtContent.quoteInfo ofMessage:msg];
  2565. } else {
  2566. __weak typeof(self)ws = self;
  2567. [[WFCCIMService sharedWFCIMService] getRemoteMessage:txtContent.quoteInfo.messageUid success:^(WFCCMessage *message) {
  2568. if (!message.content || [message.content isKindOfClass:[WFCCRecallMessageContent class]]) {
  2569. [ws.view makeToast:@"消息不存在了!"];
  2570. NSLog(@"msg not exist");
  2571. return;
  2572. } else {
  2573. [ws showQuote:txtContent.quoteInfo ofMessage:message];
  2574. }
  2575. } error:^(int error_code) {
  2576. if(error_code == 253) {
  2577. [ws.view makeToast:@"消息不存在了!"];
  2578. } else {
  2579. [ws.view makeToast:@"网络错误"];
  2580. }
  2581. }];
  2582. }
  2583. }
  2584. }
  2585. }
  2586. }
  2587. #pragma mark - AVAudioPlayerDelegate
  2588. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
  2589. NSLog(@"player finished");
  2590. [self stopPlayer];
  2591. }
  2592. - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
  2593. NSLog(@"player decode error");
  2594. [[[UIAlertView alloc] initWithTitle:WFCString(@"Warning") message:WFCString(@"NetworkError") delegate:nil cancelButtonTitle:WFCString(@"Ok") otherButtonTitles:nil, nil] show];
  2595. [self stopPlayer];
  2596. }
  2597. #pragma mark - UIScrollViewDelegate
  2598. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  2599. }
  2600. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  2601. [self.chatInputBar resetInputBarStatue];
  2602. }
  2603. - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
  2604. if (self.hasNewMessage && ceil(targetContentOffset->y)+1 >= ceil(scrollView.contentSize.height - scrollView.bounds.size.height)) {
  2605. [self loadMoreMessage:NO completion:nil];
  2606. }
  2607. if (targetContentOffset->y <= 0 && self.hasMoreOld) {
  2608. [self loadMoreMessage:YES completion:nil];
  2609. }
  2610. CGSize size = self.collectionView.contentSize;
  2611. self.isAtButtom = (scrollView.bounds.size.height + targetContentOffset->y - size.height) > -5;
  2612. NSLog(@"is at buttom %d", self.isAtButtom);
  2613. }
  2614. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  2615. }
  2616. #pragma mark - ChatInputBarDelegate
  2617. - (void)imageDidCapture:(UIImage *)capturedImage fullImage:(BOOL)fullImage{
  2618. if (!capturedImage) {
  2619. return;
  2620. }
  2621. UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  2622. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.conversation mediaType:Media_Type_IMAGE];
  2623. NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"img%lld.jpg", recordTime++]];
  2624. WFCCImageMessageContent *imgContent = [WFCCImageMessageContent contentFrom:capturedImage cachePath:path fullImage:fullImage];
  2625. [self sendMessage:imgContent];
  2626. }
  2627. -(void)gifDidCapture:(NSData *)gifData {
  2628. //save gif
  2629. UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  2630. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.conversation mediaType:Media_Type_STICKER];
  2631. NSString *filePath = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"gif%lld.jpg", recordTime]];
  2632. [gifData writeToFile:filePath atomically:YES];
  2633. WFCCStickerMessageContent *stickerContent = [WFCCStickerMessageContent contentFrom:filePath];
  2634. [self sendMessage:stickerContent];
  2635. }
  2636. - (void)videoDidCapture:(NSString *)videoPath thumbnail:(UIImage *)image duration:(long)duration {
  2637. WFCCVideoMessageContent *videoContent = [WFCCVideoMessageContent contentPath:videoPath thumbnail:image];
  2638. videoContent.duration = duration;
  2639. [self sendMessage:videoContent];
  2640. }
  2641. - (void)imageDataDidSelect:(NSArray<UIImage *> *)selectedImages isFullImage:(BOOL)fullImage {
  2642. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  2643. UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  2644. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.conversation mediaType:Media_Type_IMAGE];
  2645. for (UIImage *image in selectedImages) {
  2646. NSString *path = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"img%lld.jpg", recordTime++]];
  2647. WFCCImageMessageContent *imgContent = [WFCCImageMessageContent contentFrom:image cachePath:path];
  2648. dispatch_sync(dispatch_get_main_queue(), ^{
  2649. [self sendMessage:imgContent];
  2650. });
  2651. [NSThread sleepForTimeInterval:0.2];
  2652. }
  2653. });
  2654. }
  2655. - (void)didTapChannelMenu:(WFCCChannelMenu *)channelMenu {
  2656. if ([channelMenu.type isEqualToString:@"view"] && channelMenu.url.length) {
  2657. WFCUBrowserViewController *bvc = [[WFCUBrowserViewController alloc] init];
  2658. bvc.url = channelMenu.url;
  2659. [self.navigationController pushViewController:bvc animated:YES];
  2660. } else if([channelMenu.type isEqualToString:@"miniprogram"] && channelMenu.appId.length) {
  2661. //打开小程序。。。
  2662. }
  2663. }
  2664. - (void)didTouchSend:(NSString *)stringContent withMentionInfos:(NSMutableArray<WFCUMetionInfo *> *)mentionInfos withQuoteInfo:(WFCCQuoteInfo *)quoteInfo {
  2665. if (stringContent.length == 0) {
  2666. return;
  2667. }
  2668. WFCCTextMessageContent *txtContent = [[WFCCTextMessageContent alloc] init];
  2669. txtContent.text = stringContent;
  2670. NSMutableArray *mentionTargets = [[NSMutableArray alloc] init];
  2671. for (WFCUMetionInfo *mentionInfo in mentionInfos) {
  2672. if (mentionInfo.mentionType == 2) {
  2673. txtContent.mentionedType = 2;
  2674. mentionTargets = nil;
  2675. break;
  2676. } else if(mentionInfo.mentionType == 1) {
  2677. txtContent.mentionedType = 1;
  2678. [mentionTargets addObject:mentionInfo.target];
  2679. }
  2680. }
  2681. if (txtContent.mentionedType == 1) {
  2682. txtContent.mentionedTargets = [mentionTargets copy];
  2683. }
  2684. txtContent.quoteInfo = quoteInfo;
  2685. if(self.orignalDraft) {
  2686. self.orignalDraft = nil;
  2687. [[WFCCIMService sharedWFCIMService] setConversation:self.conversation draft:nil];
  2688. }
  2689. [self sendMessage:txtContent];
  2690. }
  2691. - (void)needSaveDraft {
  2692. self.orignalDraft = self.chatInputBar.draft;
  2693. [[WFCCIMService sharedWFCIMService] setConversation:self.conversation draft:self.orignalDraft];
  2694. }
  2695. - (void)recordDidEnd:(NSString *)dataUri duration:(long)duration error:(NSError *)error {
  2696. NSString *cacheDir = [[WFCUConfigManager globalManager] cachePathOf:self.conversation mediaType:Media_Type_VOICE];
  2697. UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
  2698. NSString *amrPath = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"img%lld.amr", recordTime]];
  2699. [self sendMessage:[WFCCSoundMessageContent soundMessageContentForWav:dataUri destinationAmrPath:amrPath duration:duration]];
  2700. }
  2701. - (BOOL)isEqualRect:(CGRect)first second:(CGRect)second {
  2702. return first.origin.x == second.origin.x
  2703. && first.origin.y == second.origin.y
  2704. && first.size.width == second.size.width
  2705. && first.size.height == second.size.height;
  2706. }
  2707. - (void)willChangeFrame:(CGRect)newFrame withDuration:(CGFloat)duration keyboardShowing:(BOOL)keyboardShowing {
  2708. if (!self.isShowingKeyboard) {
  2709. CGRect frame = self.collectionView.frame;
  2710. CGFloat diff = MIN(frame.size.height, self.collectionView.contentSize.height) - newFrame.origin.y;
  2711. if(diff > 0) {
  2712. frame.origin.y = -diff;
  2713. } else {
  2714. frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  2715. }
  2716. if([self isEqualRect:frame second:self.collectionView.frame]) {
  2717. return;
  2718. }
  2719. self.isShowingKeyboard = YES;
  2720. [UIView animateWithDuration:duration animations:^{
  2721. self.collectionView.frame = frame;
  2722. } completion:^(BOOL finished) {
  2723. self.collectionView.frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  2724. if (keyboardShowing) {
  2725. [self scrollToBottom:NO];
  2726. }
  2727. self.isShowingKeyboard = NO;
  2728. }];
  2729. } else {
  2730. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  2731. if (self.collectionView.frame.size.height != newFrame.origin.y) {
  2732. self.collectionView.frame = CGRectMake(0, 0, self.backgroundView.bounds.size.width, newFrame.origin.y);
  2733. [self scrollToBottom:YES];
  2734. }
  2735. });
  2736. }
  2737. }
  2738. - (UINavigationController *)requireNavi {
  2739. return self.navigationController;
  2740. }
  2741. - (void)locationDidSelect:(CLLocationCoordinate2D)location locationName:(NSString *)locationName mapScreenShot:(UIImage *)mapScreenShot {
  2742. WFCCLocationMessageContent *content = [WFCCLocationMessageContent contentWith:location title:locationName thumbnail:mapScreenShot];
  2743. [self sendMessage:content];
  2744. }
  2745. - (void)didSelectFiles:(NSArray *)files {
  2746. if(![[WFCCIMService sharedWFCIMService] isSupportBigFilesUpload]) {
  2747. for (NSString *file in files) {
  2748. WFCCFileMessageContent *content = [WFCCFileMessageContent fileMessageContentFromPath:file];
  2749. if(content.size >= 100 * 1024 * 1024) {
  2750. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"文件内容超大,无法发送!" preferredStyle:UIAlertControllerStyleAlert];
  2751. UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"知道了") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2752. }];
  2753. [alertController addAction:actionCancel];
  2754. [self presentViewController:alertController animated:YES completion:nil];
  2755. return;
  2756. }
  2757. }
  2758. }
  2759. for (NSString *file in files) {
  2760. BOOL isDir = NO;
  2761. [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir];
  2762. if(isDir) {
  2763. NSLog(@"file is directiory");
  2764. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:[NSString stringWithFormat:@"无法发送文件夹: %@", file.lastPathComponent] preferredStyle:UIAlertControllerStyleAlert];
  2765. UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2766. }];
  2767. [alertController addAction:actionCancel];
  2768. [self presentViewController:alertController animated:YES completion:nil];
  2769. continue;;
  2770. }
  2771. WFCCFileMessageContent *content = [WFCCFileMessageContent fileMessageContentFromPath:file];
  2772. [self sendMessage:content];
  2773. [NSThread sleepForTimeInterval:0.05];
  2774. }
  2775. }
  2776. - (void)saveStickerRemoteUrl:(WFCCStickerMessageContent *)stickerContent {
  2777. if (stickerContent.localPath.length && [WFCUUtilities isFileExist:stickerContent.localPath] && stickerContent.remoteUrl.length) {
  2778. if(self.conversation.type == SecretChat_Type) {
  2779. [[NSUserDefaults standardUserDefaults] setObject:stickerContent.remoteUrl forKey:[NSString stringWithFormat:@"sticker_remote_for_sh_%@_%ld", self.conversation.target, stickerContent.localPath.hash]];
  2780. } else {
  2781. [[NSUserDefaults standardUserDefaults] setObject:stickerContent.remoteUrl forKey:[NSString stringWithFormat:@"sticker_remote_for_%ld", stickerContent.localPath.hash]];
  2782. }
  2783. [[NSUserDefaults standardUserDefaults] synchronize];
  2784. }
  2785. }
  2786. - (void)didSelectSticker:(NSString *)stickerPath {
  2787. WFCCStickerMessageContent * content = [WFCCStickerMessageContent contentFrom:stickerPath];
  2788. NSString *remoteUrl;
  2789. if(self.conversation.type == SecretChat_Type) {
  2790. remoteUrl = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"sticker_remote_for_sh_%@_%ld", self.conversation.target, stickerPath.hash]];
  2791. } else {
  2792. remoteUrl = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"sticker_remote_for_%ld", stickerPath.hash]];
  2793. }
  2794. content.remoteUrl = remoteUrl;
  2795. [self sendMessage:content];
  2796. }
  2797. #if WFCU_SUPPORT_VOIP
  2798. - (void)didTouchVideoBtn:(BOOL)isAudioOnly {
  2799. if(self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type) {
  2800. [self startCall:@[self.conversation.target] isMulti:NO conversation:self.conversation audioOnly:isAudioOnly];
  2801. } else {
  2802. // WFCUContactListViewController *pvc = [[WFCUContactListViewController alloc] init];
  2803. // pvc.selectContact = YES;
  2804. // pvc.multiSelect = [WFAVEngineKit sharedEngineKit].supportMultiCall;
  2805. // if (pvc.multiSelect) {
  2806. // pvc.maxSelectCount = isAudioOnly ? [WFAVEngineKit sharedEngineKit].maxAudioCallCount : [WFAVEngineKit sharedEngineKit].maxVideoCallCount;
  2807. // pvc.maxSelectCount -= 1;
  2808. // }
  2809. WFCUSeletedUserViewController *vc = [[WFCUSeletedUserViewController alloc] init];
  2810. NSMutableArray *disabledUser = [[NSMutableArray alloc] init];
  2811. [disabledUser addObject:[WFCCNetworkService sharedInstance].userId];
  2812. vc.disableUserIds = disabledUser;
  2813. vc.maxSelectCount = isAudioOnly ? [WFAVEngineKit sharedEngineKit].maxAudioCallCount : [WFAVEngineKit sharedEngineKit].maxVideoCallCount;
  2814. vc.groupId = self.targetGroup.target;
  2815. // vc.maxSelectCount -= 1;
  2816. NSMutableArray *candidateUser = [[NSMutableArray alloc] init];
  2817. NSArray<WFCCGroupMember *> *members = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  2818. for (WFCCGroupMember *member in members) {
  2819. [candidateUser addObject:member.memberId];
  2820. }
  2821. vc.candidateUsers = candidateUser;
  2822. vc.type = Vertical;
  2823. __weak typeof(self)ws = self;
  2824. vc.selectResult = ^(NSArray<NSString *> * _Nonnull contacts) {
  2825. [self startCall:contacts isMulti:ws.conversation.type == Group_Type conversation:self.conversation audioOnly:isAudioOnly];
  2826. };
  2827. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vc];
  2828. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  2829. [self.navigationController presentViewController:navi animated:YES completion:nil];
  2830. }
  2831. }
  2832. - (void)startCall:(NSArray<NSString *> *)targetIds isMulti:(BOOL)isMulti conversation:(WFCCConversation *)conversation audioOnly:(BOOL)isAudioOnly {
  2833. [WFCUUtilities checkRecordOrCameraPermission:YES complete:^(BOOL granted) {
  2834. if(granted) {
  2835. if(isAudioOnly) {
  2836. UIViewController *videoVC;
  2837. if(isMulti) {
  2838. videoVC = [[WFCUMultiVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
  2839. } else {
  2840. videoVC = [[WFCUVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
  2841. }
  2842. [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
  2843. } else {
  2844. [WFCUUtilities checkRecordOrCameraPermission:NO complete:^(BOOL granted) {
  2845. if(granted) {
  2846. UIViewController *videoVC;
  2847. if(isMulti) {
  2848. videoVC = [[WFCUMultiVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
  2849. } else {
  2850. videoVC = [[WFCUVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
  2851. }
  2852. [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
  2853. }
  2854. } viewController:self];
  2855. }
  2856. }
  2857. } viewController:self];
  2858. }
  2859. #endif
  2860. - (void)onTyping:(WFCCTypingType)type {
  2861. if (self.conversation.type == Single_Type || self.conversation.type == SecretChat_Type || self.conversation.type == Group_Type) {
  2862. [self sendMessage:[WFCCTypingMessageContent contentType:type]];
  2863. }
  2864. }
  2865. #pragma mark - UIGestureRecognizerDelegate
  2866. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
  2867. return self.navigationController.childViewControllers.count > 1;
  2868. }
  2869. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
  2870. return self.navigationController.viewControllers.count > 1;
  2871. }
  2872. #pragma mark - menu
  2873. - (void)displayMenu:(WFCUMessageCellBase *)baseCell {
  2874. UIMenuController *menu = [UIMenuController sharedMenuController];
  2875. UIMenuItem *deleteItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Delete") action:@selector(performDelete:)];
  2876. UIMenuItem *cancelItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Cancel") action:@selector(performCancel:)];
  2877. UIMenuItem *copyItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Copy") action:@selector(performCopy:)];
  2878. UIMenuItem *forwardItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Forward") action:@selector(performForward:)];
  2879. UIMenuItem *recallItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Recall") action:@selector(performRecall:)];
  2880. UIMenuItem *complainItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Complain") action:@selector(performComplain:)];
  2881. UIMenuItem *multiSelectItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"MultiSelect") action:@selector(performMultiSelect:)];
  2882. UIMenuItem *quoteItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Quote") action:@selector(performQuote:)];
  2883. UIMenuItem *favoriteItem = [[UIMenuItem alloc]initWithTitle:WFCString(@"Favorite") action:@selector(performFavorite:)];
  2884. CGRect menuPos;
  2885. if ([baseCell isKindOfClass:[WFCUMessageCell class]]) {
  2886. WFCUMessageCell *msgCell = (WFCUMessageCell *)baseCell;
  2887. menuPos = msgCell.bubbleView.frame;
  2888. } else {
  2889. menuPos = baseCell.frame;
  2890. }
  2891. [menu setTargetRect:menuPos inView:baseCell];
  2892. WFCCMessage *msg = baseCell.model.message;
  2893. NSMutableArray *items = [[NSMutableArray alloc] init];
  2894. [items addObject:deleteItem];
  2895. if ([msg.content isKindOfClass:[WFCCTextMessageContent class]]) {
  2896. [items addObject:copyItem];
  2897. }
  2898. if (baseCell.model.message.direction == MessageDirection_Send && baseCell.model.message.status == Message_Status_Sending && [baseCell.model.message.content isKindOfClass:[WFCCMediaMessageContent class]]) {
  2899. [items addObject:cancelItem];
  2900. }
  2901. if (baseCell.model.message.direction == MessageDirection_Receive) {
  2902. [items addObject:complainItem];
  2903. }
  2904. if(self.conversation.type != SecretChat_Type) {
  2905. if ([msg.content isKindOfClass:[WFCCImageMessageContent class]] ||
  2906. [msg.content isKindOfClass:[WFCCTextMessageContent class]] ||
  2907. [msg.content isKindOfClass:[WFCCLinkMessageContent class]] ||
  2908. [msg.content isKindOfClass:[WFCCArticlesMessageContent class]] ||
  2909. [msg.content isKindOfClass:[WFCCLocationMessageContent class]] ||
  2910. [msg.content isKindOfClass:[WFCCFileMessageContent class]] ||
  2911. [msg.content isKindOfClass:[WFCCVideoMessageContent class]] ||
  2912. [msg.content isKindOfClass:[WFCCCardMessageContent class]] ||
  2913. [msg.content isKindOfClass:[WFCCConferenceInviteMessageContent class]] ||
  2914. [msg.content isKindOfClass:[WFCCCompositeMessageContent class]] ||
  2915. // [msg.content isKindOfClass:[WFCCSoundMessageContent class]] || //语音消息禁止转发,出于安全原因考虑,微信就禁止转发。如果您能确保安全,可以把这行注释打开
  2916. [msg.content isKindOfClass:[WFCCStickerMessageContent class]]) {
  2917. [items addObject:forwardItem];
  2918. }
  2919. }
  2920. BOOL canRecall = NO;
  2921. if ([baseCell isKindOfClass:[WFCUMessageCell class]]) {
  2922. if(msg.direction == MessageDirection_Send) {
  2923. NSDate *cur = [NSDate date];
  2924. if ([cur timeIntervalSince1970]*1000 - msg.serverTime < 60 * 1000) {
  2925. canRecall = YES;
  2926. }
  2927. } else if (self.conversation.type == Group_Type) {
  2928. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.conversation.target refresh:NO];
  2929. if([groupInfo.owner isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  2930. canRecall = YES;
  2931. } else {
  2932. __block BOOL isMyselfManager = false;
  2933. __block BOOL isTargetManager = false;
  2934. NSArray *memberList = [[WFCCIMService sharedWFCIMService] getGroupMembers:self.conversation.target forceUpdate:NO];
  2935. [memberList enumerateObjectsUsingBlock:^(WFCCGroupMember * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2936. if ([obj.memberId isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  2937. if (obj.type == Member_Type_Manager || obj.type == Member_Type_Owner) {
  2938. isMyselfManager = YES;
  2939. }
  2940. }
  2941. if([obj.memberId isEqualToString:msg.fromUser]) {
  2942. if ((obj.type == Member_Type_Manager || obj.type == Member_Type_Owner)) {
  2943. isTargetManager = YES;
  2944. }
  2945. }
  2946. }];
  2947. if(isMyselfManager && !isTargetManager) {
  2948. canRecall = YES;
  2949. }
  2950. }
  2951. }
  2952. }
  2953. if(self.conversation.type == SecretChat_Type && msg.direction == MessageDirection_Send) {
  2954. canRecall = YES;
  2955. }
  2956. if (canRecall) {
  2957. [items addObject:recallItem];
  2958. }
  2959. if(self.conversation.type != SecretChat_Type) {
  2960. if ([baseCell isKindOfClass:[WFCUMessageCell class]] || [baseCell isKindOfClass:[WFCUArticlesCell class]]) {
  2961. [items addObject:multiSelectItem];
  2962. }
  2963. }
  2964. if (msg.messageUid > 0) {
  2965. if ([msg.content.class getContentFlags] & 0x2) {
  2966. [items addObject:quoteItem];
  2967. }
  2968. }
  2969. if(self.conversation.type != SecretChat_Type) {
  2970. if ([msg.content isKindOfClass:[WFCCImageMessageContent class]] ||
  2971. [msg.content isKindOfClass:[WFCCTextMessageContent class]] ||
  2972. [msg.content isKindOfClass:[WFCCLocationMessageContent class]] ||
  2973. [msg.content isKindOfClass:[WFCCFileMessageContent class]] ||
  2974. [msg.content isKindOfClass:[WFCCVideoMessageContent class]] ||
  2975. [msg.content isKindOfClass:[WFCCSoundMessageContent class]] ||
  2976. [msg.content isKindOfClass:[WFCCFileMessageContent class]] ||
  2977. [msg.content isKindOfClass:[WFCCLinkMessageContent class]] ||
  2978. [msg.content isKindOfClass:[WFCCArticlesMessageContent class]] ||
  2979. [msg.content isKindOfClass:[WFCCCompositeMessageContent class]]) {
  2980. [items addObject:favoriteItem];
  2981. }
  2982. }
  2983. [menu setMenuItems:items];
  2984. self.cell4Menu = baseCell;
  2985. [menu setMenuVisible:YES];
  2986. }
  2987. -(BOOL)canBecomeFirstResponder {
  2988. return YES;
  2989. }
  2990. -(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  2991. if(self.cell4Menu) {
  2992. if (action == @selector(performDelete:) || action == @selector(performCancel:) || action == @selector(performCopy:) || action == @selector(performForward:) || action == @selector(performRecall:) || action == @selector(performComplain:) || action == @selector(performMultiSelect:) || action == @selector(performQuote:) || action == @selector(performFavorite:)) {
  2993. return YES; //显示自定义的菜单项
  2994. } else {
  2995. return NO;
  2996. }
  2997. }
  2998. if (action == @selector(paste:)) {
  2999. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  3000. return pasteboard.string != nil;
  3001. }
  3002. return NO;//[super canPerformAction:action withSender:sender];
  3003. }
  3004. - (void)paste:(id)sender {
  3005. [self.chatInputBar paste:sender];
  3006. }
  3007. - (void)deleteMessageUI:(long long)messageId {
  3008. for (int i = 0; i < self.modelList.count; i++) {
  3009. WFCUMessageModel *model = [self.modelList objectAtIndex:i];
  3010. if (model.message.messageId == messageId) {
  3011. [self.modelList removeObject:model];
  3012. [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. - (void)deleteMessage:(long)messageId {
  3018. [[WFCCIMService sharedWFCIMService] deleteMessage:messageId];
  3019. [self deleteMessageUI:messageId];
  3020. }
  3021. -(void)performDelete:(UIMenuController *)sender {
  3022. WFCCMessage *message = self.cell4Menu.model.message;
  3023. if([[WFCCIMService sharedWFCIMService] isCommercialServer] && self.conversation.type != Channel_Type) {
  3024. __weak typeof(self)weakSelf = self;
  3025. UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:WFCString(@"ConfirmDelete") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3026. UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  3027. }];
  3028. UIAlertAction *actionLocalDelete = [UIAlertAction actionWithTitle:WFCString(@"DeleteLocalMsg") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  3029. [weakSelf deleteMessage:message.messageId];
  3030. }];
  3031. [actionSheet addAction:actionLocalDelete];
  3032. bool superGroup = false;
  3033. if(self.conversation.type == Group_Type) {
  3034. superGroup = self.targetGroup.superGroup>0;
  3035. }
  3036. //超级群组不支持远端删除
  3037. if(!superGroup) {
  3038. UIAlertAction *actionRemoteDelete = [UIAlertAction actionWithTitle:WFCString(@"DeleteRemoteMsg") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  3039. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
  3040. hud.label.text = WFCString(@"Deleting");
  3041. [hud showAnimated:YES];
  3042. [[WFCCIMService sharedWFCIMService] deleteRemoteMessage:message.messageUid success:^{
  3043. [weakSelf deleteMessageUI:message.messageId];
  3044. [hud hideAnimated:YES];
  3045. } error:^(int error_code) {
  3046. hud.mode = MBProgressHUDModeText;
  3047. hud.label.text = WFCString(@"DeleteFailed");
  3048. [hud hideAnimated:YES afterDelay:1.f];
  3049. }];
  3050. }];
  3051. [actionSheet addAction:actionRemoteDelete];
  3052. }
  3053. [actionSheet addAction:actionCancel];
  3054. [self presentViewController:actionSheet animated:YES completion:nil];
  3055. } else {
  3056. [self deleteMessage:message.messageId];
  3057. }
  3058. }
  3059. -(void)performCancel:(UIMenuController *)sender {
  3060. if (self.cell4Menu) {
  3061. if(![[WFCCIMService sharedWFCIMService] cancelSendingMessage:self.cell4Menu.model.message.messageId]) {
  3062. [self.view makeToast:@"取消失败" duration:1 position:CSToastPositionCenter];
  3063. }
  3064. }
  3065. }
  3066. -(void)performCopy:(UIMenuItem *)sender {
  3067. if (self.cell4Menu) {
  3068. if ([self.cell4Menu.model.message.content isKindOfClass:[WFCCTextMessageContent class]]) {
  3069. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  3070. pasteboard.string = ((WFCCTextMessageContent *)self.cell4Menu.model.message.content).text;
  3071. }
  3072. }
  3073. }
  3074. -(void)performForward:(UIMenuItem *)sender {
  3075. if (self.cell4Menu) {
  3076. WFCUForwardViewController *controller = [[WFCUForwardViewController alloc] init];
  3077. controller.message = self.cell4Menu.model.message;
  3078. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
  3079. [self.navigationController presentViewController:navi animated:YES completion:nil];
  3080. }
  3081. }
  3082. -(void)performRecall:(UIMenuItem *)sender {
  3083. if (self.cell4Menu.model.message) {
  3084. __block MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  3085. hud.label.text = WFCString(@"Recalling");
  3086. [hud showAnimated:YES];
  3087. __weak typeof(self) ws = self;
  3088. long messageId = self.cell4Menu.model.message.messageId;
  3089. WFCUMessageCellBase *cell = self.cell4Menu;
  3090. [[WFCCIMService sharedWFCIMService] recall:self.cell4Menu.model.message success:^{
  3091. dispatch_async(dispatch_get_main_queue(), ^{
  3092. [hud hideAnimated:YES];
  3093. if (cell.model.message.messageId == messageId) {
  3094. if(messageId > 0) {
  3095. cell.model.message = [[WFCCIMService sharedWFCIMService] getMessage:messageId];
  3096. if(cell.model.message) {
  3097. [ws.collectionView reloadItemsAtIndexPaths:@[[ws.collectionView indexPathForCell:cell]]];
  3098. } else {
  3099. [self.modelList removeObject:cell.model];
  3100. [ws.collectionView deleteItemsAtIndexPaths:@[[ws.collectionView indexPathForCell:cell]]];
  3101. }
  3102. [ws updateQuotedMessageWhenRecall:ws.cell4Menu.model.message.messageUid];
  3103. } else {
  3104. //client will replace the message content
  3105. }
  3106. }
  3107. });
  3108. } error:^(int error_code) {
  3109. dispatch_async(dispatch_get_main_queue(), ^{
  3110. hud.mode = MBProgressHUDModeText;
  3111. hud.label.text = WFCString(@"RecallFailure");
  3112. [hud hideAnimated:YES afterDelay:1.f];
  3113. });
  3114. }];
  3115. }
  3116. }
  3117. - (void)performComplain:(UIMenuItem *)sender {
  3118. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:WFCString(@"Complain") message:@"如果您发现有违反法律和道德的内容,或者您的合法权益受到侵犯,请截图之后发送给我们。我们会在24小时之内处理。处理办法包括不限于删除内容,对作者进行警告,冻结账号,甚至报警处理。举报请到\"设置->设置->举报\"联系我们!" preferredStyle:UIAlertControllerStyleAlert];
  3119. UIAlertAction *action = [UIAlertAction actionWithTitle:WFCString(WFCString(@"Ok")) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3120. }];
  3121. [alertController addAction:action];
  3122. [self presentViewController:alertController animated:YES completion:nil];
  3123. }
  3124. - (void)performMultiSelect:(UIMenuItem *)sender {
  3125. self.multiSelecting = !self.multiSelecting;
  3126. }
  3127. - (void)performQuote:(UIMenuItem *)sender {
  3128. if (self.cell4Menu.model.message) {
  3129. [self.chatInputBar appendQuote:self.cell4Menu.model.message];
  3130. }
  3131. }
  3132. - (void)performFavorite:(UIMenuItem *)sender {
  3133. if (self.cell4Menu.model.message) {
  3134. WFCUFavoriteItem *item = [WFCUFavoriteItem itemFromMessage:self.cell4Menu.model.message];
  3135. if (!item) {
  3136. [self.view makeToast:@"暂不支持" duration:1 position:CSToastPositionCenter];
  3137. return;
  3138. }
  3139. item.sender = self.cell4Menu.model.message.fromUser;
  3140. item.conversation = self.cell4Menu.model.message.conversation;
  3141. if (self.cell4Menu.model.message.conversation.type == Single_Type || self.cell4Menu.model.message.conversation.type == SecretChat_Type) {
  3142. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.cell4Menu.model.message.fromUser refresh:NO];
  3143. item.origin = userInfo.displayName;
  3144. } else if (self.cell4Menu.model.message.conversation.type == Group_Type) {
  3145. WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.cell4Menu.model.message.conversation.target refresh:NO];
  3146. item.origin = groupInfo.displayName;
  3147. } else if (self.cell4Menu.model.message.conversation.type == Channel_Type) {
  3148. WFCCChannelInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getChannelInfo:self.cell4Menu.model.message.conversation.target refresh:NO];
  3149. item.origin = groupInfo.name;
  3150. } else {
  3151. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.cell4Menu.model.message.fromUser refresh:NO];
  3152. item.origin = userInfo.displayName;
  3153. }
  3154. __weak typeof(self)ws = self;
  3155. [[WFCUConfigManager globalManager].appServiceProvider addFavoriteItem:item success:^{
  3156. NSLog(@"added");
  3157. [ws.view makeToast:@"已收藏" duration:1 position:CSToastPositionCenter];
  3158. } error:^(int error_code) {
  3159. NSLog(@"add failure");
  3160. [ws.view makeToast:@"网络错误" duration:1 position:CSToastPositionCenter];
  3161. }];
  3162. }
  3163. }
  3164. - (void)onMenuHidden:(id)sender {
  3165. UIMenuController *menu = [UIMenuController sharedMenuController];
  3166. [menu setMenuItems:nil];
  3167. __weak typeof(self)ws = self;
  3168. dispatch_async(dispatch_get_main_queue(), ^{
  3169. ws.cell4Menu = nil;
  3170. });
  3171. }
  3172. //- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
  3173. // [super traitCollectionDidChange:previousTraitCollection];
  3174. // if (@available(iOS 13.0, *)) {
  3175. // if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
  3176. // [self.navigationController popViewControllerAnimated:NO];
  3177. // }
  3178. // }
  3179. //}
  3180. #pragma mark - UITableView
  3181. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  3182. return self.ongoingCallDict.count;
  3183. }
  3184. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  3185. BOOL isFocused = (indexPath.row == self.focusedOngoingCellIndex);
  3186. WFCCMultiCallOngoingMessageContent *ongoing = (WFCCMultiCallOngoingMessageContent *)self.ongoingCallDict[self.ongoingCallDict.allKeys[indexPath.row]].content;
  3187. WFCCUserInfo *userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:ongoing.initiator inGroup:self.conversation.type == Group_Type ? self.conversation.target : nil refresh:NO];
  3188. NSString *userName = userInfo.friendAlias.length ? userInfo.friendAlias : (userInfo.groupAlias.length ? userInfo.groupAlias : userInfo.displayName);
  3189. NSString *callHint = @"通话正在进行中...";
  3190. if(userName.length) {
  3191. callHint = [NSString stringWithFormat:@"%@ 发起的通话正在进行中...", userName];
  3192. }
  3193. if(!isFocused) {
  3194. WFCUMultiCallOngoingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
  3195. if(!cell) {
  3196. cell = [[WFCUMultiCallOngoingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
  3197. }
  3198. cell.callHintLabel.text = callHint;
  3199. return cell;
  3200. } else {
  3201. WFCUMultiCallOngoingExpendedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"expended_cell"];
  3202. if(!cell) {
  3203. cell = [[WFCUMultiCallOngoingExpendedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"expended_cell"];
  3204. cell.delegate = self;
  3205. }
  3206. cell.callHintLabel.text = callHint;
  3207. return cell;
  3208. }
  3209. }
  3210. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  3211. BOOL isFocused = (indexPath.row == self.focusedOngoingCellIndex);
  3212. if(isFocused)
  3213. return 56;
  3214. return 28;
  3215. }
  3216. #if WFCU_SUPPORT_VOIP
  3217. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  3218. if (self.focusedOngoingCellIndex == indexPath.row) {
  3219. self.focusedOngoingCellIndex = -1;
  3220. } else {
  3221. WFCCMessage *message = self.ongoingCallDict[self.ongoingCallDict.allKeys[indexPath.row]];
  3222. WFCCMultiCallOngoingMessageContent *ongoing = (WFCCMultiCallOngoingMessageContent *)message.content;
  3223. if(([ongoing.callId isEqualToString:[WFAVEngineKit sharedEngineKit].currentSession.callId] && [WFAVEngineKit sharedEngineKit].currentSession.state != kWFAVEngineStateIdle) || [ongoing.targetIds containsObject:[WFCCNetworkService sharedInstance].userId] || [message.fromUser isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
  3224. self.focusedOngoingCellIndex = -1;
  3225. } else {
  3226. self.focusedOngoingCellIndex = (int)indexPath.row;
  3227. }
  3228. }
  3229. [self.ongoingCallTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
  3230. }
  3231. #endif
  3232. #pragma mark - WFCUMultiCallOngoingExpendedCellDelegate
  3233. -(void)didJoinButtonPressed {
  3234. if(self.focusedOngoingCellIndex >= 0) {
  3235. WFCCMessage *message = self.ongoingCallDict[self.ongoingCallDict.allKeys[self.focusedOngoingCellIndex]];
  3236. WFCCMultiCallOngoingMessageContent *ongoing = (WFCCMultiCallOngoingMessageContent *)message.content;
  3237. WFCCJoinCallRequestMessageContent *join = [[WFCCJoinCallRequestMessageContent alloc] init];
  3238. join.callId = ongoing.callId;
  3239. join.clientId = [[WFCCNetworkService sharedInstance] getClientId];
  3240. [[WFCCIMService sharedWFCIMService] send:self.conversation content:join success:nil error:nil];
  3241. [self didCancelButtonPressed];
  3242. }
  3243. }
  3244. -(void)didCancelButtonPressed {
  3245. if(self.focusedOngoingCellIndex >= 0) {
  3246. int index = self.focusedOngoingCellIndex;
  3247. self.focusedOngoingCellIndex = -1;
  3248. [self.ongoingCallTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
  3249. }
  3250. }
  3251. //self.imageMsgs = imageMsgs;
  3252. #pragma mark - MWPhotoBrowserDelegate
  3253. - (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
  3254. return self.imageMsgs.count;
  3255. }
  3256. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
  3257. WFCCMessage *msg = self.imageMsgs[index];
  3258. if([msg.content isKindOfClass:[WFCCImageMessageContent class]]) {
  3259. WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)msg.content;
  3260. MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:imgCnt.remoteUrl]];
  3261. photo.message = msg;
  3262. return photo;
  3263. } else if([msg.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  3264. WFCCVideoMessageContent *videoCnt = (WFCCVideoMessageContent *)msg.content;
  3265. MWPhoto *photo = [MWPhoto videoWithURL:[NSURL URLWithString:videoCnt.remoteUrl]];
  3266. photo.message = msg;
  3267. return photo;
  3268. }
  3269. return nil;
  3270. }
  3271. - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
  3272. WFCCMessage *msg = self.imageMsgs[index];
  3273. UIImage *image = nil;
  3274. BOOL video = NO;
  3275. if([msg.content isKindOfClass:[WFCCImageMessageContent class]]) {
  3276. WFCCImageMessageContent *imgCnt = (WFCCImageMessageContent *)msg.content;
  3277. image = imgCnt.thumbnail;
  3278. } else if([msg.content isKindOfClass:[WFCCVideoMessageContent class]]) {
  3279. WFCCVideoMessageContent *videoCnt = (WFCCVideoMessageContent *)msg.content;
  3280. image = videoCnt.thumbnail;
  3281. video = YES;
  3282. }
  3283. MWPhoto *photo = [MWPhoto photoWithImage:image];
  3284. photo.isVideo = video;
  3285. return photo;
  3286. }
  3287. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
  3288. NSLog(@"Did start viewing photo at index %lu", (unsigned long)index);
  3289. }
  3290. - (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
  3291. return NO;
  3292. }
  3293. - (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
  3294. NSLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
  3295. }
  3296. - (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
  3297. // If we subscribe to this method we must dismiss the view controller ourselves
  3298. NSLog(@"Did finish modal presentation");
  3299. [self dismissViewControllerAnimated:YES completion:nil];
  3300. }
  3301. - (void)dealloc {
  3302. [[NSNotificationCenter defaultCenter] removeObserver:self];
  3303. }
  3304. @end