donate notify fin v1

This commit is contained in:
Jay
2018-07-21 00:46:01 +08:00
parent 9d964268e8
commit a767ef3869
5 changed files with 81 additions and 6 deletions
+54 -2
View File
@@ -5,17 +5,30 @@ const {
msgSplit
} = require('./parser')
const event = require('@root/event')
// const _ = require('lodash')
class WS {
constructor () {
/** @type {WebSocket} */
this.ws = null
// cache struct
// cache = {
// [channel]: {
// time: timestamp,
// list: []
// }
// }
this.cache = {}
this.tick = null
this.join = []
this.tick = setInterval(this.runTick.bind(this), 1000)
event.on('twitchJoin', (channel) => {
this.joinChannel(channel)
})
event.on('twitchSend', data => {
this.sendMsg(data.channel, data.message)
if (!('msg' in data) || typeof data.msg !== 'string') return
if (!('channel' in data) || typeof data.channel !== 'string') return
this.queueMsg(data.channel, data.msg)
})
}
@@ -66,7 +79,7 @@ class WS {
this.ws.send('CAP REQ :twitch.tv/membership :twitch.tv/commands')
// 取得要加入的頻道列表
let text = `select "name" from "public"."twitch_channel where "join" = true`
let text = `select "name" from "public"."twitch_channel" where "join" = true`
let result = await db.query({
text
})
@@ -85,6 +98,45 @@ class WS {
}
}
queueMsg (channel, msg) {
if (typeof channel !== 'string' || channel.trim().length === 0) return
if (typeof msg !== 'string' || msg.trim().length === 0) return
if (channel in this.cache) {
if ('list' in this.cache[channel]) {
this.cache[channel].list = [...this.cache[channel].list, msg]
} else {
this.cache[channel].list = [msg]
}
} else {
this.cache[channel] = {
time: -1,
list: [msg]
}
}
}
runTick () {
if (this.cache === null || typeof this.cache !== 'object') return
let time = Date.now()
for (let i in this.cache) {
if ('time' in this.cache[i] && this.cache[i].time <= (time - 1500)) {
if ('list' in this.cache[i] && Array.isArray(this.cache[i].list) && this.cache[i].list.length > 0) {
let msg = this.cache[i].list[0]
this.cache[i].list = [...this.cache[i].list.slice(1)]
this.sendMsg(i, msg)
}
this.cache[i].time = time
} else {
if ('list' in this.cache[i] && Array.isArray(this.cache[i].list) && this.cache[i].list.length > 0) {
let msg = this.cache[i].list[0]
this.cache[i].list = [...this.cache[i].list.slice(1)]
this.sendMsg(i, msg)
}
this.cache[i].time = time
}
}
}
sendMsg (channel = null, message = null) {
if (this.ws === null || !('send' in this.ws) || typeof this.ws.send !== 'function') return null
if (channel === null || typeof channel !== 'string' || channel.trim().length === 0) return null