chat.js 20 KB

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