chat.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. import { mapActions, mapState, mapMutations } from 'vuex'
  2. import { scrollMsgIntoView, lazyloadImage, getMeechatType, getUserOpt, setUserOpt } from '@/util/util.js'
  3. import { emojiList } from '@/util/emoji'
  4. import { Message } from 'element-ui'
  5. import ImageMin from '@/util/imageMin.js'
  6. // 三端公共chat
  7. export const chatCommonMixin = {
  8. watch: {
  9. isRefreshImg (val) {
  10. if (!val) return
  11. this.$nextTick(() => {
  12. lazyloadImage({
  13. wrap: this.$refs.scrollWrap,
  14. imageArr: this.chatImageArrSel,
  15. derection: 'up'
  16. })
  17. })
  18. this.setIsRefreshImg(false)
  19. }
  20. },
  21. computed: {
  22. ...mapState({
  23. isRefreshImg: state => state.group.isRefreshImg
  24. })
  25. },
  26. methods: {
  27. ...mapMutations([
  28. 'setIsRefreshImg',
  29. 'deleteChatItem',
  30. 'removeAtListLast'
  31. ]),
  32. pinMsgClose () {
  33. this.pinMsg.visible = false
  34. },
  35. /**
  36. * @des 某条消息被删除
  37. */
  38. deleteMsg (hash) {
  39. this.deleteChatItem(hash)
  40. },
  41. scrollToMsg (index) {
  42. let hash = this.atList[index].hash
  43. let eleIndex = this.group.chatList.findIndex(item => item.hash === hash)
  44. if (eleIndex >= 0) {
  45. let node = this.$refs.msgWrap.getElementsByClassName('msg-item-common').item(eleIndex)
  46. scrollMsgIntoView(
  47. this.$refs.scrollWrap,
  48. node.offsetTop - (this.pinMsg ? 40 : 10),
  49. node
  50. )
  51. }
  52. this.removeAtListLast()
  53. },
  54. scrollToView () {
  55. if (!this.pinMsg) return
  56. let hash = this.pinMsg.hash
  57. let index = this.group.chatList.findIndex(item => item.hash === hash && item.msg_type == 0)
  58. if (index < 0) {
  59. this.addPinChatItem(this.pinMsg)
  60. index = 0
  61. }
  62. this.$nextTick(() => {
  63. let node = this.$refs.msgWrap.getElementsByClassName('msg-item-common')[index]
  64. let toOffsetTop = index >= 0 ? node.offsetTop : 0
  65. let lazy = function () {
  66. lazyloadImage({
  67. wrap: this.$refs.scrollWrap,
  68. imageArr: this.chatImageArrSel,
  69. derection: 'up'
  70. })
  71. }
  72. scrollMsgIntoView(
  73. this.$refs.scrollWrap, toOffsetTop, node, lazy.bind(this)
  74. )
  75. // 防止加载更多
  76. this.isScrollToView = true
  77. setTimeout(() => {
  78. this.isScrollToView = false
  79. }, 2000)
  80. })
  81. },
  82. async joinGroup () {
  83. this.isLoadingRoom = true
  84. await this.$store.dispatch('joinGroup')
  85. this.isLoadingRoom = false
  86. }
  87. }
  88. }
  89. // 聊天mixin 用于chatRoom组件
  90. export const chatMixin = {
  91. mixins: [chatCommonMixin],
  92. watch: {
  93. '$route' (val) {
  94. this.bdHiden = true
  95. // 切换房间
  96. this.groupSet = false
  97. this.lockMore = false
  98. this.lockEnd = false
  99. this.enableScroll = false
  100. this.initRoom()
  101. },
  102. chatList (val) {
  103. let lastVal = val[val.length - 1]
  104. if ((lastVal && lastVal.msg_type == 4) || this.isBottom) {
  105. // 自己发的红包自动滚动到底部
  106. this.$nextTick(this.resizeToBottom)
  107. }
  108. },
  109. isJoinGroup (val) {
  110. if (val == 1) setTimeout(this.resizeToBottom.bind(this), 100)
  111. }
  112. },
  113. data () {
  114. return {
  115. isLoadingRoom: true,
  116. groupSet: false,
  117. lockMore: false,
  118. lockEnd: false,
  119. enableScroll: false, // 记录滚动条是否激活的状态
  120. isBottom: true,
  121. scrollHeight: 100, // 滚动条高度
  122. isScrollToView: false,
  123. isShowGroudMgr: false, // 是否显示群管理
  124. chatImageArrSel: null, // 图片组
  125. meechatType: getMeechatType()
  126. }
  127. },
  128. computed: {
  129. ...mapState(['curSession', 'group', 'chat', 'userId', 'userInfo']),
  130. ...mapState({
  131. creator: state => state.group.creator,
  132. isJoin: state => state.group.isJoin,
  133. pinMsg: state => state.group.pinMsg,
  134. atList: state => state.group.atList,
  135. unreadNums: state => state.group.unreadNums,
  136. chatList: state => state.group.chatList,
  137. members: state => state.group.members,
  138. sessionId: state => state.curSession,
  139. sessionInfo: state => state.group.sessionInfo
  140. }),
  141. isExist () {
  142. // 是否存在在会话列表中
  143. let sessionList = this.chat.sessionList
  144. if (sessionList && sessionList.length) {
  145. return sessionList.some(e => {
  146. return e.session_id == this.sessionId
  147. })
  148. } else {
  149. return true
  150. }
  151. },
  152. isAdmin () {
  153. return (this.group.adminList && this.group.adminList.some(id => id == this.userId)) || this.group.creator == this.userId
  154. },
  155. isPrivate () {
  156. return this.$store.getters.isPrivate
  157. },
  158. isCreator () {
  159. return this.userId == this.creator
  160. },
  161. isJoinGroup () {
  162. if (this.group && this.group.groupId) {
  163. return this.isJoin ? 1 : 0
  164. } else {
  165. return 1
  166. }
  167. },
  168. linkToCreator () {
  169. let { creator, userId } = this.group
  170. let sessionId = creator > userId ? `${userId}-${creator}` : `${creator}-${userId}`
  171. return `${location.origin}/#/pm/${sessionId}`
  172. }
  173. },
  174. mounted () {
  175. this.initRoom()
  176. document.getElementById('app').addEventListener('contextmenu', e => e.preventDefault())
  177. this.chatImageArrSel = this.$refs.scrollWrap.getElementsByTagName('img')
  178. // this.$nextTick(() => {
  179. // this.$refs.msgWrap.style.height = 'auto'
  180. // })
  181. },
  182. methods: {
  183. ...mapMutations([
  184. 'initGroup',
  185. 'setUserId',
  186. 'setToken',
  187. 'resetUnreadNums',
  188. 'addChatItem',
  189. 'initState',
  190. 'clearAtList',
  191. 'clearHash',
  192. 'setSessionItemUnread',
  193. 'clearChatList',
  194. 'changeSessionId',
  195. 'addPinChatItem',
  196. 'updateMembers'
  197. ]),
  198. ...mapActions([
  199. 'setAccount',
  200. 'getGroupInfo',
  201. 'getUserInfo',
  202. 'getNewMsgFromDb',
  203. 'getNewMsg',
  204. 'getHistoryMsg',
  205. 'doSendMsg',
  206. 'getPrivateNewMsgFromDb',
  207. 'getPrivateNewMsg',
  208. 'getPrivateHistoryMsg',
  209. 'doSendPrivateMsg'
  210. ]),
  211. async initRoom () {
  212. if (!this.userInfo) {
  213. await this.getUserInfo()
  214. }
  215. if (!this.userInfo) return
  216. this.changeSessionId(this.$route.params.id)
  217. this.clearHash()
  218. this.clearChatList()
  219. this.initState()
  220. if (this.isExist) {
  221. // 把会话列表的消息数设置为0
  222. this.$store.commit('setSessionItemUnread', {
  223. session_id: this.curSession,
  224. unread: 0,
  225. curSession: this.curSession
  226. })
  227. }
  228. if (this.isPrivate) await this.initPersonChat()
  229. else await this.initGroupChat()
  230. },
  231. /**
  232. * @des 私聊初始化处理
  233. */
  234. async initPersonChat () {
  235. let flag = await this.getPrivateNewMsgFromDb()
  236. if (!flag) {
  237. // 如果indexDB没数据时,才需要loading
  238. this.showLoadingRoom(true)
  239. }
  240. let data = await this.getPrivateNewMsg()
  241. this.showLoadingRoom(false)
  242. this.$nextTick(() => {
  243. this.resizeToBottom()
  244. this.bdHiden = false
  245. })
  246. // 没消息时member添加成员
  247. if (!this.members[this.userId]) {
  248. this.updateMembers({ [this.userId]: this.userInfo })
  249. }
  250. // 房间名
  251. let userIds = this.curSession.split('-')
  252. let otherId = userIds[0] != this.userId ? userIds[0] : userIds[1]
  253. let otherInfo = data.data.userMap[otherId]
  254. if (otherInfo) {
  255. this.$store.commit('updateGroup', {
  256. key: 'privateName',
  257. data: otherInfo.nick_name
  258. })
  259. // 不存在会话,则添加会话
  260. if (!this.isExist) {
  261. let obj = {
  262. cover_photo: otherInfo.cover_photo,
  263. is_group: '0',
  264. name: otherInfo.nick_name,
  265. session_id: this.sessionId
  266. }
  267. this.$store.commit('addSessionItem', obj)
  268. }
  269. }
  270. return data
  271. },
  272. /**
  273. * @des 聊天群初始化处理
  274. */
  275. async initGroupChat () {
  276. this.initGroup({
  277. userId: this.userId,
  278. groupId: this.sessionId,
  279. useCache: false
  280. })
  281. this.isShowGroudMgr = false
  282. this.getGroupInfo()
  283. let flag = await this.getNewMsgFromDb()
  284. // 如果indexDB没数据时,才需要loading
  285. if (!flag) this.showLoadingRoom(true)
  286. await this.getNewMsg()
  287. this.showLoadingRoom(false)
  288. this.$nextTick(() => {
  289. this.resizeToBottom()
  290. this.bdHiden = false
  291. lazyloadImage({
  292. wrap: this.$refs.scrollWrap,
  293. imageArr: this.chatImageArrSel,
  294. derection: 'up'
  295. })
  296. })
  297. setTimeout(() => {
  298. // 不存在会话,则添加会话
  299. if (!this.isExist) {
  300. // 获取对方信息
  301. if (this.group) {
  302. let obj = {
  303. cover_photo: this.group.coverPhoto,
  304. is_group: '1',
  305. name: this.group.groupName,
  306. session_id: this.sessionId
  307. }
  308. this.$store.commit('addSessionItem', obj)
  309. }
  310. }
  311. }, 1000)
  312. },
  313. /**
  314. * @des 滚动事件监听
  315. */
  316. initScrollEvent () {},
  317. /**
  318. * @des 聊天窗体滚动事件处理集
  319. */
  320. async handleScroll (e) {
  321. // 防止切换房间时触发滚动处理
  322. if (!this.group.chatList.length) {
  323. return
  324. }
  325. // 防止滚动到置顶消息触发滚动
  326. // if (this.isScrollToView) {
  327. // return
  328. // }
  329. // 激活滚动条
  330. this.enableScroll = true
  331. let totalHeight = this.$refs.msgWrap.offsetHeight - 16
  332. let scrollTop = e.target.scrollTop
  333. // 差不多滚动到顶部
  334. if (scrollTop == 0 && !this.lockMore) {
  335. if (this.group.endHash !== null) {
  336. this.lockMore = true
  337. let res
  338. if (this.isPrivate) {
  339. res = await this.getPrivateHistoryMsg()
  340. } else {
  341. res = await this.getHistoryMsg()
  342. }
  343. if (res === 'end') {
  344. this.lockEnd = true
  345. } else {
  346. let scrollBottom = totalHeight - scrollTop
  347. this.$nextTick(() => {
  348. e.target.scrollTop =
  349. this.$refs.msgWrap.offsetHeight - scrollBottom
  350. setTimeout(() => {
  351. this.lockMore = false
  352. }, 800)
  353. })
  354. }
  355. }
  356. }
  357. // 滚动到底部清空未读消息状态
  358. if (scrollTop + e.target.offsetHeight > totalHeight) {
  359. this.isBottom = true
  360. if (this.group.unreadNums) {
  361. this.resetUnreadNums()
  362. }
  363. } else {
  364. this.isBottom = false
  365. }
  366. lazyloadImage({
  367. wrap: this.$refs.scrollWrap,
  368. imageArr: this.chatImageArrSel,
  369. derection: 'up'
  370. })
  371. },
  372. /**
  373. * @des 聊天窗体滚动到底部
  374. */
  375. resizeToBottom () {
  376. if (!this.$refs.msgWrap) return
  377. this.$refs.msgWrap.style.height = 'auto'
  378. this.$refs.scrollWrap.scrollTop = this.$refs.msgWrap.offsetHeight
  379. this.resetUnreadNums()
  380. lazyloadImage({
  381. wrap: this.$refs.scrollWrap,
  382. imageArr: this.chatImageArrSel,
  383. derection: 'up'
  384. }, 200)
  385. },
  386. /**
  387. * @des 点击,查看未读消息
  388. * 直接滚动到聊天列表底部
  389. */
  390. doSetRead () {
  391. this.resizeToBottom()
  392. },
  393. /**
  394. * @des 引用某条消息
  395. */
  396. quoteMsg (msg) {
  397. this.$refs.inputArea.inputMsg = msg
  398. },
  399. // 群管理
  400. showGroudMgr (flag) {
  401. this.isShowGroudMgr = flag == 1
  402. },
  403. // 关闭表情,文件栏
  404. initEmojiAndTool () {
  405. this.emojiShow = false
  406. this.toolShow = false
  407. },
  408. showLoadingRoom (flag) {
  409. this.isLoadingRoom = flag
  410. }
  411. },
  412. beforeDestroy () {
  413. document.body.removeEventListener('click', this.initEmojiAndTool)
  414. }
  415. }
  416. // 聊天输入框mixin
  417. export const inputMixin = {
  418. computed: {
  419. ...mapState(['group', 'userId']),
  420. ...mapState({
  421. chatInputFocus: state => state.group.chatInputFocus,
  422. blockList: state => state.group.blockList
  423. }),
  424. isPrivate () {
  425. return this.$store.getters.isPrivate
  426. },
  427. emojiMap () {
  428. var emojiMap = {}
  429. for (let i in emojiList) {
  430. let arr = emojiList[i]
  431. arr.forEach(v => {
  432. let names = JSON.stringify(v.names)
  433. let emoji = v.surrogates
  434. emojiMap[names] = emoji
  435. })
  436. }
  437. return emojiMap
  438. }
  439. },
  440. data () {
  441. return {
  442. filePreviewShow: false, // 是否显示文件预览
  443. emojiShow: false, // 是否显示emoji
  444. fileInfo: null, // 当前上传文件
  445. inputMsg: '',
  446. atInd: 0,
  447. meechatType: getMeechatType()
  448. }
  449. },
  450. mounted () {
  451. },
  452. methods: {
  453. ...mapMutations(['updateChatInputFocus', 'addChatItem']),
  454. ...mapActions(['doSendMsg', 'doSendFile', 'doSendPrivateMsg']),
  455. addEmoji (val) {
  456. this.inputMsg += val
  457. this.emojiShow = false
  458. this.$refs.chatInput.focus()
  459. },
  460. closeFilePreview () {
  461. this.fileInfo = null
  462. this.filePreviewShow = false
  463. this.emptyFileForm()
  464. },
  465. showFilePreview (fileInfo) {
  466. if (!fileInfo) return
  467. this.fileInfo = fileInfo
  468. this.filePreviewShow = true
  469. },
  470. /**
  471. * @des 处理消息发送
  472. */
  473. handleInput () {
  474. this.inputMsg = this.inputMsg.substring(0, 5000)
  475. },
  476. /**
  477. * @des 处理消息发送
  478. */
  479. async handleSend (e) {
  480. // 判断是否被禁言
  481. if (this.blockList.some(id => id == this.userId)) {
  482. Message({
  483. message: '您已被禁言',
  484. type: 'error'
  485. })
  486. return
  487. }
  488. // 替换emoji字符串
  489. let _inputMsg = this.inputMsg
  490. let parts = _inputMsg.match(/\["[a-z0-9A-Z_]+"\]/g)
  491. for (let k in parts) {
  492. let emoji = this.emojiMap[parts[k]]
  493. if (emoji) {
  494. _inputMsg = _inputMsg.replace(parts[k], emoji)
  495. }
  496. }
  497. let text = _inputMsg.trim().substring(0, 5000)
  498. if (text.length === 0) {
  499. Message({
  500. message: '聊天内容不能为空',
  501. type: 'warning'
  502. })
  503. return
  504. }
  505. let opt = {
  506. type: 0,
  507. msg: text
  508. }
  509. // 用户不是第一次发言
  510. if (this.group.members[this.userId]) {
  511. let createTime = Date.now()
  512. let lastShowMsgUid = getUserOpt('lastShowMsgUid') || 0
  513. this.addChatItem({
  514. from: this.userId,
  515. content: text,
  516. hash: `${createTime}`,
  517. timestamp: createTime,
  518. createTime,
  519. msg_type: '0',
  520. loading: true,
  521. isShowFullInfo: this.userId != lastShowMsgUid
  522. })
  523. if (this.userId != lastShowMsgUid)lastShowMsgUid = this.userId
  524. setUserOpt('lastShowMsgUid', lastShowMsgUid)
  525. opt.createTime = createTime
  526. }
  527. this.inputMsg = ''
  528. let data = this.isPrivate ? await this.doSendPrivateMsg(opt) : await this.doSendMsg(opt)
  529. // // 发送成功后,才加
  530. this.$store.commit('setSessionItemUnread', {
  531. session_id: this.curSession,
  532. unread: 0,
  533. curSession: this.curSession,
  534. cont: text,
  535. timestamp: data.timestamp
  536. })
  537. // 滚到底部
  538. this.$nextTick(function () {
  539. this.resizeToBottom ? this.resizeToBottom() : this.$emit('toBottom')
  540. lazyloadImage({
  541. wrap: this.$refs.scrollWrap,
  542. imageArr: this.chatImageArrSel,
  543. derection: 'up'
  544. })
  545. })
  546. e.preventDefault()
  547. return false
  548. },
  549. /**
  550. * 文件预处理
  551. * @return {Object} data 预处理文件信息
  552. * @param {Number} data.type
  553. * @param {File} data.res
  554. */
  555. async preHandleFile (file) {
  556. let type = file.type
  557. let size = file.size
  558. if (type.match('video')) {
  559. return size > 3 * 1024 * 1024
  560. ? Promise.reject(new Error(file))
  561. : Promise.resolve({
  562. type: 2,
  563. res: file,
  564. preview: window.webkitURL.createObjectURL(file)
  565. })
  566. } else if (type.match('audio')) {
  567. return size > 2 * 1024 * 1024
  568. ? Promise.reject(new Error(file))
  569. : Promise.resolve({
  570. type: 3,
  571. res: file,
  572. preview: window.webkitURL.createObjectURL(file)
  573. })
  574. } else if (type.match('image')) {
  575. let image = await new ImageMin({
  576. file: file,
  577. maxSize: 1024 * 1024
  578. })
  579. return {
  580. type: 1,
  581. preview: image.base64,
  582. res: image.res
  583. }
  584. }
  585. },
  586. /**
  587. * @des 处理文件发送
  588. */
  589. async handleFile (e) {
  590. let inputfile
  591. if (e.constructor === File) {
  592. inputfile = e
  593. } else {
  594. inputfile = e.target.files[0]
  595. }
  596. try {
  597. let fileInfo = await this.preHandleFile(inputfile)
  598. if (this.meechatType == 'pc') this.showFilePreview(fileInfo)
  599. else this.handleFileSend(fileInfo)
  600. } catch (error) {
  601. Message({
  602. message: '上传文件大小限制:音频2M以内,视频3M以内',
  603. type: 'warning'
  604. })
  605. }
  606. },
  607. // 发送文件消息
  608. async handleFileSend (fileInfo) {
  609. this.filePreviewShow = false
  610. let opt = { res: fileInfo.res }
  611. let createTime = Date.now()
  612. this.addChatItem({
  613. content: fileInfo.preview || '',
  614. from: this.userId,
  615. hash: `${createTime}`,
  616. msg_type: fileInfo.type,
  617. timestamp: createTime,
  618. res: fileInfo.res,
  619. loading: true,
  620. createTime
  621. })
  622. opt.createTime = createTime
  623. await this.doSendFile(opt)
  624. setTimeout(() => {
  625. this.emptyFileForm()
  626. this.$refs.toolbar && this.$refs.toolbar.resetInput()
  627. this.resizeToBottom ? this.resizeToBottom() : this.$emit('toBottom')
  628. }, 100)
  629. },
  630. // 初始文件表单
  631. emptyFileForm () {
  632. if (this.$refs.inputFile) {
  633. this.$refs.inputFile.value = null
  634. }
  635. if (this.$refs.inputFile1) {
  636. this.$refs.inputFile1.value = null
  637. }
  638. if (this.$refs.inputFile2) {
  639. this.$refs.inputFile2.value = null
  640. }
  641. if (this.$refs.inputFile3) {
  642. this.$refs.inputFile3.value = null
  643. }
  644. }
  645. }
  646. }