123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744 |
- import API from '@/api'
- import { getWsUrl } from '@/util/contract.js'
- import WsManager from '@/util/wsManager.js'
- import {
- decryptoMsg,
- dealErrorMsg,
- noticeManager
- } from '@/util/util.js'
- import axios from 'axios'
- import Message from '@/store/db/Message.js'
- var socket = null
- const actions = {
- /**
- * @des 获取群基础信息
- * @param {Object} store
- * @param {Object} params
- */
- async getGroupInfo ({ dispatch, commit, state }, params) {
- API.group.getGroupInfo2({ group_id: state.groupId }, info => {
- if (info.data.code === 0) {
- let adminList = info.data.data.adminList
- let blockList = info.data.data.blockList
- let pinMsg = info.data.data.pinMsg
- let group = info.data.data.group
- let members = info.data.data.members
- let membersNum = info.data.data.group.member_num
- let userInfo = info.data.data.userInfo
- let sessionInfo = info.data.data.sessionInfo
- let isJoin = !!info.data.data.sessionInfo
- let eosInfo = info.data.data.eosInfo
- pinMsg && (pinMsg.visible = true)
- let _members = {}
- members.forEach(n => {
- _members[n.user_id] = n
- })
- commit('setGroupInfo', {
- userCounts: members.length,
- groupName: group.group_title,
- shareName: group.group_name,
- members: _members,
- membersArray: members,
- membersNum: membersNum,
- userInfo,
- groupNotice: group.group_notice,
- inviteUrl: group.invite_url,
- sessionInfo,
- isJoin,
- coverPhoto: group.cover_photo,
- adminList: adminList,
- blockList: blockList,
- pinMsg: pinMsg,
- creator: group.creator,
- eosInfo: eosInfo
- })
- }
- })
- },
- /**
- * @des 群聊 获取最新消息【不需要登录】
- * @param {Object} store
- * @param {Object} params
- */
- async getNewMsg (store, params = {}) {
- // 先读取indexDB的数据,来渲染
- let { state } = store
- const objMessage = new Message()
- let data = await objMessage.getMsg(state.groupId)
- if (data.list.length > 0) {
- actions._renderGroupMsg(store, data, params)
- }
- // 然后再请求网上的数据,来渲染
- let msg = await API.group.getNewMsg({
- group_id: state.groupId,
- client_hash: state.endHash
- }).catch(() => {})
- if (msg.data.code === 0 && msg.data.data.list.length > 0) {
- actions._renderGroupMsg(store, msg.data.data, params)
- }
- return 'done'
- },
- _renderGroupMsg ({ dispatch, commit, state }, data, params) {
- let list = []
- data.list.forEach(n => {
- let member = data.userMap[n.from]
- if (!member) return
- list.push({
- name: member ? member.nick_name : 'unknown',
- content: n.msg,
- userId: n.from,
- timestamp: n.create_time_int,
- avatar: member ? member.cover_photo : '',
- hash: n.hash,
- type: n.from == state.userId ? 'me' : 'you',
- msg_type: n.msg_type,
- ext: n.ext ? n.ext : null
- })
- })
- commit('updateMembers', data.userMap)
- if (state.chatList.length) {
- commit('setHash', {
- endHash: list[list.length - 1].hash
- })
- } else {
- commit('setHash', {
- endHash: list[list.length - 1].hash,
- startHash: list[0].hash
- })
- }
- let itemData = params.newMsg ? { list: list, newMsg: params.newMsg } : list
- commit('addChatItem', itemData)
- },
- /**
- * @des 私聊 获取最新消息【不需要登录】
- * @param {Object} store
- * @param {Object} params
- */
- async getPrivateNewMsg (store, params = {}) {
- let { state, rootState } = store
- const objMessage = new Message()
- let data = await objMessage.getMsg(rootState.curSession)
- if (data.list.length > 0) {
- actions._renderPrivateMsg(store, data, params)
- }
- let msg = await API.person.getNewMsg({
- session_id: rootState.curSession,
- client_hash: state.endHash
- }).catch(() => {})
- // 有聊天记录
- if (msg.data.code === 0 && msg.data.data.list.length > 0) {
- actions._renderPrivateMsg(store, msg.data.data, params)
- }
- return 'done'
- },
- _renderPrivateMsg ({ dispatch, commit, state, rootState }, data, params) {
- let list = []
- // 更新members信息
- let members = data.userMap
- commit('updateGroup', {
- key: 'members',
- data: members
- })
- for (let k in members) {
- if (k !== rootState.userId) {
- commit('updateGroup', {
- key: 'privateName',
- data: members[k]['nick_name']
- })
- }
- }
- data.list.forEach(n => {
- let member = data.userMap[n.from]
- list.push({
- name: member ? member.nick_name : 'unknown',
- content: n.msg,
- userId: n.from,
- timestamp: n.create_time_int,
- avatar: member.cover_photo || '',
- hash: n.hash,
- type: n.from == rootState.userId ? 'me' : 'you',
- msg_type: n.msg_type,
- ext: n.ext ? n.ext : null
- })
- })
- if (state.chatList.length) {
- commit('setHash', {
- endHash: list[list.length - 1].hash
- })
- } else {
- commit('setHash', {
- endHash: list[list.length - 1].hash,
- startHash: list[0].hash
- })
- }
- let itemData = params.newMsg ? { list: list, newMsg: params.newMsg } : list
- commit('addChatItem', itemData)
- },
- /**
- * @des 群聊 获取历史消息【不需要登录】
- * @param {Object} store
- * @param {Object} params
- */
- async getHistoryMsg ({ dispatch, commit, state }, params = {}) {
- let his = localStorage.getItem(params.hash) // 先从本地缓存中获取记录
- let dList = []
- let status = '' // 请求状态
- if (his && state.useCache) {
- dList = JSON.parse(his)
- } else {
- // 本地缓存中没有记录,从接口获取
- let msg = await API.group
- .getHistoryMsg({
- group_id: state.groupId,
- client_hash: state.startHash
- })
- .catch(() => {})
- if (msg && msg.data.code === 0 && msg.data.data.list.length > 0) {
- // 重新格式数据
- msg.data.data.list.forEach(n => {
- if (n.msg_type == 4) {
- n.msg = JSON.parse(decryptoMsg(n.msg))
- } else {
- n.msg = decryptoMsg(n.msg)
- }
- let member = msg.data.data.userMap[n.from]
- commit('updateMembers', msg.data.data.userMap)
- if (!member) return
- dList.push({
- name: member ? member.nick_name : 'unknown',
- content: n.msg,
- userId: n.from,
- timestamp: n.create_time_int,
- avatar: member ? member.cover_photo : '',
- hash: n.hash,
- type: n.from == state.userId ? 'me' : 'you',
- msg_type: n.msg_type,
- ext: n.ext ? n.ext : null
- })
- })
- // 保存到本地缓存中
- if (state.useCache) {
- localStorage.setItem(params.hash, JSON.stringify(dList))
- }
- }
- }
- if (dList.length > 0) {
- commit('setHash', {
- startHash: dList[0].hash
- })
- commit('addHistoryList', dList)
- status = 'done'
- } else {
- commit('setHash', {
- startHash: null
- })
- status = 'end'
- }
- return status
- },
- /**
- * @des 私聊 获取历史消息【不需要登录】
- * @param {Object} store
- * @param {Object} params
- */
- async getPrivateHistoryMsg (
- { dispatch, commit, state, rootState },
- params = {}
- ) {
- let his = localStorage.getItem(params.hash) // 先从本地缓存中获取记录
- let dList = []
- let status = '' // 请求状态
- if (his && state.useCache) {
- dList = JSON.parse(his)
- } else {
- // 本地缓存中没有记录,从接口获取
- let msg = await API.person
- .getHistoryMsg({
- session_id: rootState.curSession,
- client_hash: state.startHash
- })
- .catch(() => {})
- if (msg.data.code === 0 && msg.data.data.list.length > 0) {
- // 重新格式数据
- msg.data.data.list.forEach(n => {
- n.msg = decryptoMsg(n.msg)
- let member = msg.data.data.userMap[n.from]
- dList.push({
- name: member ? member.nick_name : 'unknow',
- content: n.msg,
- userId: n.from,
- timestamp: n.create_time_int,
- avatar: member.cover_photo || '',
- hash: n.hash,
- type: n.from == rootState.userId ? 'me' : 'you',
- msg_type: n.msg_type,
- ext: n.ext ? n.ext : null
- })
- })
- // 保存到本地缓存中
- if (state.useCache) {
- localStorage.setItem(params.hash, JSON.stringify(dList))
- }
- }
- }
- if (dList.length > 0) {
- commit('setHash', {
- startHash: dList[0].hash
- })
- commit('addHistoryList', dList)
- status = 'done'
- } else {
- commit('setHash', {
- startHash: null
- })
- status = 'end'
- }
- return status
- },
- /**
- * 发送群聊消息
- * @param {Object} data
- * @param {Object} params
- */
- doSendMsg ({ dispatch, commit, state }, params = {}) {
- return new Promise((resolve, reject) => {
- API.group
- .sendMsg({
- group_id: state.groupId,
- msg_type: params.type,
- msg: params.msg
- })
- .then(({ data }) => {
- if (data.code === 0) {
- if (params.createTime) {
- let createTime = params.createTime
- data.data.content = decryptoMsg(data.data.content)
- let list = state.chatList
- for (let i = list.length - 1; i >= 0; i--) {
- let listItem = list[i]
- if (listItem.createTime === createTime) {
- listItem.hash = data.data.hash
- listItem.loading = false
- }
- }
- } else {
- // 针对用户第一次发言
- commit('updateMembers', data.data.userMap)
- data.data.content = decryptoMsg(data.data.content)
- commit('addChatItem', data.data)
- }
- commit('setHash', {
- endHash: data.data.hash
- })
- resolve(data.data)
- } else {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- }
- })
- .catch(err => {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- reject(err)
- })
- })
- },
- /**
- * 发送聊天文件
- * @param {Object} data
- * @param {Object} params
- */
- async doSendFile ({ dispatch, commit, state, rootState }, params = {}) {
- return new Promise((resolve, reject) => {
- let userId = rootState.userId
- let token = rootState.token
- let formData = new FormData()
- formData.append('group_id', state.groupId)
- formData.append('res', params.res)
- formData.append('user_id', userId)
- formData.append('token', token)
- axios({
- url: API.host + 'group/sendFile',
- method: 'post',
- data: formData,
- headers: { 'Content-Type': 'multipart/form-data' }
- })
- .then(({ data }) => {
- if (data.code === 0) {
- if (params.createTime) {
- let createTime = params.createTime
- data.data.content = decryptoMsg(data.data.content)
- let list = state.chatList
- list.forEach(item => {
- if (item.createTime === createTime) {
- item.res = undefined
- item.content = data.data.content
- item.hash = data.data.hash
- item.loading = false
- item.fail = false
- }
- })
- } else {
- // 针对用户第一次发言
- commit('updateMembers', data.data.userMap)
- data.data.content = decryptoMsg(data.data.content)
- commit('addChatItem', data.data)
- }
- commit('setHash', {
- endHash: data.data.hash
- })
- resolve(data.data)
- } else {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- }
- })
- .catch(err => {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- reject(err)
- })
- })
- },
- /**
- * 发送私聊消息
- * @param {Object} data
- * @param {Object} params
- */
- doSendPrivateMsg ({ dispatch, commit, state, rootState }, params = {}) {
- return new Promise((resolve, reject) => {
- API.person
- .sendMsg({
- session_id: rootState.curSession,
- msg_type: params.type,
- msg: params.msg
- })
- .then(({ data }) => {
- if (data.code === 0) {
- if (params.createTime) {
- let createTime = params.createTime
- data.data.content = decryptoMsg(data.data.content)
- let list = state.chatList
- for (let i = list.length - 1; i >= 0; i--) {
- let listItem = list[i]
- if (listItem.createTime === createTime) {
- listItem.hash = data.data.hash
- listItem.loading = false
- }
- }
- } else {
- // 针对用户第一次发言
- commit('updateMembers', data.data.userMap)
- data.data.content = decryptoMsg(data.data.content)
- commit('addChatItem', data.data)
- }
- commit('setHash', {
- endHash: data.data.hash
- })
- resolve(data.data)
- } else {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- }
- })
- .catch(err => {
- if (params.createTime) {
- dealErrorMsg(state, params.createTime)
- }
- reject(err)
- })
- })
- },
- /**
- * 链接websocket
- * @param {Object} data
- * @param {Object} params
- */
- initSocket ({ commit, state, rootState, rootGetters, dispatch }, params = {}) {
- if (!window.WebSocket) {
- console.error('Error: WebSocket is not supported .')
- return
- }
- let host = `${getWsUrl()}/?user_id=${rootState.userId}&token=${
- rootState.token
- }`
- if (socket) {
- socket.destroy()
- socket = null
- }
- socket = new WsManager(host, {
- autoConnect: true, // 自动连接
- reconnection: true, // 断开自动重连
- reconnectionDelay: 5000, // 重连间隔时间,单位秒
- keepAliveContent: JSON.stringify({ act: 'alive', player: name }) // 心跳包内容
- })
- socket.on('open', res => {})
- socket.on('message', e => {
- let _data = JSON.parse(e)
- let channel = _data.channel
- let data = _data.data
- let muteList = rootGetters.muteList // 免打扰列表
- // 群聊
- if (channel.match('chat:group')) {
- let isMute = muteList.some(v => {
- return v.session_id == data.group_id
- })
- if (data.type === 'msg' && data.from !== rootState.userId) {
- // 用户打开当前群
- if (rootState.curSession === data.group_id) {
- dispatch('getNewMsg', { newMsg: true })
- commit('addUnreadNums')
- noticeManager.changeTitle()
- } else {
- if (!isMute) {
- noticeManager.showNotification(data)
- noticeManager.changeTitle()
- }
- }
- }
- if (data.type === 'leave') {
- }
- if (data.type === 'update') {
- }
- if (data.type === 'add_admin') {
- }
- if (data.type === 'remove_admin') {
- }
- if (data.type === 'repeal') {
- commit('repealChatItem', data)
- }
- if (data.type === 'block') {
- commit('updateGroupBlockList', {
- type: 'add',
- id: data.to
- })
- }
- if (data.type === 'unblock') {
- commit('updateGroupBlockList', {
- type: 'delete',
- id: data.to
- })
- }
- if (data.type === 'join') {
- commit('updateMembers', data.user_info)
- }
- if (data.type === 'pin_msg') {
- commit('updateGroupPinMsg', data.pinMsg)
- }
- if (data.type === 'unpin_msg') {
- commit('updateGroupPinMsg', null)
- }
- if (data.type === 'new_redpack' && rootState.curSession == data.group_id) {
- commit('addPacketItem', data)
- }
- if (data.type === 'grab_redpack' && rootState.curSession == data.group_id) {
- if (data.from == rootState.userId || data.to == rootState.userId) {
- commit('addPacketTip', data)
- }
- }
- }
- // 私聊
- if (channel.match('chat:person')) {
- if (!rootState.curSession) return
- let curId = +data.to > +data.from ? `${data.from}-${data.to}` : `${data.to}-${data.from}`
- let isMute = muteList.some(v => {
- return v.session_id == curId
- })
- if (data.type === 'msg') {
- // 用户打开当前聊天
- if (rootGetters.otherUserId == data.from) {
- dispatch('getPrivateNewMsg')
- commit('addUnreadNums')
- noticeManager.changeTitle()
- } else {
- if (!isMute) {
- noticeManager.showNotification(data)
- noticeManager.changeTitle()
- }
- }
- }
- if (data.type === 'repeal') {
- commit('repealChatItem', data.data)
- }
- if (data.type === 'new_redpack' && rootGetters.otherUserId == data.from) {
- commit('addPacketItem', data)
- }
- if (data.type === 'grab_redpack' && rootGetters.otherUserId == data.from) {
- if (data.from == rootState.userId || data.to == rootState.userId) {
- commit('addPacketTip', data)
- }
- }
- }
- // 有新session 更新sessionList
- if (data.type === 'msg' || data.type === 'new_redpack') {
- let sessionList = rootState.chat.sessionList
- let curId
- let content = data.content
- if (data.group_id) {
- curId = data.group_id
- } else {
- curId = +data.to > +data.from ? `${data.from}-${data.to}` : `${data.to}-${data.from}`
- }
- let isInSession = sessionList.some(v => {
- return v.session_id == curId
- })
- if (!isInSession) {
- if (!data.group_id) {
- API.user.getOtherInfo({
- target_id: data.from
- }).then(({ data }) => {
- let obj = {
- cover_photo: data.data.cover_photo,
- is_group: '0',
- name: data.data.nick_name,
- session_id: curId,
- unread: 1,
- content: content
- }
- commit('addSessionItem', obj)
- })
- } else {
- API.group.getGroupInfo({
- group_id: data.group_id
- }).then(({ data }) => {
- let group = data.data.group
- let obj = {
- cover_photo: group.cover_photo,
- is_group: '1',
- name: group.group_name,
- session_id: curId,
- unread: 1,
- content: content
- }
- commit('addSessionItem', obj)
- })
- }
- }
- commit('setSessionItemUnread', {
- unread: 1,
- cont: decryptoMsg(content),
- session_id: curId,
- curSession: rootState.curSession
- })
- }
- })
- },
- /**
- * 撤回消息
- * @param {Object} params
- * {index:number, session_id:string, hash:string}
- */
- async doRepealGroupMsg ({ dispatch, commit, state }, params = {}) {
- try {
- await API.group.repealGroupMsg({
- group_id: state.groupId,
- hash: params.hash
- })
- } catch (error) {}
- },
- /**
- * 封禁群用户
- */
- async doBlockUser ({ state }, params = {}) {
- try {
- await API.group.blockUser({
- group_id: state.groupId,
- block_id: params.id
- })
- } catch (error) {}
- },
- /**
- * 解禁用户
- */
- async doUnBlockUser ({ state }, params = {}) {
- try {
- await API.group.unblockUser({
- group_id: state.groupId,
- block_id: params.id
- })
- } catch (error) {}
- },
- /**
- * 更新置顶
- */
- async doPinMsg ({ state }, params = {}) {
- try {
- await API.group.pinMsg({
- group_id: state.groupId,
- hash: params.hash
- })
- } catch (error) {}
- },
- /**
- * 取消置顶
- */
- async doUnpinMsg ({ state }, params = {}) {
- try {
- await API.group.unpinMsg({
- group_id: state.groupId,
- hash: params.hash
- })
- } catch (error) {}
- },
- /**
- * 加入群组
- */
- async joinGroup ({ state, commit }, params = {}) {
- try {
- await API.group.joinGroup({
- group_id: state.groupId
- })
- commit('updateJoin', true)
- } catch (error) {}
- }
- }
- export default actions
|