diff --git a/backend/package-lock.json b/backend/package-lock.json index de129eb..e977784 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -15,6 +15,7 @@ "dotenv": "^17.2.3", "fastify": "^5.7.4", "node-cron": "^4.2.1", + "nodemailer": "^8.0.0", "openai": "^6.17.0", "playwright": "^1.58.1", "prisma": "^5.22.0", @@ -24,6 +25,7 @@ "devDependencies": { "@types/node": "^25.2.0", "@types/node-cron": "^3.0.11", + "@types/nodemailer": "^7.0.9", "nodemon": "^3.1.11", "tsx": "^4.21.0", "typescript": "^5.9.3" @@ -811,6 +813,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/nodemailer": { + "version": "7.0.9", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-7.0.9.tgz", + "integrity": "sha512-vI8oF1M+8JvQhsId0Pc38BdUP2evenIIys7c7p+9OZXSPOH5c1dyINP1jT8xQ2xPuBUXmIC87s+91IZMDjH8Ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/triple-beam": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", @@ -1624,6 +1636,15 @@ "node": ">=6.0.0" } }, + "node_modules/nodemailer": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-8.0.0.tgz", + "integrity": "sha512-xvVJf/f0bzmNpnRIbhCp/IKxaHgJ6QynvUbLXzzMRPG3LDQr5oXkYuw4uDFyFYs8cge8agwwrJAXZsd4hhMquw==", + "license": "MIT-0", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/nodemon": { "version": "3.1.11", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.11.tgz", diff --git a/backend/package.json b/backend/package.json index 9c8e343..3a4968c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -22,6 +22,7 @@ "dotenv": "^17.2.3", "fastify": "^5.7.4", "node-cron": "^4.2.1", + "nodemailer": "^8.0.0", "openai": "^6.17.0", "playwright": "^1.58.1", "prisma": "^5.22.0", @@ -31,6 +32,7 @@ "devDependencies": { "@types/node": "^25.2.0", "@types/node-cron": "^3.0.11", + "@types/nodemailer": "^7.0.9", "nodemon": "^3.1.11", "tsx": "^4.21.0", "typescript": "^5.9.3" diff --git a/backend/src/distributors/base.distributor.ts b/backend/src/distributors/base.distributor.ts new file mode 100644 index 0000000..4b1b87c --- /dev/null +++ b/backend/src/distributors/base.distributor.ts @@ -0,0 +1,15 @@ +import { DistributorType, DistributorConfig, DistributionResult, ReportSummary } from '../types/distributor'; + +export abstract class BaseDistributor { + protected channelId: number; + protected config: DistributorConfig; + + constructor(config: DistributorConfig, channelId: number) { + this.config = config; + this.channelId = channelId; + } + + abstract distribute(summary: ReportSummary, fullContent: string): Promise; + abstract validateConfig(): boolean; + abstract getType(): DistributorType; +} diff --git a/backend/src/distributors/dingtalk.distributor.ts b/backend/src/distributors/dingtalk.distributor.ts new file mode 100644 index 0000000..23b328e --- /dev/null +++ b/backend/src/distributors/dingtalk.distributor.ts @@ -0,0 +1,82 @@ +import { BaseDistributor } from './base.distributor'; +import { DistributorType, DistributionResult, ReportSummary, DingtalkDistributorConfig } from '../types/distributor'; +import crypto from 'crypto'; +import logger from '../utils/logger'; + +export class DingtalkDistributor extends BaseDistributor { + private dingtalkConfig: DingtalkDistributorConfig; + + constructor(config: DingtalkDistributorConfig, channelId: number) { + super(config, channelId); + this.dingtalkConfig = config; + } + + async distribute(summary: ReportSummary, fullContent: string): Promise { + try { + logger.info('钉钉分发器开始发送', { title: summary.title }); + + let url = this.dingtalkConfig.webhook; + if (this.dingtalkConfig.secret) { + const timestamp = Date.now(); + const sign = this.generateSign(timestamp, this.dingtalkConfig.secret); + url = `${url}×tamp=${timestamp}&sign=${sign}`; + } + + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(this.buildMessage(summary)), + }); + + const result = (await response.json()) as { errcode: number; errmsg: string }; + + if (result.errcode !== 0) { + throw new Error(`钉钉 API 错误: ${result.errmsg}`); + } + + logger.info('钉钉消息发送成功'); + return { success: true }; + } catch (error) { + logger.error('钉钉消息发送失败', error); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + } + + validateConfig(): boolean { + return !!this.dingtalkConfig.webhook; + } + + getType(): DistributorType { + return 'dingtalk'; + } + + private generateSign(timestamp: number, secret: string): string { + const stringToSign = `${timestamp}\n${secret}`; + const hmac = crypto.createHmac('sha256', secret); + hmac.update(stringToSign); + return encodeURIComponent(hmac.digest('base64')); + } + + private buildMessage(summary: ReportSummary) { + return { + msgtype: 'markdown', + markdown: { + title: summary.title, + text: `# ${summary.title} + +**主题**: ${summary.topicName} +**资讯数量**: ${summary.articleCount} 条 +**时间范围**: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)} + +[查看完整报告](${summary.webUrl})`, + }, + }; + } + + private formatDate(date: Date): string { + return date.toLocaleDateString('zh-CN'); + } +} diff --git a/backend/src/distributors/distributor.factory.ts b/backend/src/distributors/distributor.factory.ts new file mode 100644 index 0000000..1cf0385 --- /dev/null +++ b/backend/src/distributors/distributor.factory.ts @@ -0,0 +1,27 @@ +import { BaseDistributor } from './base.distributor'; +import { EmailDistributor } from './email.distributor'; +import { DingtalkDistributor } from './dingtalk.distributor'; +import { WechatDistributor } from './wechat.distributor'; +import { SlackDistributor } from './slack.distributor'; +import { DistributorType, DistributorConfig } from '../types/distributor'; + +export class DistributorFactory { + static create( + type: DistributorType, + config: DistributorConfig, + channelId: number + ): BaseDistributor { + switch (type) { + case 'email': + return new EmailDistributor(config as any, channelId); + case 'dingtalk': + return new DingtalkDistributor(config as any, channelId); + case 'wechat': + return new WechatDistributor(config as any, channelId); + case 'slack': + return new SlackDistributor(config as any, channelId); + default: + throw new Error(`Unknown distributor type: ${type}`); + } + } +} diff --git a/backend/src/distributors/email.distributor.ts b/backend/src/distributors/email.distributor.ts new file mode 100644 index 0000000..a07a9bb --- /dev/null +++ b/backend/src/distributors/email.distributor.ts @@ -0,0 +1,100 @@ +import { BaseDistributor } from './base.distributor'; +import { DistributorType, DistributionResult, ReportSummary, EmailDistributorConfig } from '../types/distributor'; +import nodemailer from 'nodemailer'; +import logger from '../utils/logger'; + +export class EmailDistributor extends BaseDistributor { + private emailConfig: EmailDistributorConfig; + + constructor(config: EmailDistributorConfig, channelId: number) { + super(config, channelId); + this.emailConfig = config; + } + + async distribute(summary: ReportSummary, fullContent: string): Promise { + try { + logger.info('邮件分发器开始发送', { to: this.emailConfig.to, title: summary.title }); + + const transporter = nodemailer.createTransport(this.emailConfig.smtp); + + await transporter.sendMail({ + from: this.emailConfig.from, + to: this.emailConfig.to.join(', '), + subject: summary.title, + text: this.buildTextContent(summary), + html: this.buildHtmlContent(summary, fullContent), + }); + + logger.info('邮件发送成功'); + return { success: true }; + } catch (error) { + logger.error('邮件发送失败', error); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + } + + validateConfig(): boolean { + return !!( + this.emailConfig.smtp?.host && + this.emailConfig.smtp?.auth && + this.emailConfig.from && + this.emailConfig.to?.length > 0 + ); + } + + getType(): DistributorType { + return 'email'; + } + + private buildHtmlContent(summary: ReportSummary, fullContent: string): string { + const htmlContent = fullContent + .replace(/^# (.+)$/gm, '

$1

') + .replace(/^## (.+)$/gm, '

$1

') + .replace(/^### (.+)$/gm, '

$1

') + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/\[(.+?)\]\((.+?)\)/g, '$1') + .replace(/\n/g, '
'); + + return ` + + + + + + +
+

主题: ${summary.topicName}

+

资讯数量: ${summary.articleCount} 条

+

时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}

+
+ 查看完整报告 +
+
${htmlContent}
+

本邮件由 News Aggregator 自动发送

+ +`; + } + + private buildTextContent(summary: ReportSummary): string { + return `${summary.title} + +主题: ${summary.topicName} +资讯数量: ${summary.articleCount} 条 +时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)} + +查看完整报告: ${summary.webUrl}`; + } + + private formatDate(date: Date): string { + return date.toLocaleDateString('zh-CN'); + } +} diff --git a/backend/src/distributors/index.ts b/backend/src/distributors/index.ts new file mode 100644 index 0000000..7f00e97 --- /dev/null +++ b/backend/src/distributors/index.ts @@ -0,0 +1,6 @@ +export * from './base.distributor'; +export * from './email.distributor'; +export * from './dingtalk.distributor'; +export * from './wechat.distributor'; +export * from './slack.distributor'; +export * from './distributor.factory'; diff --git a/backend/src/distributors/slack.distributor.ts b/backend/src/distributors/slack.distributor.ts new file mode 100644 index 0000000..e6f07e5 --- /dev/null +++ b/backend/src/distributors/slack.distributor.ts @@ -0,0 +1,78 @@ +import { BaseDistributor } from './base.distributor'; +import { DistributorType, DistributionResult, ReportSummary, SlackDistributorConfig } from '../types/distributor'; +import logger from '../utils/logger'; + +export class SlackDistributor extends BaseDistributor { + private slackConfig: SlackDistributorConfig; + + constructor(config: SlackDistributorConfig, channelId: number) { + super(config, channelId); + this.slackConfig = config; + } + + async distribute(summary: ReportSummary, fullContent: string): Promise { + try { + logger.info('Slack 分发器开始发送', { title: summary.title }); + + const response = await fetch(this.slackConfig.webhook, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(this.buildMessage(summary)), + }); + + if (!response.ok) { + throw new Error(`Slack API 错误: ${response.statusText}`); + } + + logger.info('Slack 消息发送成功'); + return { success: true }; + } catch (error) { + logger.error('Slack 消息发送失败', error); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + } + + validateConfig(): boolean { + return !!this.slackConfig.webhook; + } + + getType(): DistributorType { + return 'slack'; + } + + private buildMessage(summary: ReportSummary) { + return { + blocks: [ + { + type: 'header', + text: { type: 'plain_text', text: summary.title }, + }, + { + type: 'section', + fields: [ + { type: 'mrkdwn', text: `*主题:*\n${summary.topicName}` }, + { type: 'mrkdwn', text: `*资讯数量:*\n${summary.articleCount} 条` }, + { type: 'mrkdwn', text: `*时间范围:*\n${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}` }, + ], + }, + { + type: 'actions', + elements: [ + { + type: 'button', + text: { type: 'plain_text', text: '查看完整报告' }, + url: summary.webUrl, + }, + ], + }, + ], + }; + } + + private formatDate(date: Date): string { + return date.toLocaleDateString('zh-CN'); + } +} diff --git a/backend/src/distributors/wechat.distributor.ts b/backend/src/distributors/wechat.distributor.ts new file mode 100644 index 0000000..bc648b2 --- /dev/null +++ b/backend/src/distributors/wechat.distributor.ts @@ -0,0 +1,66 @@ +import { BaseDistributor } from './base.distributor'; +import { DistributorType, DistributionResult, ReportSummary, WechatDistributorConfig } from '../types/distributor'; +import logger from '../utils/logger'; + +export class WechatDistributor extends BaseDistributor { + private wechatConfig: WechatDistributorConfig; + + constructor(config: WechatDistributorConfig, channelId: number) { + super(config, channelId); + this.wechatConfig = config; + } + + async distribute(summary: ReportSummary, fullContent: string): Promise { + try { + logger.info('企业微信分发器开始发送', { title: summary.title }); + + const response = await fetch(this.wechatConfig.webhook, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(this.buildMessage(summary)), + }); + + const result = (await response.json()) as { errcode: number; errmsg: string }; + + if (result.errcode !== 0) { + throw new Error(`企业微信 API 错误: ${result.errmsg}`); + } + + logger.info('企业微信消息发送成功'); + return { success: true }; + } catch (error) { + logger.error('企业微信消息发送失败', error); + return { + success: false, + error: error instanceof Error ? error.message : 'Unknown error', + }; + } + } + + validateConfig(): boolean { + return !!this.wechatConfig.webhook; + } + + getType(): DistributorType { + return 'wechat'; + } + + private buildMessage(summary: ReportSummary) { + return { + msgtype: 'markdown', + markdown: { + content: `# ${summary.title} + +> 主题: ${summary.topicName} +> 资讯数量: ${summary.articleCount} 条 +> 时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)} + +[查看完整报告](${summary.webUrl})`, + }, + }; + } + + private formatDate(date: Date): string { + return date.toLocaleDateString('zh-CN'); + } +} diff --git a/backend/src/services/distributor.service.ts b/backend/src/services/distributor.service.ts new file mode 100644 index 0000000..bfac168 --- /dev/null +++ b/backend/src/services/distributor.service.ts @@ -0,0 +1,113 @@ +import prisma from '../config/database'; +import { DistributorFactory } from '../distributors/distributor.factory'; +import { DistributorType, ReportSummary } from '../types/distributor'; +import { config } from '../config'; +import logger from '../utils/logger'; + +export class DistributorService { + /** + * 分发报告到指定渠道 + */ + async distributeReport(reportId: number, channelId: number): Promise { + let status: 'success' | 'failed' = 'success'; + let errorMessage: string | undefined; + + try { + const report = await prisma.report.findUnique({ + where: { id: reportId }, + include: { topic: true }, + }); + + if (!report) { + throw new Error(`Report ${reportId} not found`); + } + + const channel = await prisma.channel.findUnique({ + where: { id: channelId }, + }); + + if (!channel) { + throw new Error(`Channel ${channelId} not found`); + } + + if (!channel.enabled) { + logger.info(`渠道 ${channel.name} 已禁用,跳过分发`); + return; + } + + logger.info(`开始分发报告: ${report.title} -> ${channel.name}`); + + const distributor = DistributorFactory.create( + channel.type as DistributorType, + channel.config as any, + channel.id + ); + + if (!distributor.validateConfig()) { + throw new Error('Invalid distributor config'); + } + + const summary: ReportSummary = { + title: report.title, + topicName: report.topic.name, + articleCount: report.articleCount, + periodStart: report.periodStart, + periodEnd: report.periodEnd, + webUrl: this.buildReportUrl(reportId), + }; + + const result = await distributor.distribute(summary, report.content); + + if (!result.success) { + throw new Error(result.error || 'Distribution failed'); + } + + logger.info(`报告分发成功: ${channel.name}`); + } catch (error) { + status = 'failed'; + errorMessage = error instanceof Error ? error.message : 'Unknown error'; + logger.error('报告分发失败', { reportId, channelId, error: errorMessage }); + } finally { + await prisma.pushLog.create({ + data: { reportId, channelId, status, errorMessage }, + }); + } + } + + /** + * 分发报告到所有关联的渠道 + */ + async distributeReportToAllChannels(reportId: number): Promise { + const report = await prisma.report.findUnique({ + where: { id: reportId }, + include: { + topic: { + include: { + topicChannels: { include: { channel: true } }, + }, + }, + }, + }); + + if (!report) { + throw new Error(`Report ${reportId} not found`); + } + + const channels = report.topic.topicChannels + .map((tc) => tc.channel) + .filter((c) => c.enabled); + + logger.info(`开始分发报告到 ${channels.length} 个渠道`); + + for (const channel of channels) { + await this.distributeReport(reportId, channel.id); + } + + logger.info('报告分发完成'); + } + + private buildReportUrl(reportId: number): string { + const baseUrl = process.env.WEB_BASE_URL || `http://localhost:${config.port}`; + return `${baseUrl}/reports/${reportId}`; + } +} diff --git a/backend/src/types/distributor.ts b/backend/src/types/distributor.ts new file mode 100644 index 0000000..f09c71b --- /dev/null +++ b/backend/src/types/distributor.ts @@ -0,0 +1,52 @@ +// 分发器类型定义 + +export type DistributorType = 'email' | 'dingtalk' | 'wechat' | 'slack'; + +export interface DistributorConfig { + [key: string]: any; +} + +export interface DistributionResult { + success: boolean; + error?: string; +} + +export interface ReportSummary { + title: string; + topicName: string; + articleCount: number; + periodStart: Date; + periodEnd: Date; + webUrl: string; +} + +// 邮件配置 +export interface EmailDistributorConfig { + smtp: { + host: string; + port: number; + secure: boolean; + auth: { + user: string; + pass: string; + }; + }; + from: string; + to: string[]; +} + +// 钉钉配置 +export interface DingtalkDistributorConfig { + webhook: string; + secret?: string; +} + +// 企业微信配置 +export interface WechatDistributorConfig { + webhook: string; +} + +// Slack 配置 +export interface SlackDistributorConfig { + webhook: string; +}