full
This commit is contained in:
63
services/InstagramMediaSyncCron.js
Normal file
63
services/InstagramMediaSyncCron.js
Normal file
@@ -0,0 +1,63 @@
|
||||
const cron = require('node-cron')
|
||||
const UserModel = require('../models/UserModel')
|
||||
const InstagramGraphService = require('../services/InstagramGraphService')
|
||||
const { decryptSecret, encryptSecret } = require('../utils/secretCipher')
|
||||
const { importInstagramMedia } = require('../utils/instagramMediaImport')
|
||||
|
||||
const TOKEN_REFRESH_WINDOW_MS = 7 * 24 * 60 * 60 * 1000 // ۷ روز قبل انقضا رفرش کن
|
||||
|
||||
/**
|
||||
* برای کاربرانی که «همگامسازی خودکار» رو فعال کردن، پستهای جدید اینستاگرامشون رو
|
||||
* وارد مدستاگرام میکنه. هر کاربر جدا try/catch میشه تا خطای یک حساب بقیه رو متوقف نکنه.
|
||||
* این تنها کانسیومر decryptSecret تو کل بکاند بود قبل از این فایل — همون الگوی رمزگشایی
|
||||
* که instagramController.js موقع رمزنگاری استفاده میکنه رو برعکس اجرا میکنه.
|
||||
*/
|
||||
async function runInstagramMediaSync () {
|
||||
const users = await UserModel.find({
|
||||
'instagram_sync_prefs.auto_update': true,
|
||||
instagram_access_token_enc: { $ne: null },
|
||||
})
|
||||
|
||||
for (const user of users) {
|
||||
try {
|
||||
let accessToken = decryptSecret(user.instagram_access_token_enc)
|
||||
|
||||
const expiresAt = user.instagram_token_expires_at ? new Date(user.instagram_token_expires_at).getTime() : 0
|
||||
if (expiresAt && expiresAt - Date.now() < TOKEN_REFRESH_WINDOW_MS) {
|
||||
const refreshed = await InstagramGraphService.refreshLongLivedToken(accessToken)
|
||||
accessToken = refreshed.accessToken
|
||||
await UserModel.updateOne(
|
||||
{ _id: user._id },
|
||||
{
|
||||
$set: {
|
||||
instagram_access_token_enc: encryptSecret(accessToken),
|
||||
instagram_token_expires_at: refreshed.expiresAt,
|
||||
},
|
||||
},
|
||||
{ strict: false }
|
||||
)
|
||||
}
|
||||
|
||||
const { items } = await InstagramGraphService.getMedia(accessToken)
|
||||
for (const item of items) {
|
||||
await importInstagramMedia(user, item)
|
||||
}
|
||||
|
||||
await UserModel.updateOne(
|
||||
{ _id: user._id },
|
||||
{ $set: { instagram_last_synced_at: new Date() } },
|
||||
{ strict: false }
|
||||
)
|
||||
} catch (err) {
|
||||
console.error(`[InstagramMediaSyncCron] user ${user._id} failed:`, err?.response?.data || err.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cron.schedule('0 * * * *', () => {
|
||||
runInstagramMediaSync().catch((err) => {
|
||||
console.error('[InstagramMediaSyncCron] run failed:', err.message)
|
||||
})
|
||||
}, { scheduled: true, timezone: 'Asia/Tehran' })
|
||||
|
||||
module.exports = { runInstagramMediaSync }
|
||||
Reference in New Issue
Block a user