forked from lunanting/cangku
133 lines
4.7 KiB
JavaScript
133 lines
4.7 KiB
JavaScript
'use strict';
|
||
|
||
const cron = require('node-cron');
|
||
const {
|
||
getAlibaba1688ImageSearchRuntimeConfig,
|
||
getCredentialValidity,
|
||
getExpiryNotificationAdminStatus,
|
||
} = require('../services/alibaba1688ImageSearchSettings');
|
||
const { sendYydNotification } = require('../services/yydNotificationCenterClient');
|
||
|
||
const DEFAULT_CRON = '0 9 * * *';
|
||
const TIMEZONE = 'Asia/Shanghai';
|
||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||
|
||
function selectExpiryAlertStage(validity = {}) {
|
||
if (!validity.tracked || !Number.isFinite(Number(validity.remainingMs))) return '';
|
||
const remainingMs = Number(validity.remainingMs);
|
||
if (remainingMs <= 0) return 'expired';
|
||
if (remainingMs <= DAY_MS) return 'one_day';
|
||
if (remainingMs <= 2 * DAY_MS) return 'two_days';
|
||
return '';
|
||
}
|
||
|
||
function formatChinaTime(value) {
|
||
const date = new Date(value);
|
||
if (!Number.isFinite(date.getTime())) return '未记录';
|
||
return new Intl.DateTimeFormat('zh-CN', {
|
||
timeZone: TIMEZONE,
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
day: '2-digit',
|
||
hour: '2-digit',
|
||
minute: '2-digit',
|
||
hour12: false,
|
||
}).format(date);
|
||
}
|
||
|
||
function buildExpiryNotification({ validity, stage, recipientAlias }) {
|
||
const expired = stage === 'expired';
|
||
const remainingHours = expired ? 0 : Math.max(1, Math.ceil(Number(validity.remainingMs) / (60 * 60 * 1000)));
|
||
const remainingText = expired
|
||
? '已过期'
|
||
: remainingHours >= 24
|
||
? `约 ${Math.ceil(remainingHours / 24)} 天`
|
||
: `约 ${remainingHours} 小时`;
|
||
const expiryKey = String(validity.expiresAt || '').replace(/\D/g, '').slice(0, 14) || 'unknown';
|
||
const actionUrl = String(
|
||
process.env.ALIBABA_1688_IMAGE_SEARCH_SETTINGS_URL
|
||
|| 'https://pddg.jiansuntuzhi.cn/settings?tab=alibaba1688ImageSearch'
|
||
).trim();
|
||
return {
|
||
idempotencyKey: `alibaba1688_image_search_key_expiry:${expiryKey}:${recipientAlias}:${stage}:v1`,
|
||
recipientAlias,
|
||
title: expired ? '1688以图搜款 API Key 已过期' : '1688以图搜款 API Key 即将到期',
|
||
content: [
|
||
'**配置项:** 1688 以图搜款 API Key',
|
||
`**剩余有效时间:** ${remainingText}`,
|
||
`**到期时间:** ${formatChinaTime(validity.expiresAt)}`,
|
||
'',
|
||
'> 请及时在系统设置中替换新 Key,填写新 Key 并保存后会重新计算 7 天有效期。',
|
||
].join('\n\n'),
|
||
actionTitle: '立即替换',
|
||
actionUrl,
|
||
};
|
||
}
|
||
|
||
async function checkAlibaba1688ImageSearchExpiry(options = {}) {
|
||
const now = options.now === undefined ? Date.now() : Number(options.now);
|
||
const config = await getAlibaba1688ImageSearchRuntimeConfig({ forceRefresh: true });
|
||
const validity = getCredentialValidity(config, now);
|
||
const notification = await getExpiryNotificationAdminStatus();
|
||
const stage = selectExpiryAlertStage(validity);
|
||
if (!stage) {
|
||
return { sent: false, reason: validity.status, validity };
|
||
}
|
||
if (!notification.configured) {
|
||
return { sent: false, reason: 'notification_not_configured', stage, validity };
|
||
}
|
||
|
||
const payload = buildExpiryNotification({
|
||
validity,
|
||
stage,
|
||
recipientAlias: notification.recipientAlias,
|
||
});
|
||
const response = await sendYydNotification(payload);
|
||
return {
|
||
sent: true,
|
||
stage,
|
||
deliveryId: response?.id || response?.data?.id || null,
|
||
validity,
|
||
};
|
||
}
|
||
|
||
async function runAlibaba1688ImageSearchExpiryJob(source = 'scheduled') {
|
||
try {
|
||
const result = await checkAlibaba1688ImageSearchExpiry();
|
||
if (result.sent) {
|
||
console.log(`[Alibaba1688ImageSearchExpiry] ${source} notification accepted: ${result.stage}`);
|
||
}
|
||
return result;
|
||
} catch (error) {
|
||
console.error(`[Alibaba1688ImageSearchExpiry] ${source} check failed:`, error.message || error);
|
||
return { sent: false, reason: 'error', error: error.message || String(error) };
|
||
}
|
||
}
|
||
|
||
function startAlibaba1688ImageSearchExpiryScheduler() {
|
||
const disabled = String(process.env.DISABLE_ALIBABA_1688_IMAGE_SEARCH_EXPIRY_NOTIFICATION || '')
|
||
.trim()
|
||
.toLowerCase() === 'true';
|
||
if (disabled) {
|
||
console.log('[Scheduler] 1688以图搜款 Key 到期提醒已禁用');
|
||
return;
|
||
}
|
||
const expression = String(process.env.ALIBABA_1688_IMAGE_SEARCH_EXPIRY_CRON || DEFAULT_CRON).trim();
|
||
cron.schedule(expression, () => {
|
||
runAlibaba1688ImageSearchExpiryJob('daily_schedule').catch(() => {});
|
||
}, { timezone: TIMEZONE });
|
||
const startupTimer = setTimeout(() => {
|
||
runAlibaba1688ImageSearchExpiryJob('startup').catch(() => {});
|
||
}, 30 * 1000);
|
||
if (typeof startupTimer.unref === 'function') startupTimer.unref();
|
||
console.log(`[Scheduler] 1688以图搜款 Key 到期提醒已注册: ${expression} (${TIMEZONE})`);
|
||
}
|
||
|
||
module.exports = {
|
||
buildExpiryNotification,
|
||
checkAlibaba1688ImageSearchExpiry,
|
||
runAlibaba1688ImageSearchExpiryJob,
|
||
selectExpiryAlertStage,
|
||
startAlibaba1688ImageSearchExpiryScheduler,
|
||
};
|