mtfosbot/route/google/index.js
2018-08-11 12:58:34 +08:00

100 lines
2.7 KiB
JavaScript

const Router = require('koa-router')
const xml2js = require('xml2js')
const r = new Router()
// const koaBody = require('koa-body')
const {
getRaw
} = require('@libs/middleware')
const api = require('@libs/api-action')
const DB = require('@libs/database')
r.get('/youtube/webhook', async (c, n) => {
let db = await DB.connect()
let mode = c.query['hub.mode'] || ''
// let verifyToken = c.query['hub.verify_token'] || ''
let challenge = c.query['hub.challenge']
let id = c.query['id'] || ''
if (mode) {
if (mode === 'subscribe' && typeof id === 'string' && id.trim().length > 0) {
let time = Math.floor((Date.now() + (86400 * 1000)) / 1000)
try {
await db.query({
text: `update "public"."youtube_channel" set "expire" = $1, "mtime" = now() where "id" = $2`,
values: [time, id]
})
} catch (err) {
console.log(err)
}
c.status = 200
c.body = challenge
} else {
c.status = 403
c.body = ''
}
}
db.release()
})
r.post('/youtube/webhook', getRaw, async (c, n) => {
let db = await DB.connect()
let xmlStr = c.request.raw.toString()
// console.log(xmlStr)
let data = await new Promise((resolve) => {
xml2js.parseString(xmlStr, (err, res) => {
if (err) return resolve(null)
resolve(res)
})
})
console.log(JSON.stringify(data, null, 2))
try {
let ytid = data.feed.entry[0].id[0]
let title = data.feed.entry[0].title[0]
let link = data.feed.entry[0].link[0]['$']['href']
let id = c.query['id'] || ''
console.log(`yt: ${ytid} / link: ${link} / id: ${id}`)
let text = `select rt."tmpl" as tmpl, line."id" as group from "public"."line_youtube_rt" rt
left join "public"."youtube_channel" ch
on ch."id" = rt."youtube"
left join "public"."line_group" line
on line."id" = rt."line"
where
ch."id" = $1
and ch."lastvideo" != $2
and line."notify" = true`
let values = [id, ytid]
let result = await db.query({
text,
values
})
if (result.rowCount > 0) {
result.rows.forEach(t => {
let msg = t.tmpl || ''
if (typeof msg !== 'string' || msg.trim().length === 0) {
msg = `${title || ''}\n${link}`
} else {
msg = msg.replace(/{link}/, link).replace(/{txt}/, title).replace(/\\n/, '\n')
}
api.line.pushMessage(t.group, msg).then(() => {}).catch(() => {})
})
}
await db.query({
text: `update "public"."youtube_channel" set "lastvideo" = $1, "mtime" = now() where "id" = $2`,
values: [ytid, id]
})
} catch (err) {
console.log(err)
}
c.status = 200
c.body = 'success'
db.release()
})
module.exports = r