mtfosbot/background.js
2018-06-27 17:50:56 +08:00

75 lines
2.2 KiB
JavaScript

const cron = require('cron')
const DB = require('./libs/database')
const fbParser = require('./libs/facebook-pageparse')
const {
pushMessage
} = require('./libs/line-message')
new cron.CronJob({ // eslint-disable-line
cronTime: '00 */2 * * * *',
onTick: async () => {
console.log('run cron')
let db = await DB.connect()
let text = `select line."notify" as notify, fb."id" as id, fb."groupid" as group, fb."pageid" as page, fb."tmpl" as tmpl, fb."lastpost" as post
from "public"."facebook_page" fb
left join "public"."line_group" line
on line."id" = fb."groupid"
where
line."notify" = true`
let res = await db.query({
text
})
console.log('rows length :::: ', res.rowCount)
if (res.rows.legnth === 0) return
await new Promise(resolve => {
let count = res.rowCount
res.rows.forEach(t => {
fbParser.getLastPost(t.page)
.then((data) => {
let n = Math.floor(Date.now() / 1000)
if (t.post === data.id || data.time < (n - 10 * 60)) {
if (!--count) resolve(null)
return
}
t.post = data.id
let msg = t.tmpl || ''
if (typeof msg !== 'string' || msg.trim().length === 0) {
msg = `${data.txt}\n${data.link}`
} else {
msg = msg.replace(/{link}/, data.link).replace(/{txt}/, data.txt).replace(/\\n/, '\n')
}
if (t.notify) {
pushMessage(t.group, msg).then(() => {}).catch(() => {})
}
let text = `update "public"."facebook_page" set "lastpost" = $1, "mtime" = now() where "id" = $2`
let values = [data.id, t.id]
db.query({
text,
values
}).then(() => {}).catch(() => {})
if (!--count) resolve(null)
})
.catch(() => {
if (!--count) resolve(null)
})
})
})
db.release()
},
runOnInit: true,
start: true,
timeZone: 'Asia/Taipei'
})
// register twitch streaming webhook
new cron.CronJob({ //eslint-disable-line
cronTime: '00 00 0,6,12,18 * * *',
onTick: async () => {
},
runOnInit: true,
start: true,
timeZone: 'Asia/Taipei'
})