Skip to content

Message center #297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.development
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
ENV = 'development'

VUE_APP_BASE_URL = 'http://localhost:5000/'
VUE_APP_BASE_URL = 'http://api.s.colorful3.com'
65 changes: 61 additions & 4 deletions src/components/layout/NavBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@
<breadcrumb />
<!-- 暂时放这里 -->
<div class="right-info">
<notify v-permission="'消息推送'" v-show="false" />
<lin-notify
@readMessages="readMessages"
:messages="messages"
@readAll="readAll"
@viewAll="viewAll"
class="lin-notify"
:value="value"
:hidden="hidden"
>
</lin-notify>
<clear-tab></clear-tab>
<screenfull /> <user></user>
</div>
Expand All @@ -13,26 +22,74 @@
</template>

<script>
import Notify from '@/components/notify/notify'
import Breadcrumb from './Breadcrumb'
import Screenfull from './Screenfull'
import User from './User'
import ClearTab from './ClearTab'
import { getToken } from '@/lin/utils/token'
import store from '@/store'

export default {
name: 'NavBar',
created() {},
created() {
this.$connect(this.path, { format: 'json' })
this.$options.sockets.onmessage = data => {
console.log(JSON.parse(data.data))
this.messages.push(JSON.parse(data.data))
}
this.$options.sockets.onerror = err => {
console.log(err)
this.$message.error('token已过期,请重新登录')
store.dispatch('loginOut')
const { origin } = window.location
window.location.href = origin
}
},
watch: {
messages() {
// eslint-disable-next-line
this.value = this.messages.filter(msg => {
return msg.is_read === false
}).length
if (this.value === 0) {
this.hidden = true
} else {
this.hidden = false
}
},
},
data() {
return {
value: 0,
hidden: true,
messages: [],
path: `//api.s.colorful3.com/ws/message?token=${getToken('access_token').split(' ')[1]}`,
}
},
methods: {
readAll() {
console.log('点击了readAll')
},
viewAll() {
console.log('点击了viewAll')
},
readMessages(msg, index) {
this.messages[index].is_read = true
},
},
components: {
Breadcrumb,
User,
Notify,
Screenfull,
ClearTab,
},
}
</script>

