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 "pageid", "groupid", "lastpost", "notify", "notify_tmpl" from "public"."page_group_rt"` 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.pageid) .then((data) => { let n = Math.floor(Date.now() / 1000) if (t.lastpost === data.id || data.time < (n - 10 * 60)) { if (!--count) resolve(null) return } t.lastpost = data.id let msg = t.notify_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.groupid, msg).then(() => {}).catch(() => {}) } let text = `update "public"."page_group_rt" set "lastpost" = $1, "mtime" = now() where "pageid" = $2 and "groupid" = $3` let values = [data.id, t.pageid, t.groupid] db.query({ text, values }).then(() => {}).catch(() => {}) if (!--count) resolve(null) }) .catch(() => { if (!--count) resolve(null) }) }) }) db.release() }, start: true, timeZone: 'Asia/Taipei' })