const { Resend } = require('resend');
const { decrypt } = require('./crypto');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
// 调试日志函数
function debugLog(message, data = null) {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] EMAIL DEBUG: ${message}`);
if (data) {
console.log(JSON.stringify(data, null, 2));
}
}
async function sendModelChangeNotification(siteName, diff, fastify) {
debugLog(`=== 开始邮件通知流程 ===`);
debugLog(`站点名称: ${siteName}`);
debugLog('变化数据:', diff);
try {
// 获取邮件配置
debugLog('正在获取邮件配置...');
const config = await prisma.emailConfig.findFirst();
debugLog('邮件配置查询结果:', {
exists: !!config,
enabled: config?.enabled,
hasApiKey: !!config?.resendApiKeyEnc,
notifyEmailsRaw: config?.notifyEmails,
emailCount: config?.notifyEmails ? (() => {
try {
return JSON.parse(config.notifyEmails || '[]').length;
} catch {
return 0;
}
})() : 0
});
if (!config || !config.enabled) {
debugLog('❌ 邮件配置未启用或不存在,跳过发送');
return;
}
// 解析邮箱列表(支持两种格式:JSON数组或逗号分隔字符串)
let emails = [];
try {
const emailStr = (config.notifyEmails || '').trim();
// 检测是否为 JSON 数组格式
if (emailStr.startsWith('[')) {
emails = JSON.parse(emailStr);
} else {
// 作为逗号或分号分隔的字符串处理
emails = emailStr.split(/[,;]/).map(e => e.trim()).filter(e => e.length > 0);
}
debugLog(`✅ 解析邮箱列表成功: [${emails.join(', ')}]`);
} catch (error) {
debugLog('❌ 解析邮箱列表失败:', error.message);
return;
}
if (!emails.length) {
debugLog('❌ 没有配置收件邮箱,跳过发送');
return;
}
// 解密 API Key
let apiKey;
try {
apiKey = decrypt(config.resendApiKeyEnc);
debugLog('✅ API Key 解密成功');
} catch (error) {
debugLog('❌ API Key 解密失败:', error.message);
return;
}
debugLog('正在初始化 Resend...');
const resend = new Resend(apiKey);
debugLog('✅ Resend 初始化完成');
// 检查是否有实际变化(只检查新增和删除)
const hasChanges = (diff.added && diff.added.length > 0) ||
(diff.removed && diff.removed.length > 0);
debugLog('📊 变化检查:', {
hasChanges,
added: diff.added?.length || 0,
removed: diff.removed?.length || 0
});
if (!hasChanges) {
debugLog('❌ 没有模型变化,跳过发送');
return;
}
// 构建邮件内容
debugLog('🔧 开始构建邮件内容...');
let htmlContent = `
🔔 AI 模型变化通知
站点:${siteName}
检测时间:${new Date().toLocaleString('zh-CN')}
`;
// 如果有签到信息,添加签到结果
if (diff.checkInResult) {
const { checkInSuccess, checkInMessage, checkInQuota } = diff.checkInResult;
const statusIcon = checkInSuccess ? '✅' : '❌';
const statusColor = checkInSuccess ? '#52c41a' : '#ff4d4f';
htmlContent += `
${statusIcon} 签到结果
状态:${checkInMessage || (checkInSuccess ? '签到成功' : '签到失败')}
${checkInQuota ? `
获得额度:${checkInQuota}
` : ''}
`;
}
if (diff.added && diff.added.length > 0) {
htmlContent += `
✅ 新增模型 (${diff.added.length})
`;
diff.added.forEach(model => {
htmlContent += `- ${model.id || 'Unknown'}
`;
});
htmlContent += '
';
}
if (diff.removed && diff.removed.length > 0) {
htmlContent += `
❌ 移除模型 (${diff.removed.length})
`;
diff.removed.forEach(model => {
htmlContent += `- ${model.id || 'Unknown'}
`;
});
htmlContent += '
';
}
htmlContent += `
本邮件由 AI 模型监测系统自动发送
`;
debugLog('✅ 邮件内容构建完成');
// 准备邮件参数(完全按照官方示例)
const emailParams = {
from: 'AI模型监测 ',
to: emails,
subject: `[AI模型监测] ${siteName} - 模型发生变化`,
html: htmlContent
};
debugLog('📧 准备发送邮件:', {
from: emailParams.from,
to: emailParams.to,
subject: emailParams.subject,
htmlLength: htmlContent.length
});
// 发送邮件(使用官方示例格式)
debugLog('🚀 正在调用 Resend API...');
const result = await resend.emails.send(emailParams);
debugLog('🎉 邮件发送成功!结果:', result);
fastify?.log?.info(`邮件发送成功: ${siteName} -> ${emails.join(', ')}`);
return result;
} catch (error) {
debugLog('💥 邮件发送过程出错:', {
errorName: error.name,
errorMessage: error.message,
errorStack: error.stack?.split('\n').slice(0, 3),
siteName
});
fastify?.log?.error(`邮件通知失败: ${siteName}`, error);
// 不抛出错误,避免影响主流程
console.error(`[EMAIL] 最终错误: ${siteName}`, error.message);
} finally {
debugLog(`=== 邮件通知流程结束 ===`);
}
}
// 聚合发送多个站点的变更通知
async function sendAggregatedNotification(siteChanges, fastify, failedSites = []) {
debugLog(`=== 开始聚合邮件通知流程 ===`);
debugLog(`站点变更数量: ${siteChanges.length}`);
debugLog(`失败站点数量: ${failedSites.length}`);
try {
// 获取邮件配置
debugLog('正在获取邮件配置...');
const config = await prisma.emailConfig.findFirst();
debugLog('邮件配置查询结果:', {
exists: !!config,
enabled: config?.enabled,
hasApiKey: !!config?.resendApiKeyEnc
});
if (!config || !config.enabled) {
debugLog('❌ 邮件配置未启用或不存在,跳过发送');
return;
}
// 解析邮箱列表
let emails = [];
try {
const emailStr = (config.notifyEmails || '').trim();
if (emailStr.startsWith('[')) {
emails = JSON.parse(emailStr);
} else {
emails = emailStr.split(/[,;]/).map(e => e.trim()).filter(e => e.length > 0);
}
debugLog(`✅ 解析邮箱列表成功: [${emails.join(', ')}]`);
} catch (error) {
debugLog('❌ 解析邮箱列表失败:', error.message);
return;
}
if (!emails.length) {
debugLog('❌ 没有配置收件邮箱,跳过发送');
return;
}
// 解密 API Key
let apiKey;
try {
apiKey = decrypt(config.resendApiKeyEnc);
debugLog('✅ API Key 解密成功');
} catch (error) {
debugLog('❌ API Key 解密失败:', error.message);
return;
}
debugLog('正在初始化 Resend...');
const resend = new Resend(apiKey);
debugLog('✅ Resend 初始化完成');
// 统计总变更数(只统计新增和删除)
let totalAdded = 0;
let totalRemoved = 0;
siteChanges.forEach(sc => {
totalAdded += sc.diff?.added?.length || 0;
totalRemoved += sc.diff?.removed?.length || 0;
});
debugLog('📊 聚合统计:', {
sitesWithChanges: siteChanges.length,
totalAdded,
totalRemoved
});
// 构建聚合邮件内容
debugLog('🔧 开始构建聚合邮件内容...');
let htmlContent = `
📅 检测时间:${new Date().toLocaleString('zh-CN')}
🎯 检测站点:${siteChanges.length} 个
${failedSites.length > 0 ? `
⚠️ 失败站点:${failedSites.length} 个
` : ''}
`;
// 为每个站点添加变更详情
siteChanges.forEach((siteChange, index) => {
const { siteName, diff, checkInResult } = siteChange;
// 统计变更项
const modelChanges = (diff?.added?.length || 0) + (diff?.removed?.length || 0);
const hasCheckIn = !!checkInResult;
const hasModelChange = modelChanges > 0;
// 生成标签文本
let labelText = '';
if (hasCheckIn && hasModelChange) {
labelText = '签到 + 模型变更';
} else if (hasCheckIn) {
labelText = `签到${checkInResult.checkInSuccess ? '成功' : '失败'}`;
} else if (hasModelChange) {
labelText = modelChanges + ' 项模型变更';
}
htmlContent += `
🎯 ${siteName}
${labelText}
`;
// 添加签到结果(如果有)- 放在最前面
if (checkInResult) {
const { checkInSuccess, checkInMessage, checkInQuota, checkInError } = checkInResult;
const statusIcon = checkInSuccess ? '✅' : '❌';
const statusColor = checkInSuccess ? '#52c41a' : '#ff4d4f';
const statusBg = checkInSuccess ? '#f6ffed' : '#fff2f0';
const statusBorder = checkInSuccess ? '#b7eb8f' : '#ffccc7';
htmlContent += `
${statusIcon}
签到${checkInSuccess ? '成功' : '失败'}
${checkInMessage || (checkInSuccess ? '签到成功' : '签到失败')}
${checkInQuota ? `
💰 获得额度: ${checkInQuota}
` : ''}
${checkInError ? `
${checkInError}
` : ''}
`;
}
// 新增模型(只在有变更时显示)
if (diff && diff.added && diff.added.length > 0) {
htmlContent += `
➕
新增模型 (${diff.added.length})
`;
diff.added.slice(0, 20).forEach(model => {
htmlContent += `${model.id}`;
});
if (diff.added.length > 20) {
htmlContent += `... 还有 ${diff.added.length - 20} 个`;
}
htmlContent += `
`;
}
// 移除模型(只在有变更时显示)
if (diff && diff.removed && diff.removed.length > 0) {
htmlContent += `
➖
移除模型 (${diff.removed.length})
`;
diff.removed.slice(0, 20).forEach(model => {
htmlContent += `${model.id}`;
});
if (diff.removed.length > 20) {
htmlContent += `... 还有 ${diff.removed.length - 20} 个`;
}
htmlContent += `
`;
}
htmlContent += `
`;
});
// 添加失败站点部分
if (failedSites.length > 0) {
htmlContent += `
⚠️
检测失败的站点 (${failedSites.length})
以下站点在本次检测中出现错误,请检查站点配置或网络连接。
`;
failedSites.forEach((failedSite, index) => {
htmlContent += `
❌
${failedSite.siteName}
${failedSite.error}
`;
});
htmlContent += `
`;
}
htmlContent += `
本邮件由 AI 模型监测系统自动发送
🕔 ${new Date().toLocaleString('zh-CN')}
`;
debugLog('✅ 邮件内容构建完成');
// 准备邮件参数
let subject = `[AI模型监测] 定时检测报告`;
if (siteChanges.length > 0 && failedSites.length > 0) {
subject += ` - ${siteChanges.length}个站点发生变化,${failedSites.length}个站点失败`;
} else if (siteChanges.length > 0) {
subject += ` - ${siteChanges.length}个站点发生变化`;
} else if (failedSites.length > 0) {
subject += ` - ${failedSites.length}个站点检测失败`;
}
const emailParams = {
from: 'AI模型监测 ',
to: emails,
subject,
html: htmlContent
};
debugLog('📧 准备发送邮件:', {
from: emailParams.from,
to: emailParams.to,
subject: emailParams.subject,
htmlLength: htmlContent.length
});
// 发送邮件
debugLog('🚀 正在调用 Resend API...');
const result = await resend.emails.send(emailParams);
debugLog('🎉 聚合邮件发送成功!结果:', result);
const logMsg = failedSites.length > 0
? `聚合邮件发送成功: ${siteChanges.length} 个变更, ${failedSites.length} 个失败 -> ${emails.join(', ')}`
: `聚合邮件发送成功: ${siteChanges.length} 个站点 -> ${emails.join(', ')}`;
fastify?.log?.info(logMsg);
return result;
} catch (error) {
debugLog('💥 聚合邮件发送过程出错:', {
errorName: error.name,
errorMessage: error.message,
errorStack: error.stack?.split('\n').slice(0, 3)
});
fastify?.log?.error('聚合邮件通知失败', error);
console.error('[EMAIL] 聚合邮件最终错误:', error.message);
} finally {
debugLog(`=== 聚合邮件通知流程结束 ===`);
}
}
module.exports = { sendModelChangeNotification, sendAggregatedNotification };