<style lang="scss" scoped>
.lin-notify {
margin-right: 20px;
}
.app-nav-bar {
width: 100%;
height: $navbar-height;
Expand Down
2 changes: 1 addition & 1 deletion src/components/layout/User.vue
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ export default {
done()
},
outLogin() {
this.loginOut()
window.location.reload(true)
this.loginOut()
},
submitForm(formName) {
if (this.form.old_password === '' && this.form.new_password === '' && this.form.confirm_password === '') {
Expand Down
50 changes: 50 additions & 0 deletions src/components/notify/Emitter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* eslint-disable*/
class Emitter {
constructor() {
this.listeners = new Map()
}

addListener(label, callback, vm) {
if (typeof callback === 'function') {
this.listeners.has(label) || this.listeners.set(label, [])
this.listeners.get(label).push({ callback, vm })
return true
}
return false
}

removeListener(label, callback, vm) {
const listeners = this.listeners.get(label)
let index

if (listeners && listeners.length) {
index = listeners.reduce((i, listener, index) => {
if (typeof listener.callback === 'function' && listener.callback === callback && listener.vm === vm) {
i = index
}
return i
}, -1)

if (index > -1) {
listeners.splice(index, 1)
this.listeners.set(label, listeners)
return true
}
}
return false
}

emit(label, ...args) {
const listeners = this.listeners.get(label)

if (listeners && listeners.length) {
listeners.forEach(listener => {
listener.callback.call(listener.vm, ...args)
})
return true
}
return false
}
}

export default new Emitter()
116 changes: 116 additions & 0 deletions src/components/notify/Observer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/* eslint-disable*/
import Emitter from './Emitter'

export default class {
constructor(connectionUrl, opts = {}) {
this.format = opts.format && opts.format.toLowerCase()

if (connectionUrl.startsWith('//')) {
const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws'
connectionUrl = `${scheme}:${connectionUrl}`
}

this.connectionUrl = connectionUrl
this.opts = opts

this.reconnection = this.opts.reconnection || false
this.reconnectionAttempts = this.opts.reconnectionAttempts || Infinity
this.reconnectionDelay = this.opts.reconnectionDelay || 1000
this.reconnectTimeoutId = 0
this.reconnectionCount = 0

this.passToStoreHandler = this.opts.passToStoreHandler || false

this.connect(connectionUrl, opts)

if (opts.store) {
this.store = opts.store
}
if (opts.mutations) {
this.mutations = opts.mutations
}
this.onEvent()
}

connect(connectionUrl, opts = {}) {
const protocol = opts.protocol || ''
this.WebSocket =
opts.WebSocket || (protocol === '' ? new WebSocket(connectionUrl) : new WebSocket(connectionUrl, protocol))
if (this.format === 'json') {
if (!('sendObj' in this.WebSocket)) {
this.WebSocket.sendObj = obj => this.WebSocket.send(JSON.stringify(obj))
}
}

return this.WebSocket
}

reconnect() {
if (this.reconnectionCount <= this.reconnectionAttempts) {
this.reconnectionCount++
clearTimeout(this.reconnectTimeoutId)

this.reconnectTimeoutId = setTimeout(() => {
if (this.store) {
this.passToStore('SOCKET_RECONNECT', this.reconnectionCount)
}

this.connect(this.connectionUrl, this.opts)
this.onEvent()
}, this.reconnectionDelay)
} else if (this.store) {
this.passToStore('SOCKET_RECONNECT_ERROR', true)
}
}

onEvent() {
;['onmessage', 'onclose', 'onerror', 'onopen'].forEach(eventType => {
this.WebSocket[eventType] = event => {
Emitter.emit(eventType, event)

if (this.store) {
this.passToStore(`SOCKET_${eventType}`, event)
}

if (this.reconnection && eventType === 'onopen') {
this.opts.$setInstance(event.currentTarget)
this.reconnectionCount = 0
}

if (this.reconnection && eventType === 'onclose') {
this.reconnect()
}
}
})
}

passToStore(eventName, event) {
if (this.passToStoreHandler) {
this.passToStoreHandler(eventName, event, this.defaultPassToStore.bind(this))
} else {
this.defaultPassToStore(eventName, event)
}
}

defaultPassToStore(eventName, event) {
if (!eventName.startsWith('SOCKET_')) {
return
}
let method = 'commit'
let target = eventName.toUpperCase()
let msg = event
if (this.format === 'json' && event.data) {
msg = JSON.parse(event.data)
if (msg.mutation) {
target = [msg.namespace || '', msg.mutation].filter(e => !!e).join('/')
} else if (msg.action) {
method = 'dispatch'
target = [msg.namespace || '', msg.action].filter(e => !!e).join('/')
}
}
if (this.mutations) {
target = this.mutations[target] || target
}
this.store[method](target, msg)
}
}
86 changes: 86 additions & 0 deletions src/components/notify/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/* eslint-disable*/

/* Author: https://github.com/nathantsoi/vue-native-websocket */
import Notify from './notify.vue'
import Observer from './Observer'
import Emitter from './Emitter'

export default {
install(Vue, connection, opts = {}) {
if (typeof connection === 'object') {
opts = connection
connection = ''
}
let observer = null

opts.$setInstance = wsInstance => {
Vue.prototype.$socket = wsInstance
}
Vue.prototype.$connect = (connectionUrl = connection, connectionOpts = opts) => {
connectionOpts.$setInstance = opts.$setInstance
observer = new Observer(connectionUrl, connectionOpts)
Vue.prototype.$socket = observer.WebSocket
}

Vue.prototype.$disconnect = () => {
if (observer && observer.reconnection) {
observer.reconnection = false
}
if (Vue.prototype.$socket) {
Vue.prototype.$socket.close()
delete Vue.prototype.$socket
}
}
const hasProxy = typeof Proxy !== 'undefined' && typeof Proxy === 'function' && /native code/.test(Proxy.toString())
Vue.component('LinNotify', Notify)
Vue.mixin({
created() {
const vm = this
const { sockets } = this.$options

if (hasProxy) {
this.$options.sockets = new Proxy(
{},
{
set(target, key, value) {
Emitter.addListener(key, value, vm)
target[key] = value
return true
},
deleteProperty(target, key) {
Emitter.removeListener(key, vm.$options.sockets[key], vm)
delete target.key
return true
},
},
)
if (sockets) {
Object.keys(sockets).forEach(key => {
this.$options.sockets[key] = sockets[key]
})
}
} else {
Object.seal(this.$options.sockets)

// if !hasProxy need addListener
if (sockets) {
Object.keys(sockets).forEach(key => {
Emitter.addListener(key, sockets[key], vm)
})
}
}
},
beforeDestroy() {
if (hasProxy) {
const { sockets } = this.$options

if (sockets) {
Object.keys(sockets).forEach(key => {
delete this.$options.sockets[key]
})
}
}
},
})
},
}
Loading