实现分发器模块
- 添加分发器类型定义 (distributor.ts) - 实现分发器基类 (base.distributor.ts) - 实现邮件分发器 (email.distributor.ts) - 实现钉钉分发器 (dingtalk.distributor.ts) - 实现企业微信分发器 (wechat.distributor.ts) - 实现 Slack 分发器 (slack.distributor.ts) - 创建分发器工厂 (distributor.factory.ts) - 实现分发服务 (distributor.service.ts) - 安装 nodemailer 依赖 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
75c765af93
commit
5746676819
11 files changed
+562
No files matched your search
Generated
+21
@@ -15,6 +15,7 @@
|
|||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"fastify": "^5.7.4",
|
"fastify": "^5.7.4",
|
||||||
"node-cron": "^4.2.1",
|
"node-cron": "^4.2.1",
|
||||||
|
"nodemailer": "^8.0.0",
|
||||||
"openai": "^6.17.0",
|
"openai": "^6.17.0",
|
||||||
"playwright": "^1.58.1",
|
"playwright": "^1.58.1",
|
||||||
"prisma": "^5.22.0",
|
"prisma": "^5.22.0",
|
||||||
@@ -24,6 +25,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^25.2.0",
|
"@types/node": "^25.2.0",
|
||||||
"@types/node-cron": "^3.0.11",
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@types/nodemailer": "^7.0.9",
|
||||||
"nodemon": "^3.1.11",
|
"nodemon": "^3.1.11",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
@@ -811,6 +813,16 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/@types/triple-beam": {
|
||||||
"version": "1.3.5",
|
"version": "1.3.5",
|
||||||
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
|
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
|
||||||
@@ -1624,6 +1636,15 @@
|
|||||||
"node": ">=6.0.0"
|
"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": {
|
"node_modules/nodemon": {
|
||||||
"version": "3.1.11",
|
"version": "3.1.11",
|
||||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.11.tgz",
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"fastify": "^5.7.4",
|
"fastify": "^5.7.4",
|
||||||
"node-cron": "^4.2.1",
|
"node-cron": "^4.2.1",
|
||||||
|
"nodemailer": "^8.0.0",
|
||||||
"openai": "^6.17.0",
|
"openai": "^6.17.0",
|
||||||
"playwright": "^1.58.1",
|
"playwright": "^1.58.1",
|
||||||
"prisma": "^5.22.0",
|
"prisma": "^5.22.0",
|
||||||
@@ -31,6 +32,7 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^25.2.0",
|
"@types/node": "^25.2.0",
|
||||||
"@types/node-cron": "^3.0.11",
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@types/nodemailer": "^7.0.9",
|
||||||
"nodemon": "^3.1.11",
|
"nodemon": "^3.1.11",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3"
|
||||||
|
|||||||
@@ -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<DistributionResult>;
|
||||||
|
abstract validateConfig(): boolean;
|
||||||
|
abstract getType(): DistributorType;
|
||||||
|
}
|
||||||
@@ -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<DistributionResult> {
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<DistributionResult> {
|
||||||
|
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, '<h1>$1</h1>')
|
||||||
|
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||||
|
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
|
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
|
||||||
|
.replace(/\n/g, '<br>');
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
|
||||||
|
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
|
||||||
|
a { color: #3498db; }
|
||||||
|
.summary { background: #ecf0f1; padding: 15px; border-radius: 5px; margin: 20px 0; }
|
||||||
|
.button { display: inline-block; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 5px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="summary">
|
||||||
|
<p><strong>主题:</strong> ${summary.topicName}</p>
|
||||||
|
<p><strong>资讯数量:</strong> ${summary.articleCount} 条</p>
|
||||||
|
<p><strong>时间范围:</strong> ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}</p>
|
||||||
|
</div>
|
||||||
|
<a href="${summary.webUrl}" class="button">查看完整报告</a>
|
||||||
|
<hr>
|
||||||
|
<div>${htmlContent}</div>
|
||||||
|
<p style="color: #7f8c8d; font-size: 12px; margin-top: 40px;">本邮件由 News Aggregator 自动发送</p>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
@@ -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<DistributionResult> {
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<DistributionResult> {
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<void> {
|
||||||
|
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<void> {
|
||||||
|
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}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user