store.js 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  1. import ConnectionStatus from "./wfc/client/connectionStatus";
  2. import Vue from 'vue'
  3. import wfc from "./wfc/client/wfc";
  4. import EventType from "./wfc/client/wfcEvent";
  5. import ConversationType from "./wfc/model/conversationType";
  6. import {eq, gt, numberValue, stringValue} from "./wfc/util/longUtil";
  7. import helper from "./pages/util/helper";
  8. import convert from './vendor/pinyin'
  9. import GroupType from "./wfc/model/groupType";
  10. // import {imageThumbnail, videoDuration, videoThumbnail} from "./ui/util/imageUtil";
  11. import MessageContentMediaType from "./wfc/messages/messageContentMediaType";
  12. import Conversation from "./wfc/model/conversation";
  13. import MessageContentType from "./wfc/messages/messageContentType";
  14. import Message from "./wfc/messages/message";
  15. import ImageMessageContent from "./wfc/messages/imageMessageContent";
  16. import VideoMessageContent from "./wfc/messages/videoMessageContent";
  17. import FileMessageContent from "./wfc/messages/fileMessageContent";
  18. import ForwardType from "@/pages/conversation/message/forward/ForwardType";
  19. import TextMessageContent from "./wfc/messages/textMessageContent";
  20. import SearchType from "./wfc/model/searchType";
  21. import Config from "./config";
  22. import {clear, getItem, removeItem, setItem} from "./pages/util/storageHelper";
  23. import CompositeMessageContent from "./wfc/messages/compositeMessageContent";
  24. // import {getConversationPortrait} from "./ui/util/imageUtil";
  25. import DismissGroupNotification from "./wfc/messages/notification/dismissGroupNotification";
  26. import KickoffGroupMemberNotification from "./wfc/messages/notification/kickoffGroupMemberNotification";
  27. import QuitGroupNotification from "./wfc/messages/notification/quitGroupNotification";
  28. import MessageStatus from "./wfc/messages/messageStatus";
  29. import MessageConfig from "./wfc/client/messageConfig";
  30. import PersistFlag from "./wfc/messages/persistFlag";
  31. import NullGroupInfo from "./wfc/model/nullGroupInfo";
  32. import NullUserInfo from "./wfc/model/nullUserInfo";
  33. import LeaveChannelChatMessageContent from "./wfc/messages/leaveChannelChatMessageContent";
  34. import ArticlesMessageContent from "./wfc/messages/articlesMessageContent";
  35. import EnterChannelChatMessageContent from "./wfc/messages/enterChannelChatMessageContent";
  36. import NullChannelInfo from "./wfc/model/NullChannelInfo";
  37. /**
  38. * 一些说明
  39. * _开头的字段,是为了UI层展示方便,而打补丁上出去的
  40. * __开头的字段,仅内部使用
  41. * _开头的函数,是内部函数
  42. * 外部不直接更新字段,而是通过提供各种action方法更新
  43. */
  44. let store = {
  45. debug: true,
  46. state: {
  47. conversation: {
  48. _wfc: wfc,
  49. currentConversationInfo: null,
  50. conversationInfoList: [],
  51. currentConversationMessageList: [],
  52. currentConversationOldestMessageId: 0,
  53. currentConversationOldestMessageUid: 0,
  54. currentConversationRead: null,
  55. // TODO 调用setUserEnableReceipt时,需要更新
  56. isMessageReceiptEnable: false,
  57. inputtingUser: null,
  58. inputClearHandler: null,
  59. shouldAutoScrollToBottom: true,
  60. previewMediaItems: [],
  61. previewMediaIndex: null,
  62. enableMessageMultiSelection: false,
  63. quotedMessage: null,
  64. downloadingMessages: [],
  65. sendingMessages: [],
  66. currentVoiceMessage: null,
  67. _reset() {
  68. this.currentConversationInfo = null;
  69. this.conversationInfoList = []
  70. this.currentConversationMessageList = [];
  71. this.currentConversationOldestMessageId = 0;
  72. this.currentConversationOldestMessageUid = 0;
  73. this.currentConversationRead = null;
  74. this.isMessageReceiptEnable = false;
  75. this.inputtingUser = null;
  76. this.inputClearHandler = null;
  77. this.shouldAutoScrollToBottom = true;
  78. this.previewMediaItems = [];
  79. this.previewMediaIndex = null;
  80. this.enableMessageMultiSelection = false;
  81. this.quotedMessage = null;
  82. this.downloadingMessages = [];
  83. this.currentVoiceMessage = null;
  84. }
  85. },
  86. contact: {
  87. currentFriendRequest: null,
  88. currentGroup: null,
  89. currentFriend: null,
  90. expandFriendRequestList: false,
  91. expandFriendList: true,
  92. expandGroup: false,
  93. unreadFriendRequestCount: 0,
  94. friendList: [],
  95. friendRequestList: [],
  96. favGroupList: [],
  97. channelList: [],
  98. favContactList: [],
  99. selfUserInfo: null,
  100. _reset() {
  101. this.currentFriendRequest = null;
  102. this.currentGroup = null;
  103. this.currentFriend = null;
  104. this.expandFriendRequestList = false;
  105. this.expandFriendList = true;
  106. this.expandGroup = false;
  107. this.unreadFriendRequestCount = 0;
  108. this.friendList = [];
  109. this.friendRequestList = [];
  110. this.favGroupList = [];
  111. this.favContactList = [];
  112. this.selfUserInfo = null;
  113. }
  114. },
  115. search: {
  116. query: null,
  117. conversation: null,
  118. userSearchResult: [],
  119. contactSearchResult: [],
  120. groupSearchResult: [],
  121. conversationSearchResult: [],
  122. messageSearchResult: [],
  123. _reset() {
  124. this.query = null;
  125. this.conversation = null;
  126. this.userSearchResult = [];
  127. this.contactSearchResult = [];
  128. this.groupSearchResult = [];
  129. this.conversationSearchResult = [];
  130. this.messageSearchResult = [];
  131. }
  132. },
  133. pick: {
  134. users: [],
  135. conversations: [],
  136. messages: [],
  137. _reset() {
  138. this.users = [];
  139. this.conversations = [];
  140. this.messages = [];
  141. }
  142. },
  143. misc: {
  144. connectionStatus: ConnectionStatus.ConnectionStatusUnconnected,
  145. isAppHidden: false,
  146. enableNotification: true,
  147. enableNotificationMessageDetail: true,
  148. uploadBigFiles: [],
  149. wfc: wfc,
  150. config: Config,
  151. isRecording: false,
  152. userOnlineStateMap: new Map(),
  153. _reset() {
  154. this.connectionStatus = ConnectionStatus.ConnectionStatusUnconnected;
  155. this.enableNotification = true;
  156. this.enableNotificationMessageDetail = true;
  157. this.uploadBigFiles = [];
  158. this.wfc = wfc;
  159. this.config = Config;
  160. this.isRecording = false;
  161. this.userOnlineStateMap = new Map();
  162. }
  163. },
  164. },
  165. init() {
  166. console.log('init store')
  167. // 目前,通知只可能在主窗口触发
  168. wfc.eventEmitter.on(EventType.ConnectionStatusChanged, (status) => {
  169. miscState.connectionStatus = status;
  170. console.log('connection status changed', status);
  171. if (status === ConnectionStatus.ConnectionStatusConnected) {
  172. this._loadDefaultData();
  173. } else if (status === ConnectionStatus.ConnectionStatusLogout
  174. || status === ConnectionStatus.ConnectionStatusRejected
  175. || status === ConnectionStatus.ConnectionStatusSecretKeyMismatch
  176. || status === ConnectionStatus.ConnectionStatusKickedOff
  177. || status === ConnectionStatus.ConnectionStatusTokenIncorrect) {
  178. // 清除 token 等
  179. clear();
  180. if (status === ConnectionStatus.ConnectionStatusKickedOff) {
  181. wfc.disconnect();
  182. }
  183. _reset();
  184. }
  185. });
  186. wfc.eventEmitter.on(EventType.UserInfosUpdate, (userInfos) => {
  187. console.log('store UserInfosUpdate', userInfos, miscState.connectionStatus)
  188. this._reloadSingleConversationIfExist(userInfos);
  189. // TODO optimize
  190. this._loadCurrentConversationMessages();
  191. this._loadFriendList();
  192. this._loadFriendRequest();
  193. this._loadSelfUserInfo();
  194. // TODO 其他相关逻辑
  195. });
  196. wfc.eventEmitter.on(EventType.SettingUpdate, () => {
  197. console.log('store SettingUpdate')
  198. this._loadDefaultConversationList();
  199. this._loadFavContactList();
  200. this._loadFavGroupList();
  201. this._loadChannelList();
  202. this._loadCurrentConversationMessages();
  203. });
  204. wfc.eventEmitter.on(EventType.FriendRequestUpdate, (newFrs) => {
  205. this._loadFriendRequest();
  206. });
  207. wfc.eventEmitter.on(EventType.FriendListUpdate, (updatedFriendIds) => {
  208. this._loadFriendList();
  209. this._loadFriendRequest();
  210. this._loadFavContactList();
  211. this._loadDefaultConversationList();
  212. this._loadCurrentConversationMessages();
  213. });
  214. wfc.eventEmitter.on(EventType.GroupInfosUpdate, (groupInfos) => {
  215. // TODO optimize
  216. console.log('store GroupInfosUpdate', groupInfos)
  217. this._reloadGroupConversationIfExist(groupInfos);
  218. this._loadFavGroupList();
  219. // TODO 其他相关逻辑
  220. });
  221. wfc.eventEmitter.on(EventType.GroupMembersUpdate, (groupId, members) => {
  222. // TODO optimize
  223. console.log('store GroupMembersUpdate', groupId)
  224. this._reloadGroupConversationIfExist([new NullGroupInfo(groupId)]);
  225. // this._loadFavGroupList();
  226. // TODO 其他相关逻辑
  227. });
  228. wfc.eventEmitter.on(EventType.ChannelInfosUpdate, (groupInfos) => {
  229. this._loadDefaultConversationList();
  230. this._loadChannelList();
  231. });
  232. wfc.eventEmitter.on(EventType.ConversationInfoUpdate, (conversationInfo) => {
  233. this._reloadConversation(conversationInfo.conversation)
  234. if (conversationState.currentConversationInfo && conversationState.currentConversationInfo.conversation.equal(conversationInfo.conversation)) {
  235. this._loadCurrentConversationMessages();
  236. }
  237. });
  238. wfc.eventEmitter.on(EventType.ReceiveMessage, (msg, hasMore) => {
  239. console.log('receiveMessage', hasMore);
  240. if (miscState.connectionStatus === ConnectionStatus.ConnectionStatusReceiveing) {
  241. return;
  242. }
  243. if (!hasMore) {
  244. this._reloadConversation(msg.conversation)
  245. }
  246. if (conversationState.currentConversationInfo && msg.conversation.equal(conversationState.currentConversationInfo.conversation)) {
  247. if (msg.messageContent instanceof DismissGroupNotification
  248. || (msg.messageContent instanceof KickoffGroupMemberNotification && msg.messageContent.kickedMembers.indexOf(wfc.getUserId()) >= 0)
  249. || (msg.messageContent instanceof QuitGroupNotification && msg.messageContent.operator === wfc.getUserId())
  250. ) {
  251. this.setCurrentConversationInfo(null);
  252. return;
  253. }
  254. // 移动端,目前只有单聊会发送typing消息
  255. if (msg.messageContent.type === MessageContentType.Typing) {
  256. let groupId = msg.conversation.type === 1 ? msg.conversation.target : '';
  257. let userInfo = wfc.getUserInfo(msg.from, false, groupId)
  258. userInfo = Object.assign({}, userInfo);
  259. userInfo._displayName = wfc.getGroupMemberDisplayNameEx(userInfo);
  260. conversationState.inputtingUser = userInfo;
  261. if (!conversationState.inputClearHandler) {
  262. conversationState.inputClearHandler = () => {
  263. conversationState.inputtingUser = null;
  264. }
  265. }
  266. clearTimeout(conversationState.inputClearHandler);
  267. setTimeout(conversationState.inputClearHandler, 3000)
  268. } else {
  269. clearTimeout(conversationState.inputClearHandler);
  270. conversationState.inputtingUser = null;
  271. }
  272. if (!this._isDisplayMessage(msg) || msg.messageContent.type === MessageContentType.RecallMessage_Notification) {
  273. return;
  274. }
  275. let msgIndex = conversationState.currentConversationMessageList.findIndex(m => {
  276. return m.messageId === msg.messageId || eq(m.messageUid, msg.messageUid);
  277. });
  278. if (msgIndex > -1) {
  279. console.log('msg duplicate')
  280. return;
  281. }
  282. // 会把下来加载更多加载的历史消息给清理了
  283. let lastTimestamp = 0;
  284. let msgListLength = conversationState.currentConversationMessageList.length;
  285. if (msgListLength > 0) {
  286. lastTimestamp = conversationState.currentConversationMessageList[msgListLength - 1].timestamp;
  287. }
  288. this._patchMessage(msg, lastTimestamp);
  289. conversationState.currentConversationMessageList.push(msg);
  290. }
  291. // 没有使用 uikit 默认的通知处理
  292. if (msg.conversation.type !== 2 && miscState.isAppHidden && (miscState.enableNotification || msg.status === MessageStatus.AllMentioned || msg.status === MessageStatus.Mentioned)) {
  293. this.notify(msg);
  294. }
  295. });
  296. wfc.eventEmitter.on(EventType.RecallMessage, (operator, messageUid) => {
  297. this._reloadConversationByMessageUidIfExist(messageUid);
  298. if (conversationState.currentConversationInfo) {
  299. let msg = wfc.getMessageByUid(messageUid);
  300. if (msg && msg.conversation.equal(conversationState.currentConversationInfo.conversation)) {
  301. if (conversationState.currentConversationMessageList) {
  302. let lastTimestamp = 0;
  303. conversationState.currentConversationMessageList = conversationState.currentConversationMessageList.map(msg => {
  304. if (eq(msg.messageUid, messageUid)) {
  305. let newMsg = wfc.getMessageByUid(messageUid);
  306. this._patchMessage(newMsg, lastTimestamp);
  307. return newMsg;
  308. }
  309. lastTimestamp = msg.timestamp;
  310. return msg;
  311. });
  312. }
  313. }
  314. }
  315. });
  316. wfc.eventEmitter.on(EventType.UserOnlineEvent, (userOnlineStatus) => {
  317. userOnlineStatus.forEach(e => {
  318. miscState.userOnlineStateMap.set(e.userId, e);
  319. })
  320. // 更新在线状态
  321. contactState.friendList = this._patchAndSortUserInfos(contactState.friendList, '');
  322. })
  323. // 服务端删除
  324. wfc.eventEmitter.on(EventType.MessageDeleted, (messageUid) => {
  325. this._reloadConversationByMessageUidIfExist(messageUid);
  326. if (conversationState.currentConversationInfo) {
  327. if (conversationState.currentConversationMessageList) {
  328. conversationState.currentConversationMessageList = conversationState.currentConversationMessageList.filter(msg => !eq(msg.messageUid, messageUid))
  329. }
  330. }
  331. });
  332. // 本地删除
  333. wfc.eventEmitter.on(EventType.DeleteMessage, (messageId) => {
  334. this._reloadConversationByMessageIdIfExist(messageId);
  335. if (conversationState.currentConversationInfo) {
  336. if (conversationState.currentConversationMessageList) {
  337. conversationState.currentConversationMessageList = conversationState.currentConversationMessageList.filter(msg => msg.messageId !== messageId)
  338. }
  339. }
  340. });
  341. wfc.eventEmitter.on(EventType.SendMessage, (message) => {
  342. // 删除频道,或者从频道会话切到其他会话时,会发送一条离开频道的消息
  343. if (message.messageContent instanceof LeaveChannelChatMessageContent) {
  344. return;
  345. }
  346. this._reloadConversation(message.conversation);
  347. if (!this._isDisplayMessage(message)) {
  348. return;
  349. }
  350. if (!conversationState.currentConversationInfo || !message.conversation.equal(conversationState.currentConversationInfo.conversation)) {
  351. console.log('not current conv')
  352. return;
  353. }
  354. let index = conversationState.currentConversationMessageList.findIndex(m => m.messageId === message.messageId);
  355. if (index !== -1) {
  356. return;
  357. }
  358. let length = conversationState.currentConversationMessageList.length;
  359. let lastTimestamp = 0;
  360. if (length > 0) {
  361. let lastMessage = conversationState.currentConversationMessageList[length - 1];
  362. lastTimestamp = lastMessage.timestamp;
  363. }
  364. this._patchMessage(message, lastTimestamp)
  365. conversationState.currentConversationMessageList.push(message);
  366. });
  367. wfc.eventEmitter.on(EventType.MessageStatusUpdate, (message) => {
  368. console.log('message status update', message)
  369. if (!this._isDisplayMessage(message)) {
  370. return;
  371. }
  372. if (!conversationState.currentConversationInfo || !message.conversation.equal(conversationState.currentConversationInfo.conversation)) {
  373. console.log('not current conv')
  374. return;
  375. }
  376. let index = conversationState.currentConversationMessageList.findIndex(m => m.messageId === message.messageId);
  377. if (index < 0) {
  378. return;
  379. }
  380. let msg = conversationState.currentConversationMessageList[index];
  381. Object.assign(msg, message)
  382. if (conversationState.currentConversationInfo.lastMessage && conversationState.currentConversationInfo.lastMessage.messageId === message.messageId) {
  383. Object.assign(conversationState.currentConversationInfo.lastMessage, message);
  384. }
  385. });
  386. wfc.eventEmitter.on(EventType.MessageRead, (readEntries) => {
  387. // optimization
  388. if (conversationState.currentConversationInfo) {
  389. // wfc.getConversationRead 每次返回同一个对象,只是该对象的值不一样。
  390. // 由于 VUE 不能检测到初始化时,不存在的属性的变更,故此处重新 new 一个新的对象,并赋值。
  391. // FYI:https://vuejs.org/v2/guide/reactivity.html
  392. conversationState.currentConversationRead = new Map(wfc.getConversationRead(conversationState.currentConversationInfo.conversation));
  393. }
  394. });
  395. if (wfc.getConnectionStatus() === ConnectionStatus.ConnectionStatusConnected) {
  396. this._loadDefaultData();
  397. }
  398. miscState.connectionStatus = wfc.getConnectionStatus();
  399. },
  400. _loadDefaultData() {
  401. console.log('store.js', '_loadDefaultData');
  402. this._loadFavGroupList();
  403. this._loadChannelList();
  404. this._loadFriendList();
  405. this._loadFavContactList();
  406. this._loadFriendRequest();
  407. this._loadSelfUserInfo();
  408. this._loadDefaultConversationList();
  409. this._loadUserLocalSettings();
  410. conversationState.isMessageReceiptEnable = wfc.isReceiptEnabled() && wfc.isUserReceiptEnabled();
  411. if (conversationState.currentConversationInfo) {
  412. this._loadCurrentConversationMessages();
  413. }
  414. },
  415. // conversation actions
  416. _isDisplayMessage(message) {
  417. // return [PersistFlag.Persist, PersistFlag.Persist_And_Count].indexOf(MessageConfig.getMessageContentPersitFlag(message.messageContent.type)) > -1;
  418. return message.messageId !== 0;
  419. },
  420. _loadDefaultConversationList() {
  421. this._loadConversationList([0, 1, 3], [0])
  422. },
  423. _loadConversationList(conversationType = [0, 1, 3], lines = [0]) {
  424. let conversationList = wfc.getConversationList(conversationType, lines);
  425. let toLoadUserIdSet = new Set();
  426. let toLoadGroupIds = [];
  427. console.log('_loadConversationList size', conversationList.length);
  428. conversationList.forEach(info => {
  429. if (info.conversation.type === ConversationType.Single) {
  430. toLoadUserIdSet.add(info.conversation.target)
  431. if (info.lastMessage) {
  432. toLoadUserIdSet.add(info.lastMessage.from);
  433. }
  434. } else if (info.conversation.type === ConversationType.Group) {
  435. toLoadGroupIds.push(info.conversation.target)
  436. if (info.lastMessage) {
  437. toLoadUserIdSet.add(info.lastMessage.from);
  438. }
  439. }
  440. })
  441. let userInfoMap = new Map();
  442. let groupInfoMap = new Map();
  443. toLoadUserIdSet.forEach(uid => {
  444. userInfoMap.set(uid, new NullUserInfo(uid));
  445. })
  446. toLoadGroupIds.forEach(gid => {
  447. groupInfoMap.set(gid, new NullGroupInfo(gid))
  448. })
  449. console.log('to load userIds', toLoadUserIdSet.size);
  450. wfc.getUserInfos([...toLoadUserIdSet], '')
  451. .forEach(u => {
  452. userInfoMap.set(u.uid, u);
  453. });
  454. wfc.getGroupInfos(toLoadGroupIds)
  455. .forEach(g => {
  456. groupInfoMap.set(g.target, g);
  457. });
  458. conversationList.forEach(info => {
  459. this._patchConversationInfo(info, true, userInfoMap, groupInfoMap);
  460. // side affect
  461. if (conversationState.currentConversationInfo
  462. && conversationState.currentConversationInfo.conversation.equal(info.conversation)) {
  463. conversationState.currentConversationInfo = info;
  464. this._patchCurrentConversationOnlineStatus();
  465. }
  466. });
  467. conversationState.conversationInfoList = conversationList;
  468. },
  469. _reloadConversation(conversation, insertIfNoExist = true) {
  470. let conversationInfo = wfc.getConversationInfo(conversation);
  471. if (conversationInfo) {
  472. conversationInfo = this._patchConversationInfo(conversationInfo);
  473. }
  474. let index = conversationState.conversationInfoList.findIndex(info => info.conversation.equal(conversation));
  475. if (index >= 0) {
  476. Object.assign(conversationState.conversationInfoList[index], conversationInfo);
  477. } else {
  478. if (insertIfNoExist && conversation.type !== ConversationType.ChatRoom) {
  479. conversationState.conversationInfoList.push(conversationInfo);
  480. } else {
  481. return conversationInfo;
  482. }
  483. }
  484. if (conversationState.currentConversationInfo && conversationState.currentConversationInfo.conversation.equal(conversation)) {
  485. conversationState.currentConversationInfo = conversationInfo;
  486. }
  487. // sort
  488. conversationState.conversationInfoList.sort((a, b) => {
  489. if ((a.top && b.top) || (!a.top && !b.top)) {
  490. return gt(a.timestamp, b.timestamp) ? -1 : 1;
  491. } else {
  492. if (a.top) {
  493. return -1;
  494. } else {
  495. return 1;
  496. }
  497. }
  498. })
  499. return conversationInfo;
  500. },
  501. _reloadSingleConversationIfExist(userInfos) {
  502. if (userInfos.length > 10) {
  503. this._loadDefaultConversationList();
  504. } else {
  505. userInfos.forEach(ui => {
  506. let conv = new Conversation(ConversationType.Single, ui.uid, 0);
  507. this._reloadConversation(conv, false);
  508. })
  509. }
  510. },
  511. _reloadGroupConversationIfExist(groupInfos) {
  512. if (groupInfos.length > 10) {
  513. this._loadDefaultConversationList();
  514. } else {
  515. groupInfos.forEach(gi => {
  516. let conv = new Conversation(ConversationType.Group, gi.target, 0);
  517. this._reloadConversation(conv, false);
  518. })
  519. }
  520. },
  521. _reloadConversationByMessageIdIfExist(messageId) {
  522. if (messageId === 0) {
  523. return;
  524. }
  525. let toLoadConversationInfo = null;
  526. for (let i = 0; i < conversationState.conversationInfoList.length; i++) {
  527. let info = conversationState.conversationInfoList[i];
  528. if (info.lastMessage && info.lastMessage.messageId === messageId) {
  529. toLoadConversationInfo = info;
  530. break;
  531. }
  532. }
  533. if (toLoadConversationInfo) {
  534. this._reloadConversation(toLoadConversationInfo.conversation)
  535. }
  536. },
  537. _reloadConversationByMessageUidIfExist(messageUid) {
  538. let toLoadConversationInfo = null;
  539. for (let i = 0; i < conversationState.conversationInfoList.length; i++) {
  540. let info = conversationState.conversationInfoList[i];
  541. if (info.lastMessage && eq(info.lastMessage.messageUid, messageUid)) {
  542. toLoadConversationInfo = info;
  543. break;
  544. }
  545. }
  546. if (toLoadConversationInfo) {
  547. this._reloadConversation(toLoadConversationInfo.conversation)
  548. }
  549. },
  550. setCurrentConversation(conversation) {
  551. if (!conversation) {
  552. this.setCurrentConversationInfo(null)
  553. return;
  554. }
  555. if (conversationState.currentConversationInfo && conversation.equal(conversationState.currentConversationInfo.conversation)) {
  556. return;
  557. }
  558. let convs = conversationState.conversationInfoList.filter(info => info.conversation.equal(conversation));
  559. let info;
  560. if (convs && convs.length > 0) {
  561. info = convs[0];
  562. } else {
  563. wfc.setConversationTimestamp(conversation, new Date().getTime());
  564. info = this._reloadConversation(conversation);
  565. }
  566. this.setCurrentConversationInfo(info);
  567. },
  568. setCurrentConversationInfo(conversationInfo) {
  569. if (!conversationInfo) {
  570. if (conversationState.currentConversationInfo) {
  571. let conversation = conversationState.currentConversationInfo.conversation;
  572. if ([ConversationType.Single, ConversationType.Group].indexOf(conversation.type) >= 0) {
  573. wfc.unwatchOnlineState(conversation.type, [conversation.target]);
  574. } else if (conversation.type === ConversationType.Channel) {
  575. let content = new LeaveChannelChatMessageContent();
  576. wfc.sendConversationMessage(conversation, content);
  577. } else if (conversation.type === ConversationType.ChatRoom) {
  578. wfc.quitChatroom(conversation.target)
  579. }
  580. }
  581. conversationState.currentConversationInfo = null;
  582. conversationState.shouldAutoScrollToBottom = false;
  583. conversationState.currentConversationMessageList.length = 0;
  584. conversationState.currentConversationOldestMessageId = 0;
  585. conversationState.currentConversationOldestMessageUid = 0;
  586. conversationState.currentConversationRead = null;
  587. conversationState.enableMessageMultiSelection = false;
  588. return;
  589. }
  590. if (conversationState.currentConversationInfo && conversationState.currentConversationInfo.conversation.equal(conversationInfo.conversation)) {
  591. return;
  592. }
  593. let conversation = conversationInfo.conversation;
  594. if (conversation.type === ConversationType.Group || (conversation.type === ConversationType.Single && !wfc.isMyFriend(conversation.target))) {
  595. wfc.watchOnlineState(conversation.type, [conversation.target], 1000, (states) => {
  596. states.forEach((e => {
  597. miscState.userOnlineStateMap.set(e.userId, e);
  598. }))
  599. this._patchCurrentConversationOnlineStatus();
  600. }, (err) => {
  601. console.log('watchOnlineState error', err);
  602. })
  603. }
  604. if (conversation.type === ConversationType.Channel) {
  605. let content = new EnterChannelChatMessageContent();
  606. wfc.sendConversationMessage(conversation, content);
  607. } else if (conversation.type === ConversationType.ChatRoom) {
  608. wfc.joinChatroom(conversation.target);
  609. }
  610. conversationState.currentConversationInfo = conversationInfo;
  611. conversationState.shouldAutoScrollToBottom = true;
  612. conversationState.currentConversationMessageList.length = 0;
  613. conversationState.currentConversationOldestMessageId = 0;
  614. conversationState.currentConversationOldestMessageUid = 0;
  615. this._loadCurrentConversationMessages();
  616. conversationState.currentConversationRead = wfc.getConversationRead(conversationInfo.conversation);
  617. conversationState.enableMessageMultiSelection = false;
  618. conversationState.showChannelMenu = false;
  619. if (conversation.type === ConversationType.Channel) {
  620. let channelInfo = wfc.getChannelInfo(conversation.target, true);
  621. if (channelInfo.menus && channelInfo.menus.length > 0) {
  622. conversationState.showChannelMenu = true;
  623. }
  624. } else if (conversation.type === ConversationType.Group) {
  625. wfc.getGroupInfo(conversation.target, true);
  626. } else if (conversation.type === ConversationType.Single) {
  627. wfc.getUserInfo(conversation.target, true);
  628. }
  629. conversationState.quotedMessage = null;
  630. conversationState.currentVoiceMessage = null;
  631. clearTimeout(conversationState.inputClearHandler);
  632. conversationState.inputtingUser = null;
  633. pickState.messages.length = 0;
  634. },
  635. quitGroup(groupId) {
  636. wfc.quitGroup(groupId, [0], null, () => {
  637. this.setCurrentConversationInfo(null)
  638. }, (err) => {
  639. console.log('quit group error', err)
  640. })
  641. },
  642. subscribeChannel(channelId, subscribe) {
  643. wfc.listenChannel(channelId, subscribe, () => {
  644. //this.setCurrentConversationInfo(null)
  645. }, (err) => {
  646. console.log('unsubscribe channel error', err)
  647. })
  648. },
  649. toggleMessageMultiSelection(message) {
  650. conversationState.enableMessageMultiSelection = !conversationState.enableMessageMultiSelection;
  651. pickState.messages.length = 0;
  652. if (conversationState.enableMessageMultiSelection && message) {
  653. pickState.messages.push(message);
  654. }
  655. },
  656. toggleChannelMenu(toggle) {
  657. conversationState.showChannelMenu = toggle;
  658. },
  659. selectOrDeselectMessage(message) {
  660. let index = pickState.messages.findIndex(m => m.messageId === message.messageId);
  661. if (index >= 0) {
  662. pickState.messages.splice(index, 1);
  663. } else {
  664. pickState.messages.push(message);
  665. }
  666. },
  667. deleteSelectedMessages() {
  668. conversationState.enableMessageMultiSelection = false;
  669. if (pickState.messages.length < 1) {
  670. return;
  671. }
  672. pickState.messages.sort((m1, m2) => m1.messageId - m2.messageId);
  673. pickState.messages.forEach(m => {
  674. wfc.deleteMessage(m.messageId);
  675. });
  676. pickState.messages.length = 0;
  677. },
  678. forwardMessage(forwardType, targetConversations, messages, extraMessageText) {
  679. targetConversations.forEach(conversation => {
  680. // let msg =new Message(conversation, message.messageContent)
  681. // wfc.sendMessage(msg)
  682. // 或者下面这种
  683. if (forwardType === ForwardType.NORMAL || forwardType === ForwardType.ONE_BY_ONE) {
  684. messages.forEach(message => {
  685. if (message.messageContent instanceof ArticlesMessageContent) {
  686. let linkContents = message.messageContent.toLinkMessageContent();
  687. linkContents.forEach(lm => {
  688. wfc.sendConversationMessage(conversation, lm);
  689. })
  690. } else {
  691. wfc.sendConversationMessage(conversation, message.messageContent);
  692. }
  693. });
  694. } else {
  695. // 合并转发
  696. let compositeMessageContent = new CompositeMessageContent();
  697. let title = '';
  698. let msgConversation = messages[0].conversation;
  699. if (msgConversation.type === ConversationType.Single) {
  700. let users = store.getUserInfos([wfc.getUserId(), msgConversation.target], '');
  701. title = users[0]._displayName + '和' + users[1]._displayName + '的聊天记录';
  702. } else {
  703. title = '群的聊天记录';
  704. }
  705. compositeMessageContent.title = title;
  706. compositeMessageContent.setMessages(messages);
  707. wfc.sendConversationMessage(conversation, compositeMessageContent);
  708. }
  709. if (extraMessageText) {
  710. let textMessage = new TextMessageContent(extraMessageText)
  711. wfc.sendConversationMessage(conversation, textMessage);
  712. }
  713. });
  714. },
  715. forwardByCreateConversation(forwardType, users, messages, extraMessageText) {
  716. this.createConversation(users,
  717. (conversation) => {
  718. this.forwardMessage(forwardType, [conversation], messages, extraMessageText)
  719. },
  720. (err) => {
  721. console.error('createConversation error', err)
  722. })
  723. },
  724. setShouldAutoScrollToBottom(scroll) {
  725. conversationState.shouldAutoScrollToBottom = scroll;
  726. },
  727. /**
  728. *
  729. * @param src {String} 媒体url
  730. * @param thumbUrl {String} 缩略图url
  731. * @param thumb {String} base64格式的缩略图,但不包含'data:image/png;base64,'
  732. * @param autoplay
  733. */
  734. previewMedia(src, thumbUrl, thumb, autoplay = true) {
  735. conversationState.previewMediaItems.length = 0;
  736. conversationState.previewMediaItems.push({
  737. src: src,
  738. thumb: thumbUrl ? thumbUrl : 'data:image/png;base64,' + thumb,
  739. autoplay: autoplay,
  740. });
  741. conversationState.previewMediaIndex = 0;
  742. console.log('preview media', conversationState.previewMediaItems, conversationState.previewMediaIndex)
  743. },
  744. previewMedias(mediaItems, index) {
  745. conversationState.previewMediaItems.length = 0;
  746. conversationState.previewMediaItems.push(...mediaItems);
  747. conversationState.previewMediaIndex = index;
  748. console.log('preview medias', conversationState.previewMediaItems, conversationState.previewMediaIndex)
  749. },
  750. playVoice(message) {
  751. if (conversationState.currentVoiceMessage) {
  752. conversationState.currentVoiceMessage._isPlaying = false;
  753. }
  754. conversationState.currentVoiceMessage = message;
  755. },
  756. /**
  757. *
  758. * @param message
  759. * @param {Boolean} continuous true,预览周围的媒体消息;false,只预览第一个参数传入的那条媒体消息
  760. */
  761. previewMessage(message, continuous) {
  762. conversationState.previewMediaItems.length = 0;
  763. conversationState.previewMediaIndex = 0;
  764. if (continuous && conversationState.currentConversationMessageList.length > 0) {
  765. let mediaMsgs = conversationState.currentConversationMessageList.filter(m => [MessageContentType.Image, MessageContentType.Video].indexOf(m.messageContent.type) > -1)
  766. let msg;
  767. for (let i = 0; i < mediaMsgs.length; i++) {
  768. msg = mediaMsgs[i];
  769. if (msg.messageId === message.messageId) {
  770. conversationState.previewMediaIndex = i;
  771. }
  772. conversationState.previewMediaItems.push({
  773. src: msg.messageContent.remotePath,
  774. thumb: 'data:image/png;base64,' + msg.messageContent.thumbnail,
  775. autoplay: true,
  776. });
  777. }
  778. } else {
  779. conversationState.previewMediaIndex = 0;
  780. conversationState.previewMediaItems.push({
  781. src: message.messageContent.remotePath,
  782. thumb: 'data:image/png;base64,' + message.messageContent.thumbnail,
  783. autoplay: true,
  784. });
  785. }
  786. },
  787. previewCompositeMessage(compositeMessage, focusMessageUid) {
  788. conversationState.previewMediaItems.length = 0;
  789. conversationState.previewMediaIndex = 0;
  790. let mediaMsgs = compositeMessage.messageContent.messages.filter(m => [MessageContentType.Image, MessageContentType.Video].indexOf(m.messageContent.type) > -1)
  791. let msg;
  792. for (let i = 0; i < mediaMsgs.length; i++) {
  793. msg = mediaMsgs[i];
  794. if (eq(msg.messageUid, focusMessageUid)) {
  795. conversationState.previewMediaIndex = i;
  796. }
  797. conversationState.previewMediaItems.push({
  798. src: msg.messageContent.remotePath,
  799. thumb: 'data:image/png;base64,' + msg.messageContent.thumbnail,
  800. autoplay: true,
  801. });
  802. }
  803. },
  804. /**
  805. *
  806. * @param conversation
  807. * @param {File | string} file html File 类型或者url,绝对路径只在electron里面生效
  808. * @return {Promise<boolean>}
  809. */
  810. async sendFile(conversation, file) {
  811. if (file.size && file.size > 100 * 1024 * 1024) {
  812. if (!wfc.isSupportBigFilesUpload() || conversation.type === ConversationType.SecretChat) {
  813. console.log('file too big, and not support upload big file')
  814. return true;
  815. }
  816. }
  817. let fileOrLocalPath = null;
  818. let remotePath = null;
  819. if (typeof file === 'string') {
  820. if (!file.startsWith('http')) {
  821. fileOrLocalPath = file;
  822. } else {
  823. remotePath = file;
  824. }
  825. file = {
  826. path: file,
  827. name: file.substring((file.lastIndexOf('/') + 1))
  828. }
  829. } else {
  830. fileOrLocalPath = file;
  831. }
  832. let msg = new Message();
  833. msg.conversation = conversation;
  834. let mediaType = helper.getMediaType(file.name.split('.').slice(-1).pop());
  835. // todo other file type
  836. let messageContentmediaType = {
  837. 'pic': MessageContentMediaType.Image,
  838. 'video': MessageContentMediaType.Video,
  839. 'doc': MessageContentMediaType.File,
  840. }[mediaType];
  841. let messageContent;
  842. switch (messageContentmediaType) {
  843. case MessageContentMediaType.Image:
  844. messageContent = new ImageMessageContent(fileOrLocalPath, remotePath);
  845. break;
  846. case MessageContentMediaType.Video:
  847. messageContent = new VideoMessageContent(fileOrLocalPath, remotePath, '', 0);
  848. break;
  849. case MessageContentMediaType.File:
  850. messageContent = new FileMessageContent(fileOrLocalPath, remotePath);
  851. break;
  852. default:
  853. console.log('not support file')
  854. return false;
  855. }
  856. msg.messageContent = messageContent;
  857. wfc.sendMessage(msg,
  858. (messageId) => {
  859. msg.messageId = messageId;
  860. console.log('sf, pr', messageId)
  861. },
  862. (progress, total) => {
  863. // console.log('sf p', msg.messageId, Math.ceil(progress / total * 100))
  864. let sm = conversationState.sendingMessages.find(e => e.messageId === msg.messageId);
  865. if (sm) {
  866. sm.progress = progress;
  867. sm.total = total;
  868. } else {
  869. conversationState.sendingMessages.push({messageId: msg.messageId, progress, total});
  870. }
  871. },
  872. (messageUid) => {
  873. console.log('sf s', messageUid)
  874. conversationState.sendingMessages = conversationState.sendingMessages.filter(e => e.messageId !== msg.messageId);
  875. },
  876. (error) => {
  877. console.log('sf e', error)
  878. conversationState.sendingMessages = conversationState.sendingMessages.filter(e => e.messageId !== msg.messageId);
  879. }
  880. );
  881. },
  882. quoteMessage(message) {
  883. conversationState.quotedMessage = message;
  884. },
  885. getConversationInfo(conversation) {
  886. let info = wfc.getConversationInfo(conversation);
  887. return this._patchConversationInfo(info, false);
  888. },
  889. /**
  890. * 获取会话消息
  891. * @param {Conversation} conversation 会话
  892. * @param {number} fromIndex 其实消息的 messageId
  893. * @param {boolean} before 获取其实消息之前,还是之后的消息
  894. * @param {string} withUser 过滤该用户发送或接收的消息
  895. * @param {function (Message[]) } callback 消息列表会回调
  896. */
  897. getMessages(conversation, fromIndex = 0, before = true, withUser = '', callback) {
  898. wfc.getMessagesV2(conversation, fromIndex, before, 20, withUser, msgs => {
  899. msgs = msgs.map(m => this._patchMessage(m, 0));
  900. //callback && callback(msgs);
  901. callback && callback(msgs);
  902. }, err => {
  903. console.error('getMessageV2 error', err)
  904. callback && callback([]);
  905. });
  906. },
  907. getMessageInTypes(conversation, contentTypes, timestamp, before = true, withUser = '', callback) {
  908. wfc.getMessagesByTimestampV2(conversation, contentTypes, timestamp, before, 20, withUser, msgs => {
  909. msgs = msgs.map(m => this._patchMessage(m, 0));
  910. setTimeout(() => callback && callback(msgs), 200)
  911. }, err => {
  912. callback && callback([]);
  913. });
  914. },
  915. _loadCurrentConversationMessages() {
  916. console.log('_loadCurrentConversationMessages')
  917. if (!conversationState.currentConversationInfo) {
  918. return;
  919. }
  920. let conversation = conversationState.currentConversationInfo.conversation;
  921. wfc.getMessagesV2(conversation, 0, true, 20, '', msgs => {
  922. conversationState.currentConversationMessageList = msgs;
  923. this._patchCurrentConversationMessages();
  924. if (msgs.length) {
  925. conversationState.currentConversationOldestMessageId = msgs[0].messageId;
  926. }
  927. for (let i = 0; i < msgs.length; i++) {
  928. if (gt(msgs[i].messageUid, 0)) {
  929. conversationState.currentConversationOldestMessageUid = msgs[0].messageUid;
  930. break;
  931. }
  932. }
  933. console.log('_loadCurrentConversationMessages success', conversation, msgs)
  934. }, err => {
  935. console.error('_loadCurrentConversationMessages error', err);
  936. });
  937. },
  938. _patchCurrentConversationMessages() {
  939. let lastTimestamp = 0;
  940. let msgs = conversationState.currentConversationMessageList;
  941. msgs.forEach(m => {
  942. this._patchMessage(m, lastTimestamp);
  943. lastTimestamp = m.timestamp;
  944. });
  945. },
  946. _onloadConversationMessages(conversation, messages) {
  947. if (!messages || messages.length === 0) {
  948. return false;
  949. }
  950. let loadNewMsg = false;
  951. let lastTimestamp = 0;
  952. let newMsgs = [];
  953. messages.forEach(m => {
  954. let index = conversationState.currentConversationMessageList.findIndex(cm => cm.messageId === m.messageId)
  955. if (index === -1) {
  956. this._patchMessage(m, lastTimestamp);
  957. lastTimestamp = m.timestamp;
  958. newMsgs.push(m);
  959. loadNewMsg = true;
  960. }
  961. });
  962. conversationState.currentConversationMessageList = newMsgs.concat(conversationState.currentConversationMessageList);
  963. return loadNewMsg;
  964. },
  965. loadConversationHistoryMessages(loadedCB, completeCB) {
  966. if (!conversationState.currentConversationInfo) {
  967. return;
  968. }
  969. let conversation = conversationState.currentConversationInfo.conversation;
  970. console.log('loadConversationHistoryMessage', conversation, conversationState.currentConversationOldestMessageId, stringValue(conversationState.currentConversationOldestMessageUid));
  971. let loadRemoteHistoryMessageFunc = () => {
  972. wfc.loadRemoteConversationMessages(conversation, [], conversationState.currentConversationOldestMessageUid, 20,
  973. (msgs, hasMore) => {
  974. console.log('loadRemoteConversationMessages response', msgs.length);
  975. if (msgs.length === 0) {
  976. // 拉回来的消息,本地全都有时,会走到这儿
  977. if (hasMore) {
  978. loadedCB();
  979. } else {
  980. completeCB();
  981. }
  982. } else {
  983. // 可能拉回来的时候,本地已经切换会话了
  984. if (conversation.equal(conversationState.currentConversationInfo.conversation)) {
  985. conversationState.currentConversationOldestMessageUid = msgs[0].messageUid;
  986. msgs = msgs.filter(m => m.messageId !== 0);
  987. this._onloadConversationMessages(conversation, msgs);
  988. }
  989. this._reloadConversation(conversation);
  990. loadedCB();
  991. }
  992. },
  993. (error) => {
  994. completeCB();
  995. });
  996. }
  997. wfc.getMessagesV2(conversation, conversationState.currentConversationOldestMessageId, true, 20, '', lmsgs => {
  998. if (lmsgs.length > 0) {
  999. if (!conversation.equal(conversationState.currentConversationInfo.conversation)) {
  1000. return;
  1001. }
  1002. conversationState.currentConversationOldestMessageId = lmsgs[0].messageId;
  1003. if (gt(lmsgs[0].messageUid, 0)) {
  1004. conversationState.currentConversationOldestMessageUid = lmsgs[0].messageUid;
  1005. }
  1006. let loadNewMsg = this._onloadConversationMessages(conversation, lmsgs)
  1007. if (!loadNewMsg) {
  1008. loadRemoteHistoryMessageFunc();
  1009. } else {
  1010. // loadedCB();
  1011. setTimeout(() => loadedCB(), 200)
  1012. }
  1013. } else {
  1014. loadRemoteHistoryMessageFunc();
  1015. }
  1016. }, err => {
  1017. completeCB();
  1018. });
  1019. },
  1020. setConversationTop(conversation, top) {
  1021. wfc.setConversationTop(conversation, top,
  1022. () => {
  1023. this._reloadConversation(conversation);
  1024. },
  1025. (err) => {
  1026. console.log('setConversationTop error', err)
  1027. });
  1028. },
  1029. setConversationSilent(conversation, silent) {
  1030. wfc.setConversationSlient(conversation, silent,
  1031. () => {
  1032. this._reloadConversation(conversation);
  1033. },
  1034. (err) => {
  1035. console.log('setConversationSilent error', err)
  1036. });
  1037. },
  1038. removeConversation(conversation) {
  1039. wfc.removeConversation(conversation, false);
  1040. if (conversationState.currentConversationInfo && conversationState.currentConversationInfo.conversation.equal(conversation)) {
  1041. this.setCurrentConversationInfo(null);
  1042. }
  1043. conversationState.conversationInfoList = conversationState.conversationInfoList.filter(info => !info.conversation.equal(conversation));
  1044. },
  1045. getMessageById(messageId) {
  1046. let msg = wfc.getMessageById(messageId);
  1047. if (msg) {
  1048. this._patchMessage(msg, 0);
  1049. }
  1050. return msg;
  1051. },
  1052. getMessageByUid(messageUid) {
  1053. let msg = wfc.getMessageByUid(messageUid);
  1054. if (msg) {
  1055. this._patchMessage(msg, 0);
  1056. }
  1057. return msg;
  1058. },
  1059. _patchMessage(m, lastTimestamp = 0, userInfoMap) {
  1060. // TODO
  1061. // _from
  1062. // _showTime
  1063. if (m.conversation.type === ConversationType.Single) {
  1064. m._from = userInfoMap ? userInfoMap.get(m.from) : wfc.getUserInfo(m.from, false, '');
  1065. }
  1066. if (!m._from) {
  1067. m._from = wfc.getUserInfo(m.from, false, m.conversation.type === ConversationType.Group ? m.conversation.target : '');
  1068. }
  1069. if (m.conversation.type === ConversationType.Group) {
  1070. m._from._displayName = wfc.getGroupMemberDisplayNameEx(m._from);
  1071. } else {
  1072. m._from._displayName = wfc.getUserDisplayNameEx(m._from);
  1073. }
  1074. if (numberValue(lastTimestamp) > 0 && numberValue(m.timestamp) - numberValue(lastTimestamp) > 5 * 60 * 1000) {
  1075. m._showTime = true;
  1076. }
  1077. m._timeStr = helper.timeFormat(m.timestamp)
  1078. if (m.messageContent instanceof CompositeMessageContent) {
  1079. this._patchCompositeMessageContent(m.messageContent);
  1080. }
  1081. // TODO 如果Im server支持备选网络,需要根据当前的网络情况,判断当前是处于主网络,还是备选网络,并动态修改媒体类消息的remotePath,不然可能会出现不能正常加载的情况
  1082. // 如何判断是主网络,还是备选网络,这儿提供一种思路:分别通过主网络和备选网络测试访问im server的/api/version接口
  1083. // 判断是主网络,还是备选网络,一般启动的时候,检测到网络网络变化的时候,在判断一次。
  1084. // if(m.messageContent instanceof MediaMessageContent){
  1085. // TODO 动态修改remotePath
  1086. // }
  1087. return m;
  1088. },
  1089. _patchCompositeMessageContent(compositeMessageContent) {
  1090. let messages = compositeMessageContent.messages;
  1091. messages.forEach(m => {
  1092. this._patchMessage(m, 0)
  1093. })
  1094. },
  1095. _patchConversationInfo(info, patchLastMessage = true, userInfoMap, groupInfoMap) {
  1096. if (info.conversation.type === ConversationType.Single) {
  1097. info.conversation._target = userInfoMap ? userInfoMap.get(info.conversation.target) : wfc.getUserInfo(info.conversation.target, false);
  1098. if (info.conversation._target) {
  1099. info.conversation._target._displayName = wfc.getUserDisplayNameEx(info.conversation._target);
  1100. }
  1101. } else if (info.conversation.type === ConversationType.Group) {
  1102. info.conversation._target = groupInfoMap ? groupInfoMap.get(info.conversation.target) : wfc.getGroupInfo(info.conversation.target, false);
  1103. if (info.conversation._target) {
  1104. info.conversation._target._isFav = wfc.isFavGroup(info.conversation.target);
  1105. info.conversation._target._displayName = info.conversation._target.remark ? info.conversation._target.remark : info.conversation._target.name;
  1106. }
  1107. } else if (info.conversation.type === ConversationType.Channel) {
  1108. info.conversation._target = wfc.getChannelInfo(info.conversation.target, false);
  1109. info.conversation._target._displayName = info.conversation._target.name;
  1110. } else if (info.conversation.type === ConversationType.ChatRoom) {
  1111. wfc.getChatroomInfo(info.conversation.target, 0, (chatRoomInfo) => {
  1112. info.conversation._target = chatRoomInfo;
  1113. }, err => {
  1114. console.log('get chatRoomInfo error', err);
  1115. info.conversation._target = {};
  1116. });
  1117. }
  1118. if (gt(info.timestamp, 0)) {
  1119. info._timeStr = helper.dateFormat(info.timestamp);
  1120. } else {
  1121. info._timeStr = '';
  1122. }
  1123. // 显示的时候,再 patch
  1124. if (info.lastMessage && info.lastMessage.conversation !== undefined && patchLastMessage) {
  1125. //this._patchMessage(info.lastMessage, 0, userInfoMap)
  1126. if (!info.lastMessage._from) {
  1127. info.lastMessage._from = undefined;
  1128. }
  1129. }
  1130. if (info.unreadCount) {
  1131. info._unread = info.unreadCount.unread + info.unreadCount.unreadMention + info.unreadCount.unreadMentionAll;
  1132. }
  1133. // if (info.conversation.equal(avenginekitproxy.conversation)) {
  1134. // info._isVoipOngoing = true;
  1135. // } else {
  1136. // info._isVoipOngoing = false;
  1137. // }
  1138. return info;
  1139. },
  1140. addDownloadingMessage(messageId) {
  1141. conversationState.downloadingMessages.push({
  1142. messageId: messageId,
  1143. progress: 0,
  1144. total: Number.MAX_SAFE_INTEGER,
  1145. });
  1146. console.log('add downloading')
  1147. },
  1148. isDownloadingMessage(messageId) {
  1149. return conversationState.downloadingMessages.findIndex(dm => dm.messageId === messageId) >= 0;
  1150. },
  1151. isSendingMessage(messageId) {
  1152. return conversationState.sendingMessages.has(messageId);
  1153. },
  1154. getDownloadingMessageStatus(messageId) {
  1155. return conversationState.downloadingMessages.find(dm => dm.messageId === messageId);
  1156. },
  1157. getSendingStatus(messageId) {
  1158. return conversationState.sendingMessages.find(e => e.messageId === messageId);
  1159. },
  1160. addFloatingConversation(conversation) {
  1161. conversationState.floatingConversations.push(conversation);
  1162. },
  1163. removeFloatingConversation(conversation) {
  1164. conversationState.floatingConversations = conversationState.floatingConversations.filter(c => !c.equal(conversation))
  1165. },
  1166. isConversationInCurrentWindow(conversation) {
  1167. if (miscState.isMainWindow) {
  1168. let index = conversationState.floatingConversations.findIndex(fc => fc.equal(conversation));
  1169. return index === -1;
  1170. } else {
  1171. return conversationState.currentConversationInfo && conversationState.currentConversationInfo.conversation.equal(conversation);
  1172. }
  1173. },
  1174. // contact actions
  1175. _loadSelfUserInfo() {
  1176. contactState.selfUserInfo = wfc.getUserInfo(wfc.getUserId(), false);
  1177. },
  1178. _loadFriendList() {
  1179. let friends = wfc.getMyFriendList(false);
  1180. let fileHelperIndex = friends.indexOf(Config.FILE_HELPER_ID);
  1181. if (fileHelperIndex < 0) {
  1182. friends.push(Config.FILE_HELPER_ID);
  1183. }
  1184. if (friends && friends.length > 0) {
  1185. let friendList = wfc.getUserInfos(friends, '');
  1186. contactState.friendList = this._patchAndSortUserInfos(friendList, '');
  1187. }
  1188. },
  1189. getUserOnlineState(userId) {
  1190. let userOnlineState = miscState.userOnlineStateMap.get(userId);
  1191. if (userOnlineState) {
  1192. return userOnlineState.desc();
  1193. }
  1194. return '';
  1195. },
  1196. _patchCurrentConversationOnlineStatus() {
  1197. let convInfo = conversationState.currentConversationInfo;
  1198. if (convInfo && convInfo.conversation.type === ConversationType.Single) {
  1199. // 在 将 object 和 ui 绑定之前, 向 object 中新增的属性是 reactive 的,但绑定之后,才新增的属性,不是 reactive 的,
  1200. // 故需要通过下面这种方法,让其成为 reactive 的属性
  1201. // conversationState.currentConversationInfo.conversation._targetOnlineStateDesc = userOnlineStatus.desc();
  1202. Vue.set(conversationState.currentConversationInfo.conversation, '_targetOnlineStateDesc', this.getUserOnlineState(convInfo.conversation.target))
  1203. } else {
  1204. //TODO
  1205. }
  1206. },
  1207. _loadFriendRequest() {
  1208. let requests = wfc.getIncommingFriendRequest()
  1209. requests.sort((a, b) => numberValue(b.timestamp) - numberValue(a.timestamp))
  1210. requests = requests.length >= 20 ? requests.slice(0, 20) : requests;
  1211. let uids = [];
  1212. requests.forEach(fr => {
  1213. uids.push(fr.target);
  1214. });
  1215. let userInfos = wfc.getUserInfos(uids, '')
  1216. requests.forEach(fr => {
  1217. let userInfo = userInfos.find((u => u.uid === fr.target));
  1218. fr._target = userInfo;
  1219. });
  1220. contactState.friendRequestList = requests;
  1221. contactState.unreadFriendRequestCount = wfc.getUnreadFriendRequestCount();
  1222. },
  1223. _patchAndSortUserInfos(userInfos, groupId = '', compareFn) {
  1224. userInfos = userInfos.map(u => {
  1225. if (groupId) {
  1226. u._displayName = wfc.getGroupMemberDisplayNameEx(u);
  1227. } else {
  1228. u._displayName = wfc.getUserDisplayNameEx(u);
  1229. }
  1230. u._pinyin = convert(u._displayName, {style: 0}).join('').trim().toLowerCase();
  1231. let firstLetter = u._pinyin[0];
  1232. if (firstLetter >= 'a' && firstLetter <= 'z') {
  1233. u.__sortPinyin = 'a' + u._pinyin;
  1234. } else {
  1235. u.__sortPinyin = 'z' + u._pinyin;
  1236. }
  1237. u._firstLetters = convert(u._displayName, {style: 4}).join('').trim().toLowerCase();
  1238. return u;
  1239. });
  1240. if (compareFn) {
  1241. userInfos = userInfos.sort(compareFn);
  1242. } else {
  1243. userInfos = userInfos.sort((a, b) => a.__sortPinyin.localeCompare(b.__sortPinyin));
  1244. }
  1245. userInfos.forEach(u => {
  1246. let uFirstLetter = u.__sortPinyin[1];
  1247. if (uFirstLetter >= 'a' && uFirstLetter <= 'z') {
  1248. u._category = uFirstLetter;
  1249. } else {
  1250. u._category = '#';
  1251. }
  1252. u._userOnlineStatusDesc = this.getUserOnlineState(u.uid);
  1253. });
  1254. return userInfos;
  1255. },
  1256. _loadFavGroupList() {
  1257. contactState.favGroupList = wfc.getFavGroupList();
  1258. },
  1259. _loadChannelList() {
  1260. let channelIds = wfc.getListenedChannels();
  1261. if (channelIds) {
  1262. contactState.channelList = channelIds.map(channelId => wfc.getChannelInfo(channelId, false));
  1263. contactState.channelList = contactState.channelList.filter(ch => {
  1264. return !(ch instanceof NullChannelInfo)
  1265. });
  1266. }
  1267. },
  1268. _loadFavContactList() {
  1269. let favUserIds = wfc.getFavUsers();
  1270. if (favUserIds.length > 0) {
  1271. contactState.favContactList = this.getUserInfos(favUserIds, '')
  1272. contactState.favContactList.forEach(u => {
  1273. u._category = '☆ 星标朋友';
  1274. })
  1275. } else {
  1276. contactState.favContactList = [];
  1277. }
  1278. },
  1279. reloadFavGroupList() {
  1280. this._loadFavGroupList();
  1281. },
  1282. setCurrentFriendRequest(friendRequest) {
  1283. contactState.currentFriendRequest = friendRequest;
  1284. contactState.currentFriend = null;
  1285. contactState.currentGroup = null;
  1286. },
  1287. setCurrentFriend(friend) {
  1288. contactState.currentFriendRequest = null;
  1289. contactState.currentFriend = friend;
  1290. contactState.currentGroup = null;
  1291. },
  1292. setCurrentGroup(group) {
  1293. contactState.currentFriendRequest = null;
  1294. contactState.currentFriend = null;
  1295. contactState.currentGroup = group;
  1296. },
  1297. toggleGroupList() {
  1298. contactState.expandGroup = !contactState.expandGroup;
  1299. },
  1300. toggleFriendRequestList() {
  1301. contactState.expandFriendRequestList = !contactState.expandFriendRequestList;
  1302. },
  1303. toggleFriendList() {
  1304. contactState.expandFriendList = !contactState.expandFriendList;
  1305. },
  1306. setSearchQuery(query, options) {
  1307. searchState.query = query;
  1308. if (query) {
  1309. console.log('search', query, options)
  1310. if (options.contact) {
  1311. searchState.contactSearchResult = this.filterContact(query);
  1312. }
  1313. if (options.group) {
  1314. searchState.groupSearchResult = this.filterGroupConversation(query);
  1315. }
  1316. if (options.conversation) {
  1317. searchState.conversationSearchResult = this.searchConversation(query);
  1318. }
  1319. // searchState.messageSearchResult = this.searchMessage(query);
  1320. // 默认不搜索新用户
  1321. if (options.user) {
  1322. this.searchUser(query);
  1323. }
  1324. } else {
  1325. searchState.contactSearchResult = [];
  1326. searchState.conversationSearchResult = [];
  1327. searchState.groupSearchResult = [];
  1328. searchState.messageSearchResult = [];
  1329. searchState.userSearchResult = [];
  1330. }
  1331. },
  1332. searchUser(query) {
  1333. console.log('search user', query)
  1334. wfc.searchUser(query, SearchType.General, 0, ((keyword, userInfos) => {
  1335. console.log('search user result', query, userInfos)
  1336. if (searchState.query === keyword) {
  1337. searchState.userSearchResult = userInfos.filter(u => !wfc.isMyFriend(u.uid));
  1338. }
  1339. }), (err) => {
  1340. console.log('search user error', query, err)
  1341. if (searchState.query === query) {
  1342. searchState.userSearchResult = [];
  1343. }
  1344. });
  1345. },
  1346. // TODO 到底是什么匹配了
  1347. filterContact(query) {
  1348. let result = contactState.friendList.filter(u => {
  1349. return u._displayName.indexOf(query) > -1 || u._firstLetters.indexOf(query.toLowerCase()) > -1 || u._pinyin.indexOf(query.toLowerCase()) > -1
  1350. });
  1351. console.log('friend searchResult', result)
  1352. return result;
  1353. },
  1354. searchFiles(keyword, beforeMessageUid, successCB, failCB) {
  1355. if (!keyword) {
  1356. return;
  1357. }
  1358. wfc.searchFiles(keyword, null, '', beforeMessageUid, 0, 20,
  1359. (files) => {
  1360. this._patchFileRecords(files);
  1361. successCB && successCB(files);
  1362. },
  1363. (errorCode) => {
  1364. console.log('search file error', errorCode);
  1365. failCB && failCB(errorCode);
  1366. })
  1367. },
  1368. filterUsers(users, filter) {
  1369. if (!users || !filter || !filter.trim()) {
  1370. return users;
  1371. }
  1372. let queryPinyin = convert(filter, {style: 0}).join('').trim().toLowerCase();
  1373. let result = users.filter(u => {
  1374. return u._displayName.indexOf(filter) > -1 || u._displayName.indexOf(queryPinyin) > -1
  1375. || u._pinyin.indexOf(filter) > -1 || u._pinyin.indexOf(queryPinyin) > -1
  1376. || u._firstLetters.indexOf(filter) > -1 || u._firstLetters.indexOf(queryPinyin) > -1
  1377. });
  1378. return result;
  1379. },
  1380. // TODO 匹配类型,是群名称匹配上了,还是群成员的名称匹配上了?
  1381. // 目前只搜索群名称
  1382. filterFavGroup(query) {
  1383. console.log('to search group', contactState.favGroupList)
  1384. let queryPinyin = convert(query, {style: 0}).join('').trim().toLowerCase();
  1385. let result = contactState.favGroupList.filter(g => {
  1386. let groupNamePinyin = convert(g.name, {style: 0}).join('').trim().toLowerCase();
  1387. return g.name.indexOf(query) > -1 || g.name.indexOf(queryPinyin) > -1
  1388. || groupNamePinyin.indexOf(query) > -1 || groupNamePinyin.indexOf(queryPinyin) > -1
  1389. });
  1390. console.log('group searchResult', result)
  1391. return result;
  1392. },
  1393. // TODO
  1394. filterConversation(query) {
  1395. return conversationState.conversationInfoList.filter(info => {
  1396. let displayNamePinyin = convert(info.conversation._target._displayName, {style: 0}).join('').trim().toLowerCase();
  1397. let firstLetters = convert(info.conversation._target._displayName, {style: 4}).join('').trim().toLowerCase();
  1398. return info.conversation._target._displayName.indexOf(query) > -1 || displayNamePinyin.indexOf(query.toLowerCase()) > -1 || firstLetters.indexOf(query) > -1
  1399. })
  1400. },
  1401. filterGroupConversation(query) {
  1402. // query = query.toLowerCase();
  1403. // let groups = conversationState.conversationInfoList.filter(info => info.conversation.type === ConversationType.Group).map(info => info.conversation._target);
  1404. // return groups.filter(groupInfo => {
  1405. // let namePinyin = convert(groupInfo.name, {style: 0}).join('').trim().toLowerCase();
  1406. // let firstLetters = convert(groupInfo.name, {style: 4}).join('').trim().toLowerCase();
  1407. // return groupInfo.name.indexOf(query) > -1 || namePinyin.indexOf(query) > -1 || firstLetters.indexOf(query) > -1
  1408. // })
  1409. let gsr = wfc.searchGroups(query)
  1410. return gsr.map(r => r.groupInfo);
  1411. },
  1412. searchMessage(conversation, query) {
  1413. let msgs = wfc.searchMessage(conversation, query)
  1414. msgs = msgs.reverse();
  1415. return msgs.map(m => this._patchMessage(m, 0));
  1416. },
  1417. searchMessageInTypes(conversation, contentTypes, query, offset) {
  1418. let msgs = wfc.searchMessageByTypes(conversation, query, contentTypes, true, 20, offset)
  1419. return msgs.map(m => this._patchMessage(m, 0));
  1420. },
  1421. searchConversation(query, types = [0, 1, 2], lines = [0, 1, 2]) {
  1422. let results = wfc.searchConversation(query, types, lines);
  1423. return results.map(r => {
  1424. let info = wfc.getConversationInfo(r.conversation);
  1425. r._conversationInfo = this._patchConversationInfo(info, false);
  1426. return r;
  1427. })
  1428. },
  1429. // pick actions
  1430. pickOrUnpickUser(user) {
  1431. let index = pickState.users.findIndex(u => u.uid === user.uid);
  1432. if (index >= 0) {
  1433. pickState.users = pickState.users.filter(u => user.uid !== u.uid)
  1434. } else {
  1435. pickState.users.push(user);
  1436. }
  1437. },
  1438. isUserPicked(user) {
  1439. let index = pickState.users.findIndex(u => u.uid === user.uid);
  1440. return index >= 0;
  1441. },
  1442. pickOrUnpickConversation(conversation) {
  1443. let index = pickState.conversations.findIndex(c => (conversation.target === c.target && conversation.line === c.line && conversation.type === c.type))
  1444. if (index >= 0) {
  1445. pickState.conversations = pickState.conversations.filter(c => !(conversation.target === c.target && conversation.line === c.line && conversation.type === c.type))
  1446. } else {
  1447. pickState.conversations.push(conversation);
  1448. }
  1449. },
  1450. // misc actions
  1451. createConversation(users, successCB, failCB) {
  1452. if (users.length === 1) {
  1453. let conversation = new Conversation(ConversationType.Single, users[0].uid, 0);
  1454. this.setCurrentConversation(conversation);
  1455. successCB && successCB(conversation);
  1456. return;
  1457. }
  1458. let groupName = contactState.selfUserInfo.displayName;
  1459. let groupMemberIds = [];
  1460. let groupMemberPortraits = [contactState.selfUserInfo.portrait];
  1461. for (let i = 0; i < users.length; i++) {
  1462. groupMemberIds.push(users[i].uid)
  1463. if (i <= 3) {
  1464. groupName += '、' + users[i].displayName;
  1465. }
  1466. if (i < 8) {
  1467. groupMemberPortraits.push(users[i].portrait)
  1468. }
  1469. }
  1470. groupName = groupName.substr(0, groupName.length - 1);
  1471. wfc.createGroup(null, GroupType.Restricted, groupName, null, null, groupMemberIds, null, [0], null,
  1472. (groupId) => {
  1473. let conversation = new Conversation(ConversationType.Group, groupId, 0)
  1474. this.setCurrentConversation(conversation);
  1475. successCB && successCB(conversation);
  1476. }, (error) => {
  1477. console.log('create group error', error)
  1478. failCB && failCB(error);
  1479. });
  1480. },
  1481. _loadUserLocalSettings() {
  1482. let userId = wfc.getUserId();
  1483. // 默认允许通知
  1484. let setting = getItem(userId + '-' + 'notification');
  1485. miscState.enableNotification = setting === null || setting === '1'
  1486. setting = getItem(userId + '-' + 'notificationDetail');
  1487. miscState.enableNotificationMessageDetail = setting === null || setting === '1'
  1488. },
  1489. setEnableNotification(enable) {
  1490. miscState.enableNotification = enable;
  1491. setItem(contactState.selfUserInfo.uid + '-' + 'notification', enable ? '1' : '0')
  1492. },
  1493. setEnableNotificationDetail(enable) {
  1494. miscState.enableNotificationMessageDetail = enable;
  1495. setItem(contactState.selfUserInfo.uid + '-' + 'notificationDetail', enable ? '1' : '0')
  1496. },
  1497. // clone一下,别影响到好友列表
  1498. getUserInfos(userIds, groupId) {
  1499. let userInfos = wfc.getUserInfos(userIds, groupId);
  1500. let userInfosCloneCopy = userInfos.map(u => Object.assign({}, u));
  1501. return this._patchAndSortUserInfos(userInfosCloneCopy, groupId);
  1502. },
  1503. // clone一下,别影响到好友列表
  1504. getGroupMemberUserInfos(groupId, includeSelf = true, sortByPinyin = false) {
  1505. let memberIds = wfc.getGroupMemberIds(groupId);
  1506. let userInfos = wfc.getUserInfos(memberIds, groupId);
  1507. if (!includeSelf) {
  1508. userInfos = userInfos.filter(u => u.uid !== wfc.getUserId())
  1509. }
  1510. let userInfosCloneCopy = userInfos.map(u => Object.assign({}, u));
  1511. if (sortByPinyin) {
  1512. return this._patchAndSortUserInfos(userInfosCloneCopy, groupId);
  1513. } else {
  1514. let compareFn = (u1, u2) => {
  1515. let index1 = memberIds.findIndex(id => id === u1.uid)
  1516. let index2 = memberIds.findIndex(id => id === u2.uid)
  1517. return index1 - index2;
  1518. }
  1519. return this._patchAndSortUserInfos(userInfosCloneCopy, groupId, compareFn);
  1520. }
  1521. },
  1522. // clone一下,别影响到好友列表
  1523. getConversationMemberUsrInfos(conversation) {
  1524. let userInfos = [];
  1525. if (conversation.type === 0) {
  1526. if (conversation.target !== contactState.selfUserInfo.uid) {
  1527. userInfos.push(wfc.getUserInfo(wfc.getUserId(), false));
  1528. }
  1529. userInfos.push(wfc.getUserInfo(conversation.target, false));
  1530. let userInfosCloneCopy = userInfos.map(u => Object.assign({}, u));
  1531. userInfos = this._patchAndSortUserInfos(userInfosCloneCopy, '');
  1532. } else if (conversation.type === 1) {
  1533. userInfos = this.getGroupMemberUserInfos(conversation.target, true);
  1534. }
  1535. return userInfos;
  1536. },
  1537. getMyFileRecords(beforeUid, count, successCB, failCB) {
  1538. if (!successCB) {
  1539. return;
  1540. }
  1541. wfc.getMyFileRecords(beforeUid, 0, count, fileRecords => {
  1542. this._patchFileRecords(fileRecords)
  1543. successCB(fileRecords);
  1544. }, failCB)
  1545. },
  1546. getConversationFileRecords(conversation, fromUser, beforeMessageUid, count, successCB, failCB) {
  1547. wfc.getConversationFileRecords(conversation, fromUser, beforeMessageUid, 0, count, fileRecords => {
  1548. this._patchFileRecords(fileRecords)
  1549. successCB(fileRecords);
  1550. }, failCB);
  1551. },
  1552. deleteFriend(target) {
  1553. wfc.deleteFriend(target, () => {
  1554. let conv = new Conversation(ConversationType.Single, target, 0);
  1555. wfc.removeConversation(conv, true);
  1556. conversationState.conversationInfoList = conversationState.conversationInfoList.filter(info => !info.conversation.equal(conv))
  1557. }, (err) => {
  1558. console.log('deleteFriend error', err);
  1559. });
  1560. },
  1561. _patchFileRecords(fileRecords) {
  1562. fileRecords.forEach(fileRecord => {
  1563. let groupId = fileRecord.conversation.type === 1 ? fileRecord.conversation.target : '';
  1564. if (groupId) {
  1565. fileRecord._userDisplayName = wfc.getGroupMemberDisplayName(groupId, fileRecord.userId);
  1566. } else {
  1567. fileRecord._userDisplayName = wfc.getUserDisplayName(fileRecord.userId);
  1568. }
  1569. let conversationInfo = wfc.getConversationInfo(fileRecord.conversation);
  1570. this._patchConversationInfo(conversationInfo, false);
  1571. if (fileRecord.conversation.type === 0) {
  1572. fileRecord._conversationDisplayName = '与' + conversationInfo.conversation._target._displayName + '的聊天';
  1573. } else {
  1574. fileRecord._conversationDisplayName = conversationInfo.conversation._target._displayName;
  1575. }
  1576. if (fileRecord.name.indexOf(FileMessageContent.FILE_NAME_PREFIX) === 0) {
  1577. fileRecord.name = fileRecord.name.substring(fileRecord.name.indexOf(FileMessageContent.FILE_NAME_PREFIX) + FileMessageContent.FILE_NAME_PREFIX.length);
  1578. }
  1579. fileRecord._timeStr = helper.dateFormat(fileRecord.timestamp);
  1580. fileRecord._sizeStr = helper.humanSize(fileRecord.size)
  1581. fileRecord._fileIconName = helper.getFiletypeIcon(fileRecord.name.substring(fileRecord.name.lastIndexOf('.')))
  1582. });
  1583. },
  1584. clearConversationUnreadStatus(conversation) {
  1585. let info = wfc.getConversationInfo(conversation);
  1586. if (info && (info.unreadCount.unread + info.unreadCount.unreadMention + info.unreadCount.unreadMentionAll) > 0) {
  1587. wfc.clearConversationUnreadStatus(conversation);
  1588. }
  1589. },
  1590. clearAllUnreadStatus() {
  1591. wfc.clearAllUnreadStatus();
  1592. conversationState.conversationInfoList.forEach(info => {
  1593. info.unreadCount = new UnreadCount();
  1594. });
  1595. },
  1596. notify(msg) {
  1597. let content = msg.messageContent;
  1598. let tip
  1599. //Todo
  1600. if (msg.direction === 0 /* && !(type===0 && target===file_transfer_id)*/) {
  1601. return;
  1602. }
  1603. if (MessageConfig.getMessageContentPersitFlag(content.type) === PersistFlag.Persist_And_Count) {
  1604. if (msg.status !== MessageStatus.AllMentioned && msg.status !== MessageStatus.Mentioned) {
  1605. let silent = false;
  1606. for (const info of conversationState.conversationInfoList) {
  1607. if (info.conversation.equal(msg.conversation)) {
  1608. silent = info.isSilent;
  1609. break;
  1610. }
  1611. }
  1612. if (silent) {
  1613. return;
  1614. }
  1615. tip = "新消息来了";
  1616. } else {
  1617. tip = "有人@你";
  1618. }
  1619. wfc.notify(tip, miscState.enableNotificationMessageDetail ? content.digest(msg) : '')
  1620. }
  1621. },
  1622. }
  1623. let conversationState = store.state.conversation;
  1624. let contactState = store.state.contact;
  1625. let searchState = store.state.search;
  1626. let pickState = store.state.pick;
  1627. let miscState = store.state.misc;
  1628. function _reset() {
  1629. conversationState._reset();
  1630. contactState._reset();
  1631. searchState._reset();
  1632. pickState._reset();
  1633. miscState._reset();
  1634. uni.reLaunch(
  1635. {
  1636. url: '/pages/login/LoginPage'
  1637. }
  1638. );
  1639. }
  1640. export default store