mtfosbot/route/twitch/index.js
2018-06-28 17:37:33 +08:00

83 lines
2.1 KiB
JavaScript

const Router = require('koa-router')
const r = new Router()
const {
getRaw
} = require('../../libs/middleware')
const DB = require('../../libs/database')
const api = require('../../libs/api-action')
// const config = require('../../config')
r.get('/webhook', async (c, n) => {
let mode = c.query['hub.mode']
let token = c.query['hub.secret']
let challenge = c.query['hub.challenge']
console.log(mode, token, challenge)
console.log(c.headers)
if (mode) {
if (mode === 'subscribe') {
c.status = 200
c.body = challenge
} else {
c.status = 403
c.body = ''
}
}
})
r.post('/webhook', getRaw, async (c, n) => {
// middleware
c.db = await DB.connect()
try {
await n()
} catch (err) {
console.log(err)
}
c.db.release()
c.body = 'success'
c.status = 200
}, async (c, n) => {
console.log(JSON.stringify(c.request.body, null, 2))
if (!('data' in c.request.body) || !Array.isArray(c.request.body.data)) return
if (c.request.body.data.length === 0) return // length > 0 live, length === 0 down
let data = c.request.body.data[0]
let uid = c.query['uid'] || ''
let type = c.query['type'] || ''
if (!uid || !type) return
let text = `select rt."line" as group, rt."twitch" as twitch, rt."tmpl" as tmpl, twitch."name" as user from "public"."line_twitch_rt" rt
left join "public"."twitch_channel" twitch
on twitch."id" = rt."twitch"
left join "public"."line_group" line
on line."id" = rt."line"
where
line."notify" = true
and twitch."id" = $1
and rt."type" = $2`
let values = [uid, type]
let twch = await c.db.query({
text,
values
})
if (twch.rowCount === 0) return
let chLink = `https://twitch.tv/`
for (let i in twch.rows) {
let tmp = twch.rows[i]
let msg = tmp.tmpl || ''
let link = chLink + tmp.user
if (typeof msg !== 'string' || msg.trim().length === 0) {
msg = `${data.title}\n${link}`
} else {
msg = msg.replace(/{link}/, link).replace(/{txt}/, data.title).replace(/\\n/, '\n')
}
await api.line.pushMessage(tmp.group, msg).then(() => { }).catch(() => { })
}
})
module.exports = r