84 lines
2.1 KiB
JavaScript
84 lines
2.1 KiB
JavaScript
const cron = require('cron')
|
|
const axios = require('axios')
|
|
const config = require('./config')
|
|
const fbparser = require('./facebook-parser')
|
|
|
|
const getIDsUrl = '/api/private/pages'
|
|
const updatePostsUrl = '/api/private/pageposts'
|
|
|
|
const getIDsFromAPI = async () => {
|
|
try {
|
|
let apiResult = await axios({
|
|
baseURL: config.api_url,
|
|
url: getIDsUrl,
|
|
headers: {
|
|
'X-Mtfos-Key': config.api_key
|
|
},
|
|
method: 'get'
|
|
})
|
|
if (!('data' in apiResult) || !('list' in apiResult.data) || !Array.isArray(apiResult.data.list)) return
|
|
apiResult.data.list.forEach(t => {
|
|
getLastPost(t)
|
|
})
|
|
} catch (err) {
|
|
console.log('get ids fail :::: ', err)
|
|
}
|
|
}
|
|
|
|
const getLastPost = async (id = '') => {
|
|
console.log(`Start Get ${id} Page Post`)
|
|
if (typeof id !== 'string' || id.trim().length === 0) return
|
|
id = id.trim()
|
|
|
|
try {
|
|
let lastPost = await fbparser.getLastPost(id)
|
|
if (lastPost === null) {
|
|
console.log('get post empty')
|
|
return
|
|
}
|
|
console.log('get post ::: ', `PageID: ${id} / PostID: ${lastPost.id} / Time: ${lastPost.time} / Text: ${lastPost.txt}`)
|
|
if (!('id' in lastPost) || !('txt' in lastPost) || !('time' in lastPost) || !('link' in lastPost)) return
|
|
let minTime = Math.floor(Date.now() / 1000) - 1800
|
|
if (minTime > lastPost.time) return
|
|
let data = {
|
|
id,
|
|
post_id: lastPost.id,
|
|
text: lastPost.txt,
|
|
link: lastPost.link
|
|
}
|
|
try {
|
|
await axios({
|
|
baseURL: config.api_url,
|
|
url: updatePostsUrl,
|
|
method: 'post',
|
|
headers: {
|
|
'X-Mtfos-Key': config.api_key
|
|
},
|
|
data: {
|
|
pages: [data]
|
|
}
|
|
})
|
|
} catch (err) {
|
|
console.log('update post data fail', err)
|
|
}
|
|
} catch (err) {
|
|
console.log('get last post error', err)
|
|
}
|
|
}
|
|
|
|
// set fblook
|
|
new cron.CronJob({ //eslint-disable-line
|
|
cronTime: '00 */2 * * * *',
|
|
onTick: async () => {
|
|
console.log('Start Tick')
|
|
try {
|
|
await getIDsFromAPI()
|
|
} catch (err) {
|
|
console.log('run tick fail', err)
|
|
}
|
|
},
|
|
runOnInit: true,
|
|
start: true,
|
|
timeZone: 'Asia/Taipei'
|
|
})
|