util.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import { MessageBox } from 'element-ui'
  2. import TWEEN from '@tweenjs/tween.js'
  3. import twemoji from 'twemoji'
  4. import dayjs from 'dayjs'
  5. const timestampInterval = 1e3 * 60 * 3 // 3分钟的间隔时间
  6. const cryptoKey = 'dqWt6twz6JyEy3EZ'
  7. // 错误弹窗
  8. export function showError (msg, title = 'Error') {
  9. MessageBox.confirm(msg, title, {
  10. center: true,
  11. showCancelButton: false,
  12. showConfirmButton: false,
  13. callback () {}
  14. })
  15. }
  16. // 确认操作弹窗
  17. export function confirmPopup (msg, title = '提示') {
  18. return new Promise((resolve, reject) => {
  19. MessageBox.confirm(msg, '提示', {
  20. confirmButtonText: '确定',
  21. cancelButtonText: '取消',
  22. type: 'warning'
  23. })
  24. .then(() => {
  25. resolve()
  26. })
  27. .catch(() => {})
  28. })
  29. }
  30. /**
  31. * 判断系统||浏览器中英文
  32. * 对于不支持的浏览器 一律默认为 中文
  33. */
  34. export function getLanguage () {
  35. var language = (navigator.language || navigator.browserLanguage).toLowerCase()
  36. var locale = 'zh'
  37. if (language.indexOf('en') > -1) {
  38. locale = 'en'
  39. } else {
  40. locale = 'zh'
  41. }
  42. return locale
  43. }
  44. /**
  45. * 获取Url上指定参数
  46. * @param {String} name 参数名
  47. */
  48. export function getUrlParam (name) {
  49. var reg = new RegExp('[?&]' + name + '=([^&#?]*)(&|#|$)')
  50. var r = window.location.href.match(reg)
  51. return r ? r[1] : null
  52. }
  53. export var Cookie = {
  54. setCookie (name, value) {
  55. var Days = 7
  56. var exp = new Date()
  57. exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
  58. exp.setTime(exp.getTime() + 60 * 1000)
  59. if (
  60. window.location.port === '8080' ||
  61. /^test-|\.webdev2\./.test(window.location.host)
  62. ) {
  63. document.cookie =
  64. name + '=' + escape(value) + ';expires=' + exp.toGMTString()
  65. } else {
  66. document.cookie =
  67. name +
  68. '=' +
  69. escape(value) +
  70. ';domain=.mee.chat;path=/;expires=' +
  71. exp.toGMTString()
  72. }
  73. },
  74. getCookie (name) {
  75. var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  76. var arr = document.cookie.match(reg)
  77. if (arr) {
  78. return unescape(arr[2])
  79. } else {
  80. return null
  81. }
  82. },
  83. delCookie (name) {
  84. var str1 = name + '=;domain=.mee.chat;path=/'
  85. str1 += ';expires=' + new Date(0).toGMTString()
  86. document.cookie = str1
  87. var str2 = name + '=;path=/'
  88. str2 += ';expires=' + new Date(0).toGMTString()
  89. document.cookie = str2
  90. }
  91. }
  92. /**
  93. * 获取聊天区域高度
  94. * @param {String} msg
  95. */
  96. export function getResizeHeight () {
  97. let clientHeight = document.documentElement.clientHeight
  98. let clientWidth = document.documentElement.clientWidth
  99. let topHeight = 61
  100. let botHeight = 181
  101. var chatBoxHeight
  102. if (clientHeight < 600) {
  103. chatBoxHeight = 600 - topHeight - botHeight
  104. }
  105. if (clientHeight < 800 || clientWidth < 1000) {
  106. chatBoxHeight = clientHeight - topHeight - botHeight
  107. } else {
  108. chatBoxHeight = clientHeight * 0.8 - topHeight - botHeight
  109. }
  110. return chatBoxHeight
  111. }
  112. function rc4 (str, key) {
  113. var s = []
  114. var j = 0
  115. var x
  116. var res = ''
  117. for (var i = 0; i < 256; i++) {
  118. s[i] = i
  119. }
  120. for (i = 0; i < 256; i++) {
  121. j = (j + s[i] + key.charCodeAt(i % key.length)) % 256
  122. x = s[i]
  123. s[i] = s[j]
  124. s[j] = x
  125. }
  126. i = 0
  127. j = 0
  128. for (var y = 0; y < str.length; y++) {
  129. i = (i + 1) % 256
  130. j = (j + s[i]) % 256
  131. x = s[i]
  132. s[i] = s[j]
  133. s[j] = x
  134. res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256])
  135. }
  136. return res
  137. }
  138. /**
  139. * 加密信息
  140. * @param {String} msg
  141. */
  142. export function cryptoMsg (msg) {
  143. let result
  144. try {
  145. result = btoa(rc4(encodeURIComponent(msg), cryptoKey))
  146. } catch {
  147. return msg
  148. }
  149. return result
  150. }
  151. /**
  152. * 解密信息
  153. * @param {String} msg
  154. */
  155. export function decryptoMsg (msg) {
  156. let result
  157. try {
  158. result = decodeURIComponent(rc4(atob(msg), cryptoKey))
  159. } catch {
  160. return msg
  161. }
  162. return result
  163. }
  164. const linkRule = new RegExp(
  165. '(https?|ftp|file)://[-a-zA-Z0-9/-_.?#!+%]+'
  166. )
  167. /**
  168. * 向数组添加数据
  169. * @param {Array} data
  170. */
  171. export function addSomeInArray (data) {
  172. let lastTime = null
  173. data.forEach(item => {
  174. // 添加timeMsg tag
  175. if (lastTime === null) {
  176. item.timeMsg = false
  177. } else {
  178. item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
  179. }
  180. lastTime = parseInt(item.timestamp)
  181. addLinkItem(item)
  182. })
  183. }
  184. /**
  185. * 单个添加timeMsg tag
  186. * @param {Array} data
  187. */
  188. export function addTimeMsgInItem (item, arr) {
  189. if (arr.length === 0) {
  190. item.timeMsg = true
  191. } else {
  192. let lastTime = parseInt(arr[arr.length - 1].timestamp)
  193. item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
  194. }
  195. }
  196. /**
  197. * 判断是否是移动端
  198. */
  199. export function isMobile () {
  200. return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)
  201. }
  202. function convertEntity (str) {
  203. // &colon;&rpar;
  204. const entityMap = {
  205. '&': '&amp;',
  206. '<': '&lt;',
  207. '>': '&gt;',
  208. '"': '&quot;',
  209. "'": '&apos;'
  210. }
  211. return str.replace(/[&<>'"]/g, function (matched) {
  212. return entityMap[matched]
  213. })
  214. }
  215. /*
  216. * 单个添加链接 msg_type = 10
  217. * @param {Array} data
  218. */
  219. export function addLinkItem (item) {
  220. // 先用实体处理
  221. if (item.msg_type == 0) {
  222. item.content = convertEntity(item.content)
  223. if (item.content.match(linkRule)) {
  224. item.content = item.content.replace(linkRule, a => {
  225. return `<a href="${a}" class="link text" target="_blank">${a}</a>`
  226. })
  227. }
  228. item.content = twemoji.parse(item.content, {
  229. callback: function (icon, options) {
  230. return 'https://w2.meechat.me/emoji/' + icon + '.svg'
  231. }
  232. })
  233. }
  234. }
  235. /**
  236. * 移除arr2中满足callback的arr1数组元素
  237. * @param {Array} arr1 [{hash:1}]
  238. * @param {Array} arr2 [{hash:1},{hash:2}]
  239. * @result arr1 => []
  240. */
  241. export function removeItemIfEixt (arr1, arr2, callback) {
  242. arr1.forEach((item, index) => {
  243. if (arr2.some(item2 => callback(item2) == callback(item))) {
  244. arr1.splice(index, 1)
  245. }
  246. })
  247. }
  248. /**
  249. * 格式化置顶消息
  250. */
  251. export function formatPinMsg (pinMsg, userId) {
  252. pinMsg.name = pinMsg.nick_name
  253. pinMsg.content = decryptoMsg(pinMsg.msg)
  254. pinMsg.type = pinMsg.from == userId ? 'me' : 'you'
  255. pinMsg.avatar = pinMsg.cover_photo || ''
  256. pinMsg.userId = userId
  257. }
  258. /**
  259. * 格式化最后的消息
  260. * @param lastMsg
  261. * @param isGroup
  262. * @returns {*}
  263. */
  264. export function formatLastMsg (lastMsg, isGroup) {
  265. let cont = null
  266. if (lastMsg) {
  267. if (lastMsg.msg_type == 0 && lastMsg['content']) {
  268. cont = decryptoMsg(lastMsg['content'])
  269. } else if (lastMsg.msg_type == 1) {
  270. cont = '[图片]'
  271. } else if (lastMsg.msg_type == 2) {
  272. cont = '[视频]'
  273. } else if (lastMsg.msg_type == 3) {
  274. cont = '[音频]'
  275. } else if (lastMsg.msg_type == 4) {
  276. cont = '[红包]'
  277. }
  278. if (isGroup) {
  279. cont = lastMsg.nick_name + ': ' + cont
  280. }
  281. }
  282. return cont
  283. }
  284. /**
  285. * @param {store} state
  286. * @param {Number} createTime
  287. */
  288. export function dealErrorMsg (state, createTime) {
  289. state.chatList.forEach(item => {
  290. if (item.createTime == createTime) {
  291. item.fail = true
  292. item.loading = false
  293. }
  294. })
  295. }
  296. /**
  297. * 如果含有at他人的信息,格式化
  298. * @param {String} msg @heitan@aben 123
  299. * @param {Array} members
  300. * @result => {@start[10,9]end}@heitan@aben 123
  301. */
  302. export function encryptAtMsg (msg, members) {
  303. let ats = []
  304. members.forEach(user => {
  305. let reg = new RegExp(`@${user.nick_name}`)
  306. if (reg.test(msg)) {
  307. ats.push(user.user_id)
  308. }
  309. })
  310. if (ats.length) {
  311. msg = `{@start[${ats.toString()}]end}${msg}`
  312. }
  313. return msg
  314. }
  315. /**
  316. *
  317. * @param {String} msg
  318. * @return {Array|Null}
  319. */
  320. export function decryptAtMsg (msg) {
  321. let reg = /^{@start\[(.*)\]end}/
  322. let ret = reg.exec(msg)
  323. if (ret) {
  324. return ret[0].split(',')
  325. }
  326. }
  327. /**
  328. *判断是否是at我的信息
  329. */
  330. export function checkAtMe (msg, username) {
  331. if (!username) return false
  332. let reg = new RegExp(`@${username}`)
  333. return reg.test(msg)
  334. }
  335. export function scrollIntoView (node, offsetTop) {
  336. let distance = Math.abs(offsetTop - node.scrollTop)
  337. let time = distance > 500 ? 1000 : distance * 2
  338. let tw = new TWEEN.Tween(node)
  339. .to({ scrollTop: offsetTop }, time)
  340. .easing(TWEEN.Easing.Quadratic.Out)
  341. return tw.start()
  342. }
  343. export function scrollMsgIntoView (node, offsetTop, targetNode) {
  344. scrollIntoView(node, offsetTop)
  345. .onComplete(() => {
  346. targetNode.classList.toggle('active')
  347. })
  348. setTimeout(() => {
  349. targetNode.classList.toggle('active')
  350. }, 3000)
  351. }
  352. export var noticeManager = {
  353. tabTimer: null, // tab切换定时器
  354. askPermission () {
  355. return new Promise((resolve, reject) => {
  356. if (!('Notification' in window)) {
  357. reject(new Error('This browser does not support desktop notification'))
  358. } else if (Notification.permission === 'granted') {
  359. resolve()
  360. } else if (Notification.permission === 'default ') {
  361. Notification.requestPermission(function (permission) {
  362. // 如果用户同意,就可以向他们发送通知
  363. if (permission === 'granted') {
  364. resolve()
  365. } else {
  366. reject(new Error())
  367. }
  368. })
  369. }
  370. })
  371. },
  372. showNotification (data) {
  373. // 开启全局消息免扰
  374. if (this.getGlobalNotice() == 1) return
  375. // 已经打开页面了,就不需要额外通知
  376. if (!document.hidden) return
  377. this.askPermission().then(() => {
  378. let notification = new Notification(data.name, {
  379. body: '你收到了一条消息',
  380. icon: `/dist/icons/meechat.png`
  381. })
  382. // 打开页面
  383. let path
  384. if (data.group_id) {
  385. path = `/group/${data.group_id}`
  386. } else {
  387. let sessionId = +data.to > +data.from ? `${data.from}-${data.to}` : `${data.to}-${data.from}`
  388. path = `/pm/${sessionId}`
  389. }
  390. notification.onclick = () => {
  391. window.$router.push({ path })
  392. notification.close()
  393. window.focus()
  394. }
  395. setTimeout(() => {
  396. notification.close()
  397. }, 3500)
  398. })
  399. },
  400. changeTitle (num) {
  401. // 开启全局消息免扰
  402. if (this.getGlobalNotice() == 1) return
  403. if (document.hidden) {
  404. let title = num ? `MeeChat (你有${num}新消息)` : `MeeChat`
  405. document.title = title
  406. if (num) {
  407. if (this.tabTimer) clearTimeout(this.tabTimer)
  408. this.tabTimer = setTimeout(() => {
  409. document.title = `MeeChat`
  410. }, 1000)
  411. }
  412. }
  413. },
  414. getGlobalNotice () {
  415. let systemConfig = JSON.parse(localStorage.getItem('systemConfig') || '{}')
  416. return systemConfig.mute || 0
  417. },
  418. /**
  419. * @des 设置通知提醒
  420. * @param type {1:开启,2:关闭}
  421. * */
  422. setGlobalNotice (type) {
  423. let systemConfig = JSON.parse(localStorage.getItem('systemConfig') || '{}')
  424. systemConfig.mute = type
  425. localStorage.setItem('systemConfig', JSON.stringify(systemConfig))
  426. }
  427. }
  428. /**
  429. * @des 转换消息时间
  430. * @param {timeStamp} 时间戳
  431. * @param {type} 类型{1:会话列表,2:信息段}
  432. */
  433. export function formatMsgTime (timeStamp, type = 1) {
  434. if (!timeStamp) return ''
  435. let lastDate = dayjs().subtract(1, 'days').format('YYYY-MM-DD') // 昨天
  436. let inputDay = dayjs(timeStamp * 1)
  437. let inputDate = inputDay.format('YYYY-MM-DD')
  438. switch (type) {
  439. // 会话列表
  440. case 1:
  441. if (inputDate < lastDate) {
  442. return inputDay.format('YY/MM/DD')
  443. } else if (lastDate == inputDate) {
  444. return `昨天`
  445. } else {
  446. return inputDay.format('HH:mm')
  447. }
  448. // 信息段
  449. case 2:
  450. if (inputDate < lastDate) {
  451. return inputDay.format('MM月DD日 HH:mm')
  452. } else if (lastDate == inputDate) {
  453. return `昨天 ${inputDay.format('HH:mm')}`
  454. } else {
  455. return inputDay.format('HH:mm')
  456. }
  457. }
  458. }