// Telegram 机器人通知:加密配置读取、消息发送与新邮件推送队列
import { decrypt } from '../crypto.js';
import { getRawSettings } from '../settings.js';
const TELEGRAM_API = 'https://api.telegram.org';
/** 读取当前用户的 Telegram 配置并解密凭据 */
export function getTelegramConfig(userId) {
const notifications = getRawSettings(userId).notifications || {};
return {
enabled: Boolean(notifications.enabled),
botToken: decrypt(notifications.botTokenEnc || ''),
chatId: decrypt(notifications.chatIdEnc || ''),
};
}
function formatTime(timestamp) {
const timeZone = process.env.TZ || 'Asia/Shanghai';
try {
return new Date(timestamp || Date.now()).toLocaleString('zh-CN', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
});
} catch {
return new Date(timestamp || Date.now()).toLocaleString('zh-CN', { hour12: false });
}
}
/** 调用 Telegram Bot API 发送消息 */
export async function sendTelegramMessage({ botToken, chatId }, text) {
if (!botToken || !chatId) throw new Error('请先填写 Bot Token 与 Chat ID');
let response;
try {
response = await fetch(`${TELEGRAM_API}/bot${botToken}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text,
disable_web_page_preview: true,
}),
signal: AbortSignal.timeout(15000),
});
} catch (err) {
throw new Error(`无法连接 Telegram:${err.message || err}`);
}
let data = null;
try {
data = await response.json();
} catch {
/* 非 JSON 响应 */
}
if (!response.ok || (data && data.ok === false)) {
const detail = data?.description || `HTTP ${response.status}`;
throw new Error(`Telegram 返回错误:${detail}`);
}
return true;
}
/** 新邮件通知文本 */
export function buildMailNotification(data) {
const from = data.fromName
? `${data.fromName} <${data.fromAddr || ''}>`
: data.fromAddr || '未知发件人';
const account = data.accountEmail
? `${data.accountName || ''} <${data.accountEmail}>`.trim()
: data.accountName || '';
const lines = [
'📬 xmail 新邮件提醒',
`收件账号:${account || '未知账号'}`,
`发件人:${from}`,
`主题:${data.subject || '(无主题)'}`,
`时间:${formatTime(data.date)}`,
];
if (data.snippet) lines.push(`摘要:${data.snippet}`);
return lines.join('\n');
}
/** 发送测试消息(可传入页面未保存的凭据) */
export async function sendTestTelegram(userId, overrides = {}) {
const config = getTelegramConfig(userId);
const botToken = String(overrides.botToken || '').trim() || config.botToken;
const chatId = String(overrides.chatId || '').trim() || config.chatId;
const text = [
'✅ xmail 测试消息',
'Telegram 通知配置已生效。',
`时间:${formatTime(Date.now())}`,
].join('\n');
await sendTelegramMessage({ botToken, chatId }, text);
}
// ---------- 新邮件推送队列 ----------
// 同步过程中只入队,不阻塞 IMAP;后台串行发送,避免触发 Telegram 频率限制
const queue = [];
const MAX_QUEUE = 100;
const SEND_INTERVAL = 1000;
let draining = false;
/** 将一封新邮件加入推送队列 */
export function queueMailNotification(userId, data) {
if (queue.length >= MAX_QUEUE) return;
queue.push({ userId, data });
void drainQueue();
}
async function drainQueue() {
if (draining) return;
draining = true;
try {
while (queue.length) {
const job = queue.shift();
try {
const config = getTelegramConfig(job.userId);
if (config.enabled && config.botToken && config.chatId) {
await sendTelegramMessage(config, buildMailNotification(job.data));
}
} catch (err) {
console.error('[xmail] Telegram 通知发送失败:', String(err.message || err));
}
await new Promise((resolve) => setTimeout(resolve, SEND_INTERVAL));
}
} finally {
draining = false;
}
}