Files

951 lines
23 KiB
Markdown
Raw Permalink Normal View History

2026-02-03 12:11:57 +08:00
# 任务 07:分发器实现
## 任务概述
实现插件式分发器架构,支持邮件、钉钉、企业微信、Slack 等多种推送渠道。
## 前置条件
- 任务 01-06 已完成
- 报告生成服务已实现
## 任务目标
- 创建分发器基类接口
- 实现邮件分发器
- 实现钉钉分发器
- 实现企业微信分发器
- 实现 Slack 分发器
- 创建分发器工厂
- 实现分发服务
## 详细步骤
### 1. 安装依赖
```bash
cd backend
npm install nodemailer
npm install -D @types/nodemailer
```
### 2. 创建分发器类型定义
创建 `backend/src/types/distributor.ts`:
```typescript
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
}
```
### 3. 创建分发器基类
创建 `backend/src/distributors/base.distributor.ts`:
```typescript
import type { DistributorType, DistributorConfig, DistributionResult, ReportSummary } from '../types/distributor'
export abstract class BaseDistributor {
constructor(
protected config: DistributorConfig,
protected channelId: number
) {}
/**
* 执行分发
*/
abstract distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult>
/**
* 验证配置
*/
abstract validateConfig(): boolean
/**
* 获取分发器类型
*/
abstract getType(): DistributorType
}
```
### 4. 实现邮件分发器
创建 `backend/src/distributors/email.distributor.ts`:
```typescript
import { BaseDistributor } from './base.distributor'
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
import nodemailer from 'nodemailer'
import { logger } from '../utils/logger'
interface EmailConfig {
smtp: {
host: string
port: number
secure: boolean
auth: {
user: string
pass: string
}
}
from: string
to: string[]
}
export class EmailDistributor extends BaseDistributor {
private config: EmailConfig
constructor(config: EmailConfig, channelId: number) {
super(config, channelId)
this.config = config
}
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
try {
logger.info('邮件分发器开始发送', {
to: this.config.to,
title: summary.title,
})
// 创建邮件传输器
const transporter = nodemailer.createTransport(this.config.smtp)
// 构建邮件内容
const htmlContent = this.buildHtmlContent(summary, fullContent)
const textContent = this.buildTextContent(summary)
// 发送邮件
await transporter.sendMail({
from: this.config.from,
to: this.config.to.join(', '),
subject: summary.title,
text: textContent,
html: htmlContent,
})
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.config.smtp &&
this.config.smtp.host &&
this.config.smtp.auth &&
this.config.from &&
this.config.to &&
this.config.to.length > 0
)
}
getType(): DistributorType {
return 'email'
}
private buildHtmlContent(summary: ReportSummary, fullContent: string): string {
// 将 Markdown 转换为简单的 HTML(这里简化处理)
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, '<em>$1</em>')
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
.replace(/\n/g, '<br>')
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 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; }
h2 { color: #34495e; margin-top: 30px; }
h3 { color: #7f8c8d; }
a { color: #3498db; text-decoration: none; }
a:hover { text-decoration: underline; }
.summary {
background: #ecf0f1;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
}
.button {
display: inline-block;
padding: 10px 20px;
background: #3498db;
color: white !important;
text-decoration: none;
border-radius: 5px;
margin: 20px 0;
}
.footer {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #ecf0f1;
color: #7f8c8d;
font-size: 12px;
}
</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 class="content">
${htmlContent}
</div>
<div class="footer">
<p>本邮件由 News Aggregator 自动发送</p>
</div>
</body>
</html>
`
}
private buildTextContent(summary: ReportSummary): string {
return `
${summary.title}
主题: ${summary.topicName}
资讯数量: ${summary.articleCount} 条
时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
查看完整报告: ${summary.webUrl}
---
本邮件由 News Aggregator 自动发送
`.trim()
}
private formatDate(date: Date): string {
return date.toLocaleDateString('zh-CN')
}
}
```
### 5. 实现钉钉分发器
创建 `backend/src/distributors/dingtalk.distributor.ts`:
```typescript
import { BaseDistributor } from './base.distributor'
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
import crypto from 'crypto'
import { logger } from '../utils/logger'
interface DingtalkConfig {
webhook: string
secret?: string
}
export class DingtalkDistributor extends BaseDistributor {
private config: DingtalkConfig
constructor(config: DingtalkConfig, channelId: number) {
super(config, channelId)
this.config = config
}
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
try {
logger.info('钉钉分发器开始发送', { title: summary.title })
// 构建签名(如果有 secret)
let url = this.config.webhook
if (this.config.secret) {
const timestamp = Date.now()
const sign = this.generateSign(timestamp, this.config.secret)
url = `${url}&timestamp=${timestamp}&sign=${sign}`
}
// 构建消息内容
const message = this.buildMessage(summary)
// 发送请求
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
})
const result = await response.json()
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.config.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) {
const text = `# ${summary.title}
**主题**: ${summary.topicName}
**资讯数量**: ${summary.articleCount} 条
**时间范围**: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
[查看完整报告](${summary.webUrl})`
return {
msgtype: 'markdown',
markdown: {
title: summary.title,
text,
},
}
}
private formatDate(date: Date): string {
return date.toLocaleDateString('zh-CN')
}
}
```
### 6. 实现企业微信分发器
创建 `backend/src/distributors/wechat.distributor.ts`:
```typescript
import { BaseDistributor } from './base.distributor'
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
import { logger } from '../utils/logger'
interface WechatConfig {
webhook: string
}
export class WechatDistributor extends BaseDistributor {
private config: WechatConfig
constructor(config: WechatConfig, channelId: number) {
super(config, channelId)
this.config = config
}
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
try {
logger.info('企业微信分发器开始发送', { title: summary.title })
// 构建消息内容
const message = this.buildMessage(summary)
// 发送请求
const response = await fetch(this.config.webhook, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
})
const result = await response.json()
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.config.webhook
}
getType(): DistributorType {
return 'wechat'
}
private buildMessage(summary: ReportSummary) {
const content = `# ${summary.title}
> 主题: ${summary.topicName}
> 资讯数量: ${summary.articleCount} 条
> 时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
[查看完整报告](${summary.webUrl})`
return {
msgtype: 'markdown',
markdown: {
content,
},
}
}
private formatDate(date: Date): string {
return date.toLocaleDateString('zh-CN')
}
}
```
### 7. 实现 Slack 分发器
创建 `backend/src/distributors/slack.distributor.ts`:
```typescript
import { BaseDistributor } from './base.distributor'
import type { DistributorType, DistributionResult, ReportSummary } from '../types/distributor'
import { logger } from '../utils/logger'
interface SlackConfig {
webhook: string
}
export class SlackDistributor extends BaseDistributor {
private config: SlackConfig
constructor(config: SlackConfig, channelId: number) {
super(config, channelId)
this.config = config
}
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
try {
logger.info('Slack 分发器开始发送', { title: summary.title })
// 构建消息内容
const message = this.buildMessage(summary)
// 发送请求
const response = await fetch(this.config.webhook, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
})
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.config.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')
}
}
```
### 8. 创建分发器工厂
创建 `backend/src/distributors/distributor.factory.ts`:
```typescript
import type { 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 type { 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, channelId)
case 'dingtalk':
return new DingtalkDistributor(config, channelId)
case 'wechat':
return new WechatDistributor(config, channelId)
case 'slack':
return new SlackDistributor(config, channelId)
default:
throw new Error(`Unknown distributor type: ${type}`)
}
}
}
```
### 9. 创建分发服务
创建 `backend/src/services/distributor.service.ts`:
```typescript
import prisma from '../utils/prisma'
import { DistributorFactory } from '../distributors/distributor.factory'
import { logger } from '../utils/logger'
import type { ReportSummary } from '../types/distributor'
import { config } from '../config'
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 any,
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('报告分发完成')
}
/**
* 构建报告 Web URL
*/
private buildReportUrl(reportId: number): string {
const baseUrl = process.env.WEB_BASE_URL || `http://localhost:${config.app.port}`
return `${baseUrl}/reports/${reportId}`
}
}
```
### 10. 更新类型导出
更新 `backend/src/types/index.ts`:
```typescript
export * from './api'
export * from './collector'
export * from './llm'
export * from './distributor'
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis'
export type ReportStatus = 'pending' | 'generating' | 'completed' | 'failed'
export interface ProcessedContent {
content: string
mode: ProcessMode
articlesCount: number
}
export interface ReportGenerationOptions {
topicId: number
periodStart: Date
periodEnd: Date
manualTrigger?: boolean
}
```
### 11. 更新服务导出
更新 `backend/src/services/index.ts`:
```typescript
export * from './collector.service'
export * from './processor.service'
export * from './report.service'
export * from './distributor.service'
```
### 12. 创建分发器导出
创建 `backend/src/distributors/index.ts`:
```typescript
export * from './base.distributor'
export * from './email.distributor'
export * from './dingtalk.distributor'
export * from './wechat.distributor'
export * from './slack.distributor'
export * from './distributor.factory'
```
## 验证步骤
### 1. 配置测试渠道
使用 Prisma Studio 配置一个测试渠道:
```bash
npm run prisma:studio
```
在 `channels` 表中添加或更新记录,例如钉钉:
```json
{
"webhook": "https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN",
"secret": "YOUR_SECRET"
}
```
### 2. 创建测试脚本
创建 `backend/src/test-distributor.ts`:
```typescript
import { DistributorService } from './services/distributor.service'
import { ReportService } from './services/report.service'
import prisma from './utils/prisma'
async function test() {
const distributorService = new DistributorService()
const reportService = new ReportService()
// 查询一个已完成的报告
let report = await prisma.report.findFirst({
where: { status: 'completed' },
include: {
topic: {
include: {
topicChannels: {
include: {
channel: true,
},
},
},
},
},
})
// 如果没有报告,先生成一个
if (!report) {
console.log('没有找到报告,先生成一个...')
const topic = await prisma.topic.findFirst({
where: { enabled: true },
})
if (!topic) {
console.log('没有启用的主题')
return
}
const reportId = await reportService.generateReportForTopic(topic.id)
report = await prisma.report.findUnique({
where: { id: reportId },
include: {
topic: {
include: {
topicChannels: {
include: {
channel: true,
},
},
},
},
},
})
}
if (!report) {
console.log('无法获取报告')
return
}
console.log(`找到报告: ${report.title}`)
console.log(`关联渠道数量: ${report.topic.topicChannels.length}`)
// 测试分发
console.log('\n开始分发报告...')
await distributorService.distributeReportToAllChannels(report.id)
// 查看分发日志
const logs = await prisma.pushLog.findMany({
where: { reportId: report.id },
include: {
channel: true,
},
orderBy: { createdAt: 'desc' },
})
console.log('\n=== 分发日志 ===')
logs.forEach((log) => {
console.log(`- [${log.status}] ${log.channel.name}${log.errorMessage ? `: ${log.errorMessage}` : ''}`)
})
}
test()
.catch(console.error)
.finally(() => prisma.$disconnect())
```
### 3. 运行测试
```bash
npx tsx src/test-distributor.ts
```
### 4. 验证推送
检查对应的渠道是否收到消息:
- 邮件:检查邮箱
- 钉钉:检查钉钉群
- 企业微信:检查企业微信群
- Slack:检查 Slack 频道
### 5. 验证数据库
使用 Prisma Studio 查看 `push_logs` 表,确认有分发记录。
## 预期产物
- ✅ 分发器基类创建完成
- ✅ 邮件分发器实现完成
- ✅ 钉钉分发器实现完成
- ✅ 企业微信分发器实现完成
- ✅ Slack 分发器实现完成
- ✅ 分发器工厂创建完成
- ✅ 分发服务实现完成
- ✅ 测试通过
## 常见问题
### 问题 1:邮件发送失败
**解决方案**:
- 检查 SMTP 配置是否正确
- 检查邮箱密码(可能需要使用应用专用密码)
- 检查网络连接
### 问题 2:钉钉/企业微信消息发送失败
**解决方案**:
- 检查 webhook 地址是否正确
- 检查签名配置(钉钉)
- 查看错误日志
### 问题 3:消息格式不正确
**解决方案**:
- 检查各平台的消息格式要求
- 调整消息构建逻辑
## 下一步
完成本任务后,继续 [任务 08:定时任务](./08-scheduler.md)。