123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763 |
- import { mapActions, mapState, mapMutations } from 'vuex'
- import { scrollMsgIntoView, lazyloadImage, getMeechatType } from '@/util/util.js'
- import { emojiList } from '@/util/emoji'
- import { Message } from 'element-ui'
- import WsManager from '@/util/wsManager.js'
- import ImageMin from '@/util/imageMin.js'
- import { getMiniWsUrl } from '@/util/contract.js'
- import PostMessager from '@/util/postMessager.js'
- // 聊天mixin 用于chatRoom组件
- export const chatMixin = {
- watch: {
- '$route' () {
- this.bdHiden = true
- // 切换房间
- this.groupSet = false
- this.lockMore = false
- this.lockEnd = false
- this.enableScroll = false
- if (this.meechatType == 'mini') this.initMiniRoom()
- else this.initRoom()
- },
- chatList (val) {
- let lastVal = val[val.length - 1]
- if ((lastVal && lastVal.msg_type == 4) || this.isBottom) {
- // 自己发的红包自动滚动到底部
- this.$nextTick(this.resizeToBottom)
- }
- },
- isJoinGroup (val) {
- if (val == 1) setTimeout(this.resizeToBottom.bind(this), 100)
- }
- },
- data () {
- return {
- isLoadingRoom: true,
- groupSet: false,
- lockMore: false,
- lockEnd: false,
- enableScroll: false, // 记录滚动条是否激活的状态
- isBottom: true,
- scrollHeight: 100, // 滚动条高度
- isScrollToView: false,
- isShowGroudMgr: false, // 是否显示群管理
- chatImageArrSel: null, // 图片组
- meechatType: getMeechatType()
- }
- },
- computed: {
- ...mapState(['curSession', 'group', 'chat', 'userId', 'userInfo']),
- ...mapState({
- creator: state => state.group.creator,
- isJoin: state => state.group.isJoin,
- pinMsg: state => state.group.pinMsg,
- atList: state => state.group.atList,
- unreadNums: state => state.group.unreadNums,
- chatList: state => state.group.chatList,
- members: state => state.group.members,
- sessionId: state => state.curSession,
- sessionInfo: state => state.group.sessionInfo
- }),
- isExist () {
- // 是否存在在会话列表中
- let sessionList = this.chat.sessionList
- if (sessionList && sessionList.length) {
- return sessionList.some(e => {
- return e.session_id == this.sessionId
- })
- } else {
- return true
- }
- },
- isAdmin () {
- return (this.group.adminList && this.group.adminList.some(id => id == this.userId)) || this.group.creator == this.userId
- },
- isPrivate () {
- return this.$store.getters.isPrivate
- },
- isCreator () {
- return this.userId == this.creator
- },
- isJoinGroup () {
- if (this.group && this.group.groupId) {
- return this.isJoin ? 1 : 0
- } else {
- return 1
- }
- },
- linkToCreator () {
- let { creator, userId } = this.group
- let sessionId = creator > userId ? `${userId}-${creator}` : `${creator}-${userId}`
- return `${location.origin}/#/pm/${sessionId}`
- }
- },
- mounted () {
- if (this.meechatType == 'mini') this.initMiniRoom()
- else this.initRoom()
- document.getElementById('app').addEventListener('contextmenu', e => e.preventDefault())
- this.chatImageArrSel = this.$refs.scrollWrap.getElementsByTagName('img')
- // this.$nextTick(() => {
- // this.$refs.msgWrap.style.height = 'auto'
- // })
- },
- methods: {
- ...mapMutations([
- 'initGroup',
- 'setUserId',
- 'setToken',
- 'resetUnreadNums',
- 'addChatItem',
- 'deleteChatItem',
- 'initState',
- 'clearAtList',
- 'clearHash',
- 'setSessionItemUnread',
- 'clearChatList',
- 'changeSessionId',
- 'addPinChatItem'
- ]),
- ...mapActions([
- 'setAccount',
- 'getGroupInfo',
- 'getUserInfo',
- 'getNewMsgFromDb',
- 'getNewMsg',
- 'getHistoryMsg',
- 'doSendMsg',
- 'initPrivateMsg',
- 'getPrivateHistoryMsg',
- 'doSendPrivateMsg'
- ]),
- /**
- * 内嵌房间初始化
- */
- async initMiniRoom () {
- // 初始化postMessage消息管理器
- let callback = (event) => {
- if (event.action === 'meechat:setShow') {
- this.handleToggleChat(event.show)
- } else if (event.action === 'meechat:logout') {
- this.handleLogout2()
- }
- }
- this.postMessager = new PostMessager('*', { callback })
- window.postMessager = this.postMessager
- // 设置groupId
- this.initGroup({
- userId: this.userId,
- groupId: this.groupId,
- useCache: false
- })
- // 检查登录态
- let userId = localStorage.getItem('user_id')
- let token = localStorage.getItem('token')
- let account = localStorage.getItem('account')
- if (userId && token && account) {
- this.setUserId(userId)
- this.setToken(token)
- this.setAccount(JSON.parse(account))
- this.showLoginBtn = false
- if (self === top) {
- await this.scatterConnect()
- }
- await this.getUserInfo()
- }
- this.$nextTick(this.initChat)
- this.$nextTick(this.initMiniSocket)
- },
- async initRoom () {
- if (!this.userInfo) {
- await this.getUserInfo()
- }
- if (!this.userInfo) return
- this.changeSessionId(this.$route.params.id)
- this.clearHash()
- this.clearChatList()
- this.showLoadingRoom(true)
- if (this.isExist) {
- // 把会话列表的消息数设置为0
- this.$store.commit('setSessionItemUnread', {
- session_id: this.curSession,
- unread: 0,
- curSession: this.curSession
- })
- }
- if (this.isPrivate) await this.initPersonChat()
- else await this.initGroupChat()
- this.showLoadingRoom(false)
- },
- /**
- * @des 私聊初始化处理
- */
- async initPersonChat () {
- let data = await this.initPrivateMsg()
- this.$nextTick(() => {
- this.resizeToBottom()
- this.bdHiden = false
- })
- setTimeout(() => {
- // 不存在会话,则添加会话
- if (!this.isExist) {
- // 获取对方信息
- let otherInfo = null
- for (let key in data.data.userMap) {
- if (key != this.userId) {
- otherInfo = data.data.userMap[key]
- }
- }
- if (otherInfo) {
- let obj = {
- cover_photo: otherInfo.cover_photo,
- is_group: '0',
- name: otherInfo.nick_name,
- session_id: this.sessionId
- }
- this.$store.commit('addSessionItem', obj)
- }
- }
- }, 1000)
- return data
- },
- /**
- * @des 聊天群初始化处理
- */
- async initGroupChat () {
- this.initGroup({
- userId: this.userId,
- groupId: this.sessionId,
- useCache: false
- })
- this.isShowGroudMgr = false
- this.getGroupInfo()
- await this.getNewMsgFromDb()
- await this.getNewMsg()
- this.$nextTick(() => {
- this.resizeToBottom()
- this.bdHiden = false
- lazyloadImage({
- wrap: this.$refs.scrollWrap,
- imageArr: this.chatImageArrSel,
- derection: 'up'
- })
- })
- setTimeout(() => {
- // 不存在会话,则添加会话
- if (!this.isExist) {
- // 获取对方信息
- if (this.group) {
- let obj = {
- cover_photo: this.group.coverPhoto,
- is_group: '1',
- name: this.group.groupName,
- session_id: this.sessionId
- }
- this.$store.commit('addSessionItem', obj)
- }
- }
- }, 1000)
- },
- // Mini链接socket
- initMiniSocket () {
- if (!window.WebSocket) {
- console.log('Error: WebSocket is not supported .')
- return
- }
- let host = getMiniWsUrl() + `?group_id=${this.groupId}`
- if (this.socket) {
- this.socket.destroy()
- this.socket = null
- }
- this.socket = new WsManager(host, {
- autoConnect: true, // 自动连接
- reconnection: true, // 断开自动重连
- reconnectionDelay: 2000 // 重连间隔时间,单位秒
- })
- this.socket.on('open', res => {})
- this.socket.on('message', (data) => {
- data = JSON.parse(data)
- if (data.channel.match('chat:group')) {
- if (data.data.type === 'msg') {
- this.getNewMsg({ newMsg: true })
- if (data.data.from != this.userId) {
- // 未读消息数+1
- if (!this.showChat) {
- if (this.unreadCounts === 0) {
- this.postResize(130, 50)
- }
- this.unreadCounts++
- } else {
- this.addUnreadNums()
- }
- }
- }
- if (data.data.type === 'repeal') {
- this.repealChatItem(data.data)
- }
- if (data.data.type === 'block') {
- this.updateGroupBlockList({
- type: 'add',
- id: data.data.to
- })
- }
- if (data.data.type === 'unblock') {
- this.updateGroupBlockList({
- type: 'delete',
- id: data.data.to
- })
- }
- if (data.data.type === 'join') {
- this.updateMembers(data.data.user_info)
- }
- if (data.data.type === 'pin_msg') {
- this.updateGroupPinMsg(data.data.pinMsg)
- }
- if (data.data.type === 'unpin_msg') {
- this.updateGroupPinMsg(null)
- }
- if (data.data.type === 'new_redpack') {
- this.addPacketItem(data.data)
- if (data.data.from == this.userId) {
- this.$nextTick(this.resizeToBottom)
- }
- }
- if (data.data.type === 'grab_redpack') {
- if (data.data.from == this.userId || data.data.to == this.userId) {
- this.addPacketTip(data.data)
- }
- }
- }
- })
- },
- /**
- * @des 滚动事件监听
- */
- initScrollEvent () {},
- /**
- * @des 聊天窗体滚动事件处理集
- */
- async handleScroll (e) {
- // 防止切换房间时触发滚动处理
- if (!this.group.chatList.length) {
- return
- }
- // 防止滚动到置顶消息触发滚动
- if (this.isScrollToView) {
- return
- }
- // 激活滚动条
- this.enableScroll = true
- let totalHeight = this.$refs.msgWrap.offsetHeight - 16
- let scrollTop = e.target.scrollTop
- // 差不多滚动到顶部
- if (scrollTop === 0 && !this.lockMore) {
- if (this.group.endHash !== null) {
- this.lockMore = true
- let res
- if (this.isPrivate) {
- res = await this.getPrivateHistoryMsg()
- } else {
- res = await this.getHistoryMsg()
- }
- if (res === 'end') {
- this.lockEnd = true
- } else {
- let scrollBottom = totalHeight - scrollTop
- this.$nextTick(() => {
- e.target.scrollTop =
- this.$refs.msgWrap.offsetHeight - scrollBottom
- setTimeout(() => {
- this.lockMore = false
- }, 800)
- })
- }
- }
- }
- // 滚动到底部清空未读消息状态
- if (scrollTop + e.target.offsetHeight > totalHeight) {
- this.isBottom = true
- if (this.group.unreadNums) {
- this.resetUnreadNums()
- }
- } else {
- this.isBottom = false
- }
- lazyloadImage({
- wrap: this.$refs.scrollWrap,
- imageArr: this.chatImageArrSel,
- derection: 'up'
- })
- },
- /**
- * @des 聊天窗体滚动到底部
- */
- resizeToBottom () {
- if (!this.$refs.msgWrap) return
- this.$refs.msgWrap.style.height = 'auto'
- this.$refs.scrollWrap.scrollTop = this.$refs.msgWrap.offsetHeight
- this.resetUnreadNums()
- lazyloadImage({
- wrap: this.$refs.scrollWrap,
- imageArr: this.chatImageArrSel,
- derection: 'up'
- }, 200)
- },
- /**
- * @des 点击,查看未读消息
- * 直接滚动到聊天列表底部
- */
- doSetRead () {
- this.resizeToBottom()
- },
- /**
- * @des 引用某条消息
- */
- quoteMsg (msg) {
- this.$refs.inputArea.inputMsg = msg
- },
- /**
- * @des 某条消息被删除
- */
- deleteMsg (hash) {
- this.deleteChatItem(hash)
- },
- pinMsgClose () {
- this.pinMsg.visible = false
- },
- scrollToView () {
- if (!this.pinMsg) return
- let hash = this.pinMsg.hash
- let index = this.group.chatList.findIndex(item => item.hash === hash)
- if (index < 0) {
- this.addPinChatItem(this.pinMsg)
- index = 0
- }
- let node = this.$refs.msgWrap.getElementsByClassName('msg-item')[index]
- let toOffsetTop = index >= 0 ? node.offsetTop : node.offsetTop
- let lazy = function () {
- lazyloadImage({
- wrap: this.$refs.scrollWrap,
- imageArr: this.chatImageArrSel,
- derection: 'up'
- })
- }
- scrollMsgIntoView(
- this.$refs.scrollWrap, toOffsetTop, node, lazy.bind(this)
- )
- // 防止加载更多
- this.isScrollToView = true
- setTimeout(() => {
- this.isScrollToView = false
- }, 2000)
- },
- scrollToMsg (index) {
- let hash = this.atList[index].hash
- let eleIndex = this.group.chatList.findIndex(item => item.hash === hash)
- if (eleIndex >= 0) {
- let node = this.$refs.msgWrap.getElementsByClassName('msg-item').item(eleIndex)
- scrollMsgIntoView(
- this.$refs.scrollWrap,
- node.offsetTop - (this.pinMsg ? 40 : 10),
- node
- )
- }
- this.clearAtList()
- },
- async joinGroup () {
- this.showLoadingRoom(true)
- await this.$store.dispatch('joinGroup')
- this.showLoadingRoom(false)
- },
- // 群管理
- showGroudMgr (flag) {
- this.isShowGroudMgr = flag == 1
- },
- // 关闭表情,文件栏
- initEmojiAndTool () {
- this.emojiShow = false
- this.toolShow = false
- },
- showLoadingRoom (flag) {
- this.isLoadingRoom = flag
- }
- },
- beforeDestroy () {
- document.body.removeEventListener('click', this.initEmojiAndTool)
- }
- }
- // 聊天输入框mixin
- export const inputMixin = {
- computed: {
- ...mapState(['group', 'userId']),
- ...mapState({
- chatInputFocus: state => state.group.chatInputFocus,
- blockList: state => state.group.blockList
- }),
- isPrivate () {
- return this.$store.getters.isPrivate
- },
- emojiMap () {
- var emojiMap = {}
- for (let i in emojiList) {
- let arr = emojiList[i]
- arr.forEach(v => {
- let names = JSON.stringify(v.names)
- let emoji = v.surrogates
- emojiMap[names] = emoji
- })
- }
- return emojiMap
- }
- },
- data () {
- return {
- filePreviewShow: false, // 是否显示文件预览
- emojiShow: false, // 是否显示emoji
- fileInfo: null, // 当前上传文件
- inputMsg: '',
- atInd: 0,
- meechatType: getMeechatType()
- }
- },
- mounted () {
- },
- methods: {
- ...mapMutations(['updateChatInputFocus', 'addChatItem']),
- ...mapActions(['doSendMsg', 'doSendFile', 'doSendPrivateMsg']),
- addEmoji (val) {
- this.inputMsg += val
- this.emojiShow = false
- this.$refs.chatInput.focus()
- },
- closeFilePreview () {
- this.fileInfo = null
- this.filePreviewShow = false
- },
- showFilePreview (fileInfo) {
- if (!fileInfo) return
- this.fileInfo = fileInfo
- this.filePreviewShow = true
- },
- /**
- * @des 处理消息发送
- */
- handleInput () {
- this.inputMsg = this.inputMsg.substring(0, 5000)
- },
- /**
- * @des 处理消息发送
- */
- async handleSend (e) {
- // 判断是否被禁言
- if (this.blockList.some(id => id == this.userId)) {
- Message({
- message: '您已被禁言',
- type: 'error'
- })
- return
- }
- // 替换emoji字符串
- let _inputMsg = this.inputMsg
- let parts = _inputMsg.match(/\["[a-z0-9A-Z_]+"\]/g)
- for (let k in parts) {
- let emoji = this.emojiMap[parts[k]]
- if (emoji) {
- _inputMsg = _inputMsg.replace(parts[k], emoji)
- }
- }
- let text = _inputMsg.trim().substring(0, 5000)
- if (text.length === 0) {
- Message({
- message: '聊天内容不能为空',
- type: 'warning'
- })
- return
- }
- let opt = {
- type: 0,
- msg: text
- }
- // 用户不是第一次发言
- if (this.group.members[this.userId]) {
- let createTime = Date.now()
- this.addChatItem({
- from: this.userId,
- content: text,
- hash: `${createTime}`,
- timestamp: createTime,
- createTime,
- msg_type: '0',
- loading: true
- })
- opt.createTime = createTime
- }
- this.inputMsg = ''
- let data = this.isPrivate ? await this.doSendPrivateMsg(opt) : await this.doSendMsg(opt)
- // // 发送成功后,才加
- this.$store.commit('setSessionItemUnread', {
- session_id: this.curSession,
- unread: 0,
- curSession: this.curSession,
- cont: text,
- timestamp: data.timestamp
- })
- // 滚到底部
- this.$nextTick(function () {
- this.resizeToBottom ? this.resizeToBottom() : this.$emit('toBottom')
- lazyloadImage({
- wrap: this.$refs.scrollWrap,
- imageArr: this.chatImageArrSel,
- derection: 'up'
- })
- })
- e.preventDefault()
- return false
- },
- /**
- * 文件预处理
- * @return {Object} data 预处理文件信息
- * @param {Number} data.type
- * @param {File} data.res
- */
- async preHandleFile (file) {
- let type = file.type
- let size = file.size
- if (type.match('video')) {
- return size > 3 * 1024 * 1024
- ? Promise.reject(new Error(file))
- : Promise.resolve({
- type: 2,
- res: file
- })
- } else if (type.match('audio')) {
- return size > 2 * 1024 * 1024
- ? Promise.reject(new Error(file))
- : Promise.resolve({
- type: 3,
- res: file
- })
- } else if (type.match('image')) {
- let image = await new ImageMin({
- file: file,
- maxSize: 1024 * 1024
- })
- return {
- type: 1,
- preview: image.base64,
- res: image.res
- }
- }
- },
- /**
- * @des 处理文件发送
- */
- async handleFile (e) {
- let inputfile
- if (e.constructor === File) {
- inputfile = e
- } else {
- inputfile = e.target.files[0]
- }
- try {
- let fileInfo = await this.preHandleFile(inputfile)
- if (this.meechatType == 'pc' && fileInfo.type == 1) this.showFilePreview(fileInfo)
- else this.handleFileSend(fileInfo)
- } catch (error) {
- Message({
- message: '上传文件大小限制:音频2M以内,视频3M以内',
- type: 'warning'
- })
- }
- },
- // 发送文件消息
- handleFileSend (fileInfo) {
- this.filePreviewShow = false
- let opt = { res: fileInfo.res }
- let createTime = Date.now()
- this.addChatItem({
- content: fileInfo.preview || '',
- from: this.userId,
- hash: `${createTime}`,
- msg_type: fileInfo.type,
- timestamp: createTime,
- res: fileInfo.res,
- loading: true,
- createTime
- })
- opt.createTime = createTime
- this.doSendFile(opt)
- setTimeout(() => {
- if (this.$refs.inputFile) {
- this.$refs.inputFile.value = null
- }
- if (this.$refs.inputFile1) {
- this.$refs.inputFile1.value = null
- }
- if (this.$refs.inputFile2) {
- this.$refs.inputFile2.value = null
- }
- if (this.$refs.inputFile3) {
- this.$refs.inputFile3.value = null
- }
- this.$refs.toolbar && this.$refs.toolbar.resetInput()
- this.resizeToBottom ? this.resizeToBottom() : this.$emit('toBottom')
- }, 100)
- }
- }
- }
|