group.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. import API from '@/api'
  2. import { getWsUrl } from '@/util/contract.js'
  3. import WsManager from '@/util/wsManager.js'
  4. import Vue from 'vue'
  5. import {
  6. addSomeInArray,
  7. addTimeMsgInItem,
  8. decryptoMsg,
  9. addLinkItem,
  10. removeItemIfEixt,
  11. formatPinMsg,
  12. dealErrorMsg,
  13. checkAtMe
  14. } from '@/util/util.js'
  15. import axios from 'axios'
  16. import _ from 'lodash'
  17. var socket = null // websocket实例
  18. const group = {
  19. state: {
  20. useCache: false, // 是否使用缓存
  21. adminList: [], // 管理员列表
  22. creator: '', // 群主
  23. blockList: [], // 禁言小分队
  24. userCounts: '', // 当前房间用户数
  25. groupName: '', // 当前房间名称
  26. shareName: '', // 房间分享名称
  27. groupNotice: '', // 群公告
  28. privateName: '', // 私聊人名称
  29. coverPhoto: '', // 群头像
  30. inviteUrl: '', // 邀请链接
  31. sessionInfo: {}, // 群设置
  32. groupId: '', // 当前房间ID
  33. members: {}, // 当前房间用户列表
  34. userId: '', // 当前用户ID
  35. nickName: '',
  36. atList: [], // 被at的msgMap
  37. pinList: [], // 当前置顶列表
  38. chatList: [], // 聊天数据列表
  39. startHash: '', // 当前储存消息列表开始的hash
  40. endHash: '', // 当前储存消息列表结束的hash
  41. userInfo: {}, // 用户群角色信息
  42. unreadNums: 0, // 用户未读消息数
  43. chatInputFocus: false, // 聊天输入框聚焦
  44. pinMsg: {} // 置顶消息
  45. },
  46. mutations: {
  47. initGroup (state, data) {
  48. state.userId = data.userId
  49. state.groupId = data.groupId
  50. state.useCache = data.useCache
  51. },
  52. initState (state, data) {
  53. state.endHash = ''
  54. state.startHash = ''
  55. state.chatList = []
  56. state.pinList = []
  57. state.atList = []
  58. state.unreadNums = 0
  59. state.userId = data.user_id
  60. state.userInfo = data
  61. },
  62. setGroupInfo (state, data) {
  63. state.groupName = data.groupName
  64. state.userCounts = data.userCounts
  65. state.members = data.members
  66. state.groupNotice = data.groupNotice
  67. state.inviteUrl = data.inviteUrl
  68. state.sessionInfo = data.sessionInfo
  69. state.coverPhoto = data.coverPhoto
  70. state.adminList = data.adminList
  71. state.blockList = data.blockList
  72. state.shareName = data.shareName
  73. state.creator = data.creator
  74. if (data.pinMsg) {
  75. formatPinMsg(data.pinMsg, state.userId)
  76. state.pinList.push(data.pinMsg)
  77. removeItemIfEixt(state.pinList, state.chatList, item => item.hash)
  78. }
  79. state.pinMsg = data.pinMsg || {}
  80. },
  81. setGroupUserInfo (state, data) {
  82. state.userInfo = data
  83. state.userId = data.user_id
  84. },
  85. /**
  86. * @des 添加历史消息到当前chatList队列
  87. * @param {Object} state
  88. * @param {Array} data 待添加的消息队列
  89. */
  90. addHistoryList (state, data) {
  91. if (data.length) {
  92. addSomeInArray(data)
  93. removeItemIfEixt(state.pinList, data, item => item.hash)
  94. // 根据 hash 求data相对于chatList的差集(去重)
  95. let newList = _.differenceBy(data, state.chatList, 'hash') || []
  96. state.chatList = newList.concat(state.chatList)
  97. }
  98. },
  99. addChatItem (state, data, isFirst) {
  100. if (data && data.length > 0) {
  101. addSomeInArray(data)
  102. removeItemIfEixt(state.pinList, data, item => item.hash)
  103. isFirst && data.forEach(item => {
  104. // 检测是否被@
  105. if (checkAtMe(item.content, state.userInfo.user_name)) {
  106. state.atList.push(item)
  107. }
  108. })
  109. // 根据 hash 求data相对于chatList的差集(去重)
  110. let newList = _.differenceBy(data, state.chatList, 'hash') || []
  111. state.chatList = state.chatList.concat(newList)
  112. } else {
  113. let item = {
  114. name: state.members[data.from]
  115. ? state.members[data.from].nick_name
  116. : 'unknown',
  117. content: data.content,
  118. userId: data.from,
  119. timestamp: data.timestamp,
  120. avatar: state.members[data.from] ? state.members[data.from].cover_photo : '',
  121. hash: data.hash,
  122. type: data.from === state.userId ? 'me' : 'you',
  123. msg_type: data.msg_type,
  124. loading: Boolean(data.loading),
  125. res: data.res,
  126. fail: false
  127. }
  128. // 针对自己发送的情况
  129. if (data.createTime) {
  130. item.createTime = data.createTime
  131. }
  132. addTimeMsgInItem(item, state.chatList)
  133. addLinkItem(item)
  134. // 去重
  135. if (!state.chatList.some(n => { return n.hash === item.hash })) {
  136. state.chatList.push(item)
  137. }
  138. }
  139. },
  140. addPacketItem (state, data) {
  141. let item = {
  142. name: state.members[data.from]
  143. ? state.members[data.from].nick_name
  144. : 'unknown',
  145. timestamp: data.timestamp,
  146. avatar: state.members[data.from] ? state.members[data.from].cover_photo : '',
  147. userId: data.from,
  148. msg_type: data.type === 'new_redpack' ? 4 : 5,
  149. content: JSON.parse(decryptoMsg(data.content)),
  150. type: data.from === state.userId ? 'me' : 'you',
  151. ext: { grabbed: 0, redpack_status: 0 },
  152. hash: data.hash
  153. }
  154. addTimeMsgInItem(item, state.chatList)
  155. state.chatList.push(item)
  156. state.endHash = data.hash
  157. },
  158. addPacketTip (state, data) {
  159. let item = {
  160. content: {
  161. trxId: data.content.redpack_trx_id,
  162. title: data.content.title
  163. },
  164. ext: {
  165. grabbed: 1,
  166. redpack_status: 0
  167. },
  168. avatar: state.members[data.from] ? state.members[data.from].cover_photo : '',
  169. name: state.members[data.from]
  170. ? state.members[data.from].nick_name
  171. : 'unknown',
  172. from: data.from,
  173. to: data.to,
  174. redPackTip: true
  175. }
  176. state.chatList.push(item)
  177. },
  178. unpdatePacketItem (state, { type, trxId, data }) {
  179. let list = state.chatList
  180. let ind = list.findIndex(e => {
  181. return e.msg_type == 4 && e.content.trxId == trxId
  182. })
  183. let item = list[ind]
  184. item.ext[type] = data
  185. Vue.set(state.chatList, ind, item)
  186. },
  187. reSendChatItem (state, data) {
  188. let chatList = state.chatList
  189. chatList.forEach(item => {
  190. if (item.createTime == data.createTime) {
  191. item.loading = true
  192. item.fail = false
  193. }
  194. })
  195. },
  196. clearAtList (state) {
  197. state.atList = []
  198. },
  199. /**
  200. * 撤回消息,设置消息数据为{ repealMsg: true }
  201. * @param {state} state
  202. * @param {Object|Number} data
  203. */
  204. repealChatItem (state, data) {
  205. let { pinList, chatList } = state
  206. for (let i = chatList.length - 1; i >= 0; i--) {
  207. let item = chatList[i]
  208. if (item.hash === data.hash) {
  209. Vue.set(item, 'repealMsg', true)
  210. Vue.set(item, 'from', data.from)
  211. }
  212. }
  213. if (pinList.length) {
  214. removeItemIfEixt(pinList, [data], item => item.hash)
  215. }
  216. },
  217. deleteChatItem (state, hash) {
  218. let index = state.chatList.findIndex(item => item.hash === hash)
  219. state.chatList.splice(index, index)
  220. },
  221. addUnreadNums (state) {
  222. state.unreadNums++
  223. },
  224. resetUnreadNums (state) {
  225. state.unreadNums = 0
  226. },
  227. setHash (state, data) {
  228. if (data.startHash) {
  229. state.startHash = data.startHash
  230. }
  231. if (data.endHash) {
  232. state.endHash = data.endHash
  233. }
  234. },
  235. /**
  236. * @des 更新置顶
  237. */
  238. updatePin (state, data) {
  239. state.sessionInfo.is_pin = data
  240. },
  241. /**
  242. * @des 更新免打扰
  243. */
  244. updateMute (state, data) {
  245. state.sessionInfo.is_mute = data
  246. },
  247. /**
  248. * @des 更新群信息
  249. */
  250. updateGroup (state, { key, data }) {
  251. state[key] = data
  252. },
  253. updateMembers (state, data) {
  254. state.members = Object.assign({}, state.members, data)
  255. },
  256. /**
  257. * @des 更新members里自己的头像
  258. */
  259. updateMemberAvatar (state, { userId, imageUrl }) {
  260. let members = state.members
  261. let chatList = state.chatList
  262. for (let i = 0; i < chatList.length; i++) {
  263. let id = chatList[i]['userId']
  264. if (id === userId) {
  265. let item = chatList[i]
  266. item['avatar'] = imageUrl
  267. Vue.set(state.chatList, i, item)
  268. }
  269. }
  270. for (let k in members) {
  271. if (k === userId) {
  272. let item = members[k]
  273. item['cover_photo'] = imageUrl
  274. Vue.set(state.members, k, item)
  275. return
  276. }
  277. }
  278. },
  279. /**
  280. * @des 更新members里自己的名字
  281. */
  282. updateMemberNickName (state, { userId, nickName }) {
  283. let members = state.members
  284. let chatList = state.chatList
  285. for (let i = 0; i < chatList.length; i++) {
  286. let id = chatList[i]['userId']
  287. if (id === userId) {
  288. let item = chatList[i]
  289. item['name'] = nickName
  290. Vue.set(state.chatList, i, item)
  291. }
  292. }
  293. for (let k in members) {
  294. if (k === userId) {
  295. let item = members[k]
  296. item['nick_name'] = nickName
  297. Vue.set(state.members, k, item)
  298. return
  299. }
  300. }
  301. },
  302. /**
  303. * @des 更新聊天输入框聚焦状态
  304. */
  305. updateChatInputFocus (state, focus) {
  306. state.chatInputFocus = focus
  307. },
  308. /**
  309. * @des 更新群组封禁人员列表
  310. * @param {String} param.type [delete,add]
  311. * @param {String} param.id
  312. */
  313. updateGroupBlockList (state, param) {
  314. let { type, id } = param
  315. if (type === 'delete') {
  316. let index = state.blockList.findIndex(uid => uid == id)
  317. index !== -1 && state.blockList.splice(index, 1)
  318. } else if (type === 'add') {
  319. state.blockList.push(id)
  320. }
  321. },
  322. /**
  323. *
  324. * @param {Object|Null} param
  325. */
  326. updateGroupPinMsg (state, param) {
  327. if (param) {
  328. param.visible = true
  329. formatPinMsg(param, state.userId)
  330. state.pinMsg = param
  331. } else {
  332. state.pinMsg = {}
  333. state.pinList = []
  334. }
  335. }
  336. },
  337. actions: {
  338. /**
  339. * @des 获取群基础信息
  340. * @param {Object} store
  341. * @param {Object} params
  342. */
  343. async getGroupInfo ({ dispatch, commit, state }, params) {
  344. let info = await API.group
  345. .getGroupInfo({ group_id: state.groupId })
  346. .catch(() => {})
  347. if (info.data.code === 0) {
  348. let adminList = info.data.data.adminList
  349. let blockList = info.data.data.blockList
  350. let pinMsg = info.data.data.pinMsg
  351. let group = info.data.data.group
  352. let members = info.data.data.members
  353. let userInfo = info.data.data.userInfo
  354. let sessionInfo = info.data.data.sessionInfo
  355. pinMsg && (pinMsg.visible = true)
  356. let _members = {}
  357. members.forEach(n => {
  358. _members[n.user_id] = n
  359. })
  360. commit('setGroupInfo', {
  361. userCounts: members.length + group.increase_num,
  362. groupName: group.group_title,
  363. shareName: group.group_name,
  364. members: _members,
  365. userInfo,
  366. groupNotice: group.group_notice,
  367. inviteUrl: group.invite_url,
  368. sessionInfo,
  369. coverPhoto: group.cover_photo,
  370. adminList: adminList,
  371. blockList: blockList,
  372. pinMsg: pinMsg,
  373. creator: group.creator
  374. })
  375. }
  376. },
  377. /**
  378. * @des 群聊 获取最新消息【不需要登录】
  379. * @param {Object} store
  380. * @param {Object} params
  381. */
  382. async getNewMsg ({ dispatch, commit, state }, params = {}) {
  383. let isFirst = state.endHash == null
  384. let msg = await API.group
  385. .getNewMsg({
  386. group_id: state.groupId,
  387. client_hash: state.endHash
  388. })
  389. .catch(() => {})
  390. if (msg.data.code === 0 && msg.data.data.list.length > 0) {
  391. let list = []
  392. msg.data.data.list.forEach(n => {
  393. let member = msg.data.data.userMap[n.from]
  394. if (!member) return
  395. list.push({
  396. name: member ? member.nick_name : 'unknown',
  397. content: n.msg,
  398. userId: n.from,
  399. timestamp: n.create_time_int,
  400. avatar: member ? member.cover_photo : '',
  401. hash: n.hash,
  402. type: n.from === state.userId ? 'me' : 'you',
  403. msg_type: n.msg_type,
  404. ext: n.ext ? n.ext : null
  405. })
  406. })
  407. if (state.chatList.length) {
  408. commit('setHash', {
  409. endHash: list[list.length - 1].hash
  410. })
  411. } else {
  412. commit('setHash', {
  413. endHash: list[list.length - 1].hash,
  414. startHash: list[0].hash
  415. })
  416. }
  417. commit('addChatItem', list, isFirst)
  418. }
  419. return 'done'
  420. },
  421. /**
  422. * @des 私聊 获取最新消息【不需要登录】
  423. * @param {Object} store
  424. * @param {Object} params
  425. */
  426. async getPrivateNewMsg ({ dispatch, commit, state, rootState }, params = {}) {
  427. let msg = await API.person
  428. .getNewMsg({
  429. session_id: rootState.curSession,
  430. client_hash: state.endHash
  431. })
  432. .catch(() => {})
  433. // 有聊天记录
  434. if (msg.data.code === 0 && msg.data.data.list.length > 0) {
  435. let list = []
  436. // 更新members信息
  437. let members = msg.data.data.userMap
  438. commit('updateGroup', {
  439. key: 'members',
  440. data: members
  441. })
  442. for (let k in members) {
  443. if (k !== rootState.userId) {
  444. commit('updateGroup', {
  445. key: 'privateName',
  446. data: members[k]['nick_name']
  447. })
  448. }
  449. }
  450. msg.data.data.list.forEach(n => {
  451. let member = msg.data.data.userMap[n.from]
  452. list.push({
  453. name: member ? member.nick_name : 'unknown',
  454. content: n.msg,
  455. userId: n.from,
  456. timestamp: n.create_time_int,
  457. avatar: member.cover_photo || '',
  458. hash: n.hash,
  459. type: n.from === rootState.userId ? 'me' : 'you',
  460. msg_type: n.msg_type,
  461. ext: n.ext ? n.ext : null
  462. })
  463. })
  464. commit('setHash', {
  465. endHash: list[list.length - 1].hash,
  466. startHash: list[0].hash
  467. })
  468. commit('addChatItem', list)
  469. }
  470. return 'done'
  471. },
  472. /**
  473. * @des 群聊 获取历史消息【不需要登录】
  474. * @param {Object} store
  475. * @param {Object} params
  476. */
  477. async getHistoryMsg ({ dispatch, commit, state }, params = {}) {
  478. let his = localStorage.getItem(params.hash) // 先从本地缓存中获取记录
  479. let dList = []
  480. let status = '' // 请求状态
  481. if (his && state.useCache) {
  482. dList = JSON.parse(his)
  483. } else {
  484. // 本地缓存中没有记录,从接口获取
  485. let msg = await API.group
  486. .getHistoryMsg({
  487. group_id: state.groupId,
  488. client_hash: state.startHash
  489. })
  490. .catch(() => {})
  491. if (msg.data.code === 0 && msg.data.data.list.length > 0) {
  492. // 重新格式数据
  493. msg.data.data.list.forEach(n => {
  494. if (n.msg_type == 4) {
  495. n.msg = JSON.parse(decryptoMsg(n.msg))
  496. } else {
  497. n.msg = decryptoMsg(n.msg)
  498. }
  499. let member = msg.data.data.userMap[n.from]
  500. if (!member) return
  501. dList.push({
  502. name: member ? member.nick_name : 'unknown',
  503. content: n.msg,
  504. userId: n.from,
  505. timestamp: n.create_time_int,
  506. avatar: member ? member.cover_photo : '',
  507. hash: n.hash,
  508. type: n.from === state.userId ? 'me' : 'you',
  509. msg_type: n.msg_type,
  510. ext: n.ext ? n.ext : null
  511. })
  512. })
  513. // 保存到本地缓存中
  514. if (state.useCache) {
  515. localStorage.setItem(params.hash, JSON.stringify(dList))
  516. }
  517. }
  518. }
  519. if (dList.length > 0) {
  520. commit('setHash', {
  521. startHash: dList[0].hash
  522. })
  523. commit('addHistoryList', dList)
  524. status = 'done'
  525. } else {
  526. commit('setHash', {
  527. startHash: null
  528. })
  529. status = 'end'
  530. }
  531. return status
  532. },
  533. /**
  534. * @des 私聊 获取历史消息【不需要登录】
  535. * @param {Object} store
  536. * @param {Object} params
  537. */
  538. async getPrivateHistoryMsg (
  539. { dispatch, commit, state, rootState },
  540. params = {}
  541. ) {
  542. let his = localStorage.getItem(params.hash) // 先从本地缓存中获取记录
  543. let dList = []
  544. let status = '' // 请求状态
  545. if (his && state.useCache) {
  546. dList = JSON.parse(his)
  547. } else {
  548. // 本地缓存中没有记录,从接口获取
  549. let msg = await API.person
  550. .getHistoryMsg({
  551. session_id: rootState.curSession,
  552. client_hash: params.hash
  553. })
  554. .catch(() => {})
  555. if (msg.data.code === 0 && msg.data.data.list.length > 0) {
  556. // 重新格式数据
  557. msg.data.data.list.forEach(n => {
  558. n.msg = decryptoMsg(n.msg)
  559. let member = msg.data.data.userMap[n.from]
  560. dList.push({
  561. name: member ? member.nick_name : 'unknow',
  562. content: n.msg,
  563. userId: n.from,
  564. timestamp: n.create_time_int,
  565. avatar: member.cover_photo || '',
  566. hash: n.hash,
  567. type: n.from === rootState.userId ? 'me' : 'you',
  568. msg_type: n.msg_type,
  569. ext: n.ext ? n.ext : null
  570. })
  571. })
  572. // 保存到本地缓存中
  573. if (state.useCache) {
  574. localStorage.setItem(params.hash, JSON.stringify(dList))
  575. }
  576. }
  577. }
  578. if (dList.length > 0) {
  579. commit('setHash', {
  580. startHash: dList[0].hash
  581. })
  582. commit('addHistoryList', dList)
  583. status = 'done'
  584. } else {
  585. commit('setHash', {
  586. startHash: null
  587. })
  588. status = 'end'
  589. }
  590. return status
  591. },
  592. /**
  593. * 发送群聊消息
  594. * @param {Object} data
  595. * @param {Object} params
  596. */
  597. doSendMsg ({ dispatch, commit, state }, params = {}) {
  598. return new Promise((resolve, reject) => {
  599. API.group
  600. .sendMsg({
  601. group_id: state.groupId,
  602. msg_type: params.type,
  603. msg: params.msg
  604. })
  605. .then(({ data }) => {
  606. if (data.code === 0) {
  607. if (params.createTime) {
  608. let createTime = params.createTime
  609. data.data.content = decryptoMsg(data.data.content)
  610. let list = state.chatList
  611. for (let i = list.length - 1; i >= 0; i--) {
  612. let listItem = list[i]
  613. if (listItem.createTime === createTime) {
  614. listItem.hash = data.data.hash
  615. listItem.loading = false
  616. }
  617. }
  618. } else {
  619. // 针对用户第一次发言
  620. commit('updateMembers', data.data.userMap)
  621. data.data.content = decryptoMsg(data.data.content)
  622. commit('addChatItem', data.data)
  623. }
  624. commit('setHash', {
  625. endHash: data.data.hash
  626. })
  627. resolve(data.data)
  628. } else {
  629. if (params.createTime) {
  630. dealErrorMsg(state, params.createTime)
  631. }
  632. }
  633. })
  634. .catch(err => {
  635. if (params.createTime) {
  636. dealErrorMsg(state, params.createTime)
  637. }
  638. reject(err)
  639. })
  640. })
  641. },
  642. /**
  643. * 发送聊天文件
  644. * @param {Object} data
  645. * @param {Object} params
  646. */
  647. async doSendFile ({ dispatch, commit, state, rootState }, params = {}) {
  648. return new Promise((resolve, reject) => {
  649. let userId = rootState.userId
  650. let token = rootState.token
  651. let formData = new FormData()
  652. formData.append('group_id', state.groupId)
  653. formData.append('res', params.res)
  654. formData.append('user_id', userId)
  655. formData.append('token', token)
  656. axios({
  657. url: API.host + 'group/sendFile',
  658. method: 'post',
  659. data: formData,
  660. headers: { 'Content-Type': 'multipart/form-data' }
  661. })
  662. .then(({ data }) => {
  663. if (data.code === 0) {
  664. if (params.createTime) {
  665. let createTime = params.createTime
  666. data.data.content = decryptoMsg(data.data.content)
  667. let list = state.chatList
  668. list.forEach(item => {
  669. if (item.createTime === createTime) {
  670. item.res = undefined
  671. item.content = data.data.content
  672. item.hash = data.data.hash
  673. item.loading = false
  674. item.fail = false
  675. }
  676. })
  677. } else {
  678. // 针对用户第一次发言
  679. commit('updateMembers', data.data.userMap)
  680. data.data.content = decryptoMsg(data.data.content)
  681. commit('addChatItem', data.data)
  682. }
  683. commit('setHash', {
  684. endHash: data.data.hash
  685. })
  686. resolve(data.data)
  687. } else {
  688. if (params.createTime) {
  689. dealErrorMsg(state, params.createTime)
  690. }
  691. }
  692. })
  693. .catch(err => {
  694. if (params.createTime) {
  695. dealErrorMsg(state, params.createTime)
  696. }
  697. reject(err)
  698. })
  699. })
  700. },
  701. /**
  702. * 发送私聊消息
  703. * @param {Object} data
  704. * @param {Object} params
  705. */
  706. doSendPrivateMsg ({ dispatch, commit, rootState }, params = {}) {
  707. return new Promise((resolve, reject) => {
  708. API.person
  709. .sendMsg({
  710. session_id: rootState.curSession,
  711. msg_type: params.type,
  712. msg: params.msg
  713. })
  714. .then(({ data }) => {
  715. if (data.code === 0) {
  716. commit('addChatItem', data.data)
  717. resolve(data.data)
  718. }
  719. })
  720. .catch(err => reject(err))
  721. })
  722. },
  723. doUploadFile ({ dispatch, commit, state }, params = {}) {
  724. API.session.fileUpload({
  725. name: 'res'
  726. })
  727. },
  728. /**
  729. * 链接websocket
  730. * @param {Object} data
  731. * @param {Object} params
  732. */
  733. initSocket ({ commit, rootState, dispatch }, params = {}) {
  734. if (!window.WebSocket) {
  735. console.error('Error: WebSocket is not supported .')
  736. return
  737. }
  738. let host = `${getWsUrl()}/?user_id=${rootState.userId}&token=${
  739. rootState.token
  740. }`
  741. if (socket) {
  742. socket.destroy()
  743. socket = null
  744. }
  745. socket = new WsManager(host, {
  746. autoConnect: true, // 自动连接
  747. reconnection: true, // 断开自动重连
  748. reconnectionDelay: 5000, // 重连间隔时间,单位秒
  749. keepAliveContent: JSON.stringify({ act: 'alive', player: name }) // 心跳包内容
  750. })
  751. socket.on('open', res => {})
  752. socket.on('message', e => {
  753. let _data = JSON.parse(e)
  754. let channel = _data.channel
  755. let data = _data.data
  756. // 群聊
  757. if (channel.match('chat:group')) {
  758. if (data.type === 'msg' && data.from !== rootState.userId) {
  759. // 用户打开当前群
  760. if (rootState.curSession === data.group_id) {
  761. dispatch('getNewMsg')
  762. commit('addUnreadNums')
  763. }
  764. }
  765. if (data.type === 'leave') {
  766. }
  767. if (data.type === 'update') {
  768. }
  769. if (data.type === 'add_admin') {
  770. }
  771. if (data.type === 'remove_admin') {
  772. }
  773. if (data.type === 'repeal') {
  774. commit('repealChatItem', data)
  775. }
  776. if (data.type === 'unblock') {
  777. commit('updateGroupBlockList', {
  778. type: 'delete',
  779. id: data.to
  780. })
  781. }
  782. if (data.type === 'join') {
  783. commit('updateMembers', data.user_info)
  784. }
  785. if (data.type === 'pin_msg') {
  786. commit('updateGroupPinMsg', data.pinMsg)
  787. }
  788. if (data.type === 'unpin_msg') {
  789. commit('updateGroupPinMsg', null)
  790. }
  791. }
  792. // 私聊
  793. if (channel.match('chat:person')) {
  794. if (data.type === 'msg') {
  795. // 用户打开当前聊天
  796. if (rootState.curSession.indexOf(data.to) > -1) {
  797. // commit('addChatItem', data)
  798. dispatch('getPrivateNewMsg')
  799. commit('addUnreadNums')
  800. }
  801. }
  802. if (data.type === 'repeal') {
  803. commit('repealChatItem', data.data)
  804. }
  805. }
  806. })
  807. },
  808. /**
  809. * 撤回消息
  810. * @param {Object} params
  811. * {index:number, session_id:string, hash:string}
  812. */
  813. async doRepealGroupMsg ({ dispatch, commit, state }, params = {}) {
  814. try {
  815. await API.group.repealGroupMsg({
  816. group_id: state.groupId,
  817. hash: params.hash
  818. })
  819. } catch (error) {}
  820. },
  821. /**
  822. * 封禁群用户
  823. */
  824. async doBlockUser ({ state }, params = {}) {
  825. try {
  826. await API.group.blockUser({
  827. group_id: state.groupId,
  828. block_id: params.id
  829. })
  830. } catch (error) {}
  831. },
  832. /**
  833. * 解禁用户
  834. */
  835. async doUnBlockUser ({ state }, params = {}) {
  836. try {
  837. await API.group.unblockUser({
  838. group_id: state.groupId,
  839. block_id: params.id
  840. })
  841. } catch (error) {}
  842. },
  843. /**
  844. * 更新置顶
  845. */
  846. async doPinMsg ({ state }, params = {}) {
  847. try {
  848. await API.group.pinMsg({
  849. group_id: state.groupId,
  850. hash: params.hash
  851. })
  852. } catch (error) {}
  853. },
  854. /**
  855. * 取消置顶
  856. */
  857. async doUnpinMsg ({ state }, params = {}) {
  858. try {
  859. await API.group.unpinMsg({
  860. group_id: state.groupId,
  861. hash: params.hash
  862. })
  863. } catch (error) {}
  864. }
  865. },
  866. getters: {}
  867. }
  868. export default group