123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393 |
- import { MessageBox } from 'element-ui'
- import TWEEN from '@tweenjs/tween.js'
- const timestampInterval = 1e3 * 60 * 3 // 3分钟的间隔时间
- const cryptoKey = 'dqWt6twz6JyEy3EZ'
- // 错误弹窗
- export function showError (msg, title = 'Error') {
- MessageBox.confirm(msg, title, {
- center: true,
- showCancelButton: false,
- showConfirmButton: false,
- callback () {}
- })
- }
- // 确认操作弹窗
- export function confirmPopup (msg, title = '提示') {
- return new Promise((resolve, reject) => {
- MessageBox.confirm(msg, '提示', {
- confirmButtonText: '确定',
- cancelButtonText: '取消',
- type: 'warning'
- })
- .then(() => {
- resolve()
- })
- .catch(() => {})
- })
- }
- /**
- * 判断系统||浏览器中英文
- * 对于不支持的浏览器 一律默认为 中文
- */
- export function getLanguage () {
- var language = (navigator.language || navigator.browserLanguage).toLowerCase()
- var locale = 'zh'
- if (language.indexOf('en') > -1) {
- locale = 'en'
- } else {
- locale = 'zh'
- }
- return locale
- }
- /**
- * 获取Url上指定参数
- * @param {String} name 参数名
- */
- export function getUrlParam (name) {
- var reg = new RegExp('[?&]' + name + '=([^&#?]*)(&|#|$)')
- var r = window.location.href.match(reg)
- return r ? r[1] : null
- }
- export var Cookie = {
- setCookie (name, value) {
- var Days = 7
- var exp = new Date()
- exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
- exp.setTime(exp.getTime() + 60 * 1000)
- if (
- window.location.port === '8080' ||
- /^test-|\.webdev2\./.test(window.location.host)
- ) {
- document.cookie =
- name + '=' + escape(value) + ';expires=' + exp.toGMTString()
- } else {
- document.cookie =
- name +
- '=' +
- escape(value) +
- ';domain=.mee.chat;path=/;expires=' +
- exp.toGMTString()
- }
- },
- getCookie (name) {
- var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
- var arr = document.cookie.match(reg)
- if (arr) {
- return unescape(arr[2])
- } else {
- return null
- }
- },
- delCookie (name) {
- var str1 = name + '=;domain=.mee.chat;path=/'
- str1 += ';expires=' + new Date(0).toGMTString()
- document.cookie = str1
- var str2 = name + '=;path=/'
- str2 += ';expires=' + new Date(0).toGMTString()
- document.cookie = str2
- }
- }
- /**
- * 获取聊天区域高度
- * @param {String} msg
- */
- export function getResizeHeight () {
- let clientHeight = document.documentElement.clientHeight
- let clientWidth = document.documentElement.clientWidth
- let topHeight = 61
- let botHeight = 181
- var chatBoxHeight
- if (clientHeight < 600) {
- chatBoxHeight = 600 - topHeight - botHeight
- }
- if (clientHeight < 800 || clientWidth < 1000) {
- chatBoxHeight = clientHeight - topHeight - botHeight
- } else {
- chatBoxHeight = clientHeight * 0.8 - topHeight - botHeight
- }
- return chatBoxHeight
- }
- function rc4 (str, key) {
- var s = []
- var j = 0
- var x
- var res = ''
- for (var i = 0; i < 256; i++) {
- s[i] = i
- }
- for (i = 0; i < 256; i++) {
- j = (j + s[i] + key.charCodeAt(i % key.length)) % 256
- x = s[i]
- s[i] = s[j]
- s[j] = x
- }
- i = 0
- j = 0
- for (var y = 0; y < str.length; y++) {
- i = (i + 1) % 256
- j = (j + s[i]) % 256
- x = s[i]
- s[i] = s[j]
- s[j] = x
- res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256])
- }
- return res
- }
- /**
- * 加密信息
- * @param {String} msg
- */
- export function cryptoMsg (msg) {
- let result
- try {
- result = btoa(rc4(encodeURIComponent(msg), cryptoKey))
- } catch {
- return msg
- }
- return result
- }
- /**
- * 解密信息
- * @param {String} msg
- */
- export function decryptoMsg (msg) {
- let result
- try {
- result = decodeURIComponent(rc4(atob(msg), cryptoKey))
- } catch {
- return msg
- }
- return result
- }
- /**
- * 向数组添加数据
- * @param {Array} data
- */
- export function addSomeInArray (data) {
- let lastTime = null
- let linkRule = new RegExp(
- '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
- )
- let queLink = /(['"])(?:(?!\1).)*?\1/
- data.forEach(item => {
- // 添加timeMsg tag
- if (lastTime === null) {
- item.timeMsg = false
- } else {
- item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
- }
- lastTime = parseInt(item.timestamp)
- // 添加链接标识 msg_type = 10
- if (item.content && typeof item.content == 'string' && !item.content.match(queLink) &&
- item.content.match(linkRule) && item.msg_type == 0) {
- item.msg_type = 10
- item.content = item.content.replace(linkRule, a => {
- return `<a href="${a}" class="link text" target="_blank">${a}</a>`
- })
- }
- })
- }
- /**
- * 单个添加timeMsg tag
- * @param {Array} data
- */
- export function addTimeMsgInItem (item, arr) {
- if (arr.length === 0) {
- item.timeMsg = true
- } else {
- let lastTime = parseInt(arr[arr.length - 1].timestamp)
- item.timeMsg = parseInt(item.timestamp) - lastTime > timestampInterval
- }
- }
- /**
- * 判断是否是移动端
- */
- export function isMobile () {
- return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)
- }
- /*
- * 单个添加链接 msg_type = 10
- * @param {Array} data
- */
- export function addLinkItem (item) {
- var linkRule = new RegExp(
- '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
- )
- var queLink = /(['"])(?:(?!\1).)*?\1/
- if (item.content.match(linkRule) && item.msg_type == 0 && !item.content.match(queLink)) {
- item.msg_type = 10
- item.content = item.content.replace(linkRule, a => {
- return `<a href="${a}" class="link text" target="_blank">${a}</a>`
- })
- }
- }
- /**
- * 移除arr2中满足callback的arr1数组元素
- * @param {Array} arr1 [{hash:1}]
- * @param {Array} arr2 [{hash:1},{hash:2}]
- * @result arr1 => []
- */
- export function removeItemIfEixt (arr1, arr2, callback) {
- arr1.forEach((item, index) => {
- if (arr2.some(item2 => callback(item2) == callback(item))) {
- arr1.splice(index, 1)
- }
- })
- }
- /**
- * 格式化置顶消息
- */
- export function formatPinMsg (pinMsg, userId) {
- pinMsg.name = pinMsg.nick_name
- pinMsg.content = decryptoMsg(pinMsg.msg)
- pinMsg.type = pinMsg.from == userId ? 'me' : 'you'
- pinMsg.avatar = pinMsg.cover_photo || ''
- pinMsg.userId = userId
- }
- /**
- * @param {store} state
- * @param {Number} createTime
- */
- export function dealErrorMsg (state, createTime) {
- state.chatList.forEach(item => {
- if (item.createTime == createTime) {
- item.fail = true
- item.loading = false
- }
- })
- }
- /**
- * 如果含有at他人的信息,格式化
- * @param {String} msg @heitan@aben 123
- * @param {Array} members
- * @result => {@start[10,9]end}@heitan@aben 123
- */
- export function encryptAtMsg (msg, members) {
- let ats = []
- members.forEach(user => {
- let reg = new RegExp(`@${user.nick_name}`)
- if (reg.test(msg)) {
- ats.push(user.user_id)
- }
- })
- if (ats.length) {
- msg = `{@start[${ats.toString()}]end}${msg}`
- }
- return msg
- }
- /**
- *
- * @param {String} msg
- * @return {Array|Null}
- */
- export function decryptAtMsg (msg) {
- let reg = /^{@start\[(.*)\]end}/
- let ret = reg.exec(msg)
- if (ret) {
- return ret[0].split(',')
- }
- }
- /**
- *判断是否是at我的信息
- */
- export function checkAtMe (msg, username) {
- if (!username) return false
- let reg = new RegExp(`@${username}`)
- return reg.test(msg)
- }
- export function scrollIntoView (node, offsetTop) {
- let distance = Math.abs(offsetTop - node.scrollTop)
- let time = distance > 500 ? 1000 : distance * 2
- let tw = new TWEEN.Tween(node)
- .to({ scrollTop: offsetTop }, time)
- .easing(TWEEN.Easing.Quadratic.Out)
- return tw.start()
- }
- export function scrollMsgIntoView (node, offsetTop, targetNode) {
- scrollIntoView(node, offsetTop)
- .onComplete(() => {
- targetNode.classList.toggle('active')
- })
- setTimeout(() => {
- targetNode.classList.toggle('active')
- }, 3000)
- }
- export var noticeManager = {
- askPermission () {
- return new Promise((resolve, reject) => {
- if (!('Notification' in window)) {
- reject(new Error('This browser does not support desktop notification'))
- } else if (Notification.permission === 'granted') {
- resolve()
- } else if (Notification.permission === 'default ') {
- Notification.requestPermission(function (permission) {
- // 如果用户同意,就可以向他们发送通知
- if (permission === 'granted') {
- resolve()
- } else {
- reject(new Error())
- }
- })
- }
- })
- },
- showNotification (data) {
- this.askPermission().then(() => {
- let notification = new Notification(data.name, {
- body: '你收到了一条消息',
- icon: `${process.env.BASE_URL}icon_192.png`
- })
- // 打开页面
- let path
- if (data.group_id) {
- path = `/group/${data.group_id}`
- } else {
- let sessionId = +data.to > +data.from ? `${data.from}-${data.to}` : `${data.to}-${data.from}`
- path = `/pm/${sessionId}`
- }
- notification.onclick = () => {
- window.$router.push({ path })
- notification.close()
- window.focus()
- }
- setTimeout(() => {
- notification.close()
- }, 3500)
- })
- },
- changeTitle () {
- if (document.hidden) {
- document.title = 'MeeChat (你有新消息)'
- }
- }
- }
|