feat: 支持 push

This commit is contained in:
richarjiang
2025-10-11 17:38:04 +08:00
parent 999fc7f793
commit 305a969912
30 changed files with 4582 additions and 1 deletions

View File

@@ -0,0 +1,301 @@
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as apn from '@parse/node-apn';
import * as fs from 'fs';
import * as path from 'path';
import { ApnsConfig, ApnsNotificationOptions } from './interfaces/apns-config.interface';
@Injectable()
export class ApnsProvider implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(ApnsProvider.name);
private provider: apn.Provider;
private multiProvider: apn.MultiProvider;
private config: ApnsConfig;
constructor(private readonly configService: ConfigService) {
this.config = this.buildConfig();
}
async onModuleInit() {
try {
await this.initializeProvider();
this.logger.log('APNs Provider initialized successfully');
} catch (error) {
this.logger.error('Failed to initialize APNs Provider', error);
throw error;
}
}
async onModuleDestroy() {
try {
this.shutdown();
this.logger.log('APNs Provider shutdown successfully');
} catch (error) {
this.logger.error('Error during APNs Provider shutdown', error);
}
}
/**
* 构建APNs配置
*/
private buildConfig(): ApnsConfig {
const keyId = this.configService.get<string>('APNS_KEY_ID');
const teamId = this.configService.get<string>('APNS_TEAM_ID');
const keyPath = this.configService.get<string>('APNS_KEY_PATH');
const bundleId = this.configService.get<string>('APNS_BUNDLE_ID');
const environment = this.configService.get<string>('APNS_ENVIRONMENT', 'sandbox');
const clientCount = this.configService.get<number>('APNS_CLIENT_COUNT', 2);
if (!keyId || !teamId || !keyPath || !bundleId) {
throw new Error('Missing required APNs configuration');
}
let key: string | Buffer;
try {
// 尝试读取密钥文件
if (fs.existsSync(keyPath)) {
key = fs.readFileSync(keyPath);
} else {
// 如果是直接的内容而不是文件路径
key = keyPath;
}
} catch (error) {
this.logger.error(`Failed to read APNs key file: ${keyPath}`, error);
throw new Error(`Invalid APNs key file: ${keyPath}`);
}
return {
token: {
key,
keyId,
teamId,
},
production: environment === 'production',
clientCount,
connectionRetryLimit: this.configService.get<number>('APNS_CONNECTION_RETRY_LIMIT', 3),
heartBeat: this.configService.get<number>('APNS_HEARTBEAT', 60000),
requestTimeout: this.configService.get<number>('APNS_REQUEST_TIMEOUT', 5000),
};
}
/**
* 初始化APNs连接
*/
private async initializeProvider(): Promise<void> {
try {
// 创建单个Provider
this.provider = new apn.Provider(this.config);
// 创建多Provider连接池
this.multiProvider = new apn.MultiProvider(this.config);
this.logger.log(`APNs Provider initialized with ${this.config.clientCount} clients`);
this.logger.log(`Environment: ${this.config.production ? 'Production' : 'Sandbox'}`);
} catch (error) {
this.logger.error('Failed to initialize APNs Provider', error);
throw error;
}
}
/**
* 发送单个通知
*/
async send(notification: apn.Notification, deviceTokens: string[]): Promise<apn.Results> {
try {
this.logger.debug(`Sending notification to ${deviceTokens.length} devices`);
const results = await this.provider.send(notification, deviceTokens);
this.logResults(results);
return results;
} catch (error) {
this.logger.error('Error sending notification', error);
throw error;
}
}
/**
* 批量发送通知
*/
async sendBatch(notifications: apn.Notification[], deviceTokens: string[]): Promise<apn.Results> {
try {
this.logger.debug(`Sending ${notifications.length} notifications to ${deviceTokens.length} devices`);
const results = await this.multiProvider.send(notifications, deviceTokens);
this.logResults(results);
return results;
} catch (error) {
this.logger.error('Error sending batch notifications', error);
throw error;
}
}
/**
* 管理推送通道
*/
async manageChannels(notification: apn.Notification, bundleId: string, action: string): Promise<any> {
try {
this.logger.debug(`Managing channels for bundle ${bundleId} with action ${action}`);
const results = await this.provider.manageChannels(notification, bundleId, action);
this.logger.log(`Channel management completed: ${JSON.stringify(results)}`);
return results;
} catch (error) {
this.logger.error('Error managing channels', error);
throw error;
}
}
/**
* 广播实时活动通知
*/
async broadcast(notification: apn.Notification, bundleId: string): Promise<any> {
try {
this.logger.debug(`Broadcasting to bundle ${bundleId}`);
const results = await this.provider.broadcast(notification, bundleId);
this.logger.log(`Broadcast completed: ${JSON.stringify(results)}`);
return results;
} catch (error) {
this.logger.error('Error broadcasting', error);
throw error;
}
}
/**
* 创建标准通知
*/
createNotification(options: {
title?: string;
body?: string;
payload?: any;
pushType?: string;
priority?: number;
expiry?: number;
collapseId?: string;
topic?: string;
sound?: string;
badge?: number;
mutableContent?: boolean;
contentAvailable?: boolean;
}): apn.Notification {
const notification = new apn.Notification();
// 设置基本内容
if (options.title) {
notification.title = options.title;
}
if (options.body) {
notification.body = options.body;
}
// 设置自定义负载
if (options.payload) {
notification.payload = options.payload;
}
// 设置推送类型
if (options.pushType) {
notification.pushType = options.pushType;
}
// 设置优先级
if (options.priority) {
notification.priority = options.priority;
}
// 设置过期时间
if (options.expiry) {
notification.expiry = options.expiry;
}
// 设置折叠ID
if (options.collapseId) {
notification.collapseId = options.collapseId;
}
// 设置主题
if (options.topic) {
notification.topic = options.topic;
}
// 设置声音
if (options.sound) {
notification.sound = options.sound;
}
// 设置徽章
if (options.badge) {
notification.badge = options.badge;
}
// 设置可变内容
if (options.mutableContent) {
notification.mutableContent = 1;
}
// 设置静默推送
if (options.contentAvailable) {
notification.contentAvailable = 1;
}
return notification;
}
/**
* 记录推送结果
*/
private logResults(results: apn.Results): void {
const { sent, failed } = results;
this.logger.log(`Push results: ${sent.length} sent, ${failed.length} failed`);
if (failed.length > 0) {
failed.forEach((failure) => {
if (failure.error) {
this.logger.error(`Push error for device ${failure.device}: ${failure.error.message}`);
} else {
this.logger.warn(`Push rejected for device ${failure.device}: ${failure.status} - ${JSON.stringify(failure.response)}`);
}
});
}
}
/**
* 关闭连接
*/
shutdown(): void {
try {
if (this.provider) {
this.provider.shutdown();
}
if (this.multiProvider) {
this.multiProvider.shutdown();
}
this.logger.log('APNs Provider connections closed');
} catch (error) {
this.logger.error('Error closing APNs Provider connections', error);
}
}
/**
* 获取Provider状态
*/
getStatus(): { connected: boolean; clientCount: number; environment: string } {
return {
connected: !!(this.provider || this.multiProvider),
clientCount: this.config.clientCount || 1,
environment: this.config.production ? 'production' : 'sandbox',
};
}
}

View File

@@ -0,0 +1,35 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsObject, IsOptional, IsEnum, IsNumber } from 'class-validator';
import { PushType } from '../enums/push-type.enum';
export class CreatePushTemplateDto {
@ApiProperty({ description: '模板键' })
@IsString()
@IsNotEmpty()
templateKey: string;
@ApiProperty({ description: '模板标题' })
@IsString()
@IsNotEmpty()
title: string;
@ApiProperty({ description: '模板内容' })
@IsString()
@IsNotEmpty()
body: string;
@ApiProperty({ description: '负载模板', required: false })
@IsObject()
@IsOptional()
payloadTemplate?: any;
@ApiProperty({ description: '推送类型', enum: PushType, required: false })
@IsEnum(PushType)
@IsOptional()
pushType?: PushType;
@ApiProperty({ description: '优先级', required: false })
@IsNumber()
@IsOptional()
priority?: number;
}

View File

@@ -0,0 +1,93 @@
import { ApiProperty } from '@nestjs/swagger';
import { ResponseCode } from '../../base.dto';
export class PushResult {
@ApiProperty({ description: '用户ID' })
userId: string;
@ApiProperty({ description: '设备令牌' })
deviceToken: string;
@ApiProperty({ description: '是否成功' })
success: boolean;
@ApiProperty({ description: '错误信息', required: false })
error?: string;
@ApiProperty({ description: 'APNs响应', required: false })
apnsResponse?: any;
}
export class PushResponseDto {
@ApiProperty({ description: '响应代码' })
code: ResponseCode;
@ApiProperty({ description: '响应消息' })
message: string;
@ApiProperty({ description: '推送结果' })
data: {
success: boolean;
sentCount: number;
failedCount: number;
results: PushResult[];
};
}
export class BatchPushResponseDto {
@ApiProperty({ description: '响应代码' })
code: ResponseCode;
@ApiProperty({ description: '响应消息' })
message: string;
@ApiProperty({ description: '批量推送结果' })
data: {
totalUsers: number;
totalTokens: number;
successCount: number;
failedCount: number;
results: PushResult[];
};
}
export class RegisterTokenResponseDto {
@ApiProperty({ description: '响应代码' })
code: ResponseCode;
@ApiProperty({ description: '响应消息' })
message: string;
@ApiProperty({ description: '注册结果' })
data: {
success: boolean;
tokenId: string;
};
}
export class UpdateTokenResponseDto {
@ApiProperty({ description: '响应代码' })
code: ResponseCode;
@ApiProperty({ description: '响应消息' })
message: string;
@ApiProperty({ description: '更新结果' })
data: {
success: boolean;
tokenId: string;
};
}
export class UnregisterTokenResponseDto {
@ApiProperty({ description: '响应代码' })
code: ResponseCode;
@ApiProperty({ description: '响应消息' })
message: string;
@ApiProperty({ description: '注销结果' })
data: {
success: boolean;
};
}

View File

@@ -0,0 +1,29 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsEnum, IsOptional } from 'class-validator';
import { DeviceType } from '../enums/device-type.enum';
export class RegisterDeviceTokenDto {
@ApiProperty({ description: '设备推送令牌' })
@IsString()
@IsNotEmpty()
deviceToken: string;
@ApiProperty({ description: '设备类型', enum: DeviceType })
@IsEnum(DeviceType)
deviceType: DeviceType;
@ApiProperty({ description: '应用版本', required: false })
@IsString()
@IsOptional()
appVersion?: string;
@ApiProperty({ description: '操作系统版本', required: false })
@IsString()
@IsOptional()
osVersion?: string;
@ApiProperty({ description: '设备名称', required: false })
@IsString()
@IsOptional()
deviceName?: string;
}

View File

@@ -0,0 +1,38 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsString, IsNotEmpty, IsObject, IsOptional } from 'class-validator';
export class SendPushByTemplateDto {
@ApiProperty({ description: '用户ID列表' })
@IsArray()
@IsString({ each: true })
userIds: string[];
@ApiProperty({ description: '模板键' })
@IsString()
@IsNotEmpty()
templateKey: string;
@ApiProperty({ description: '模板数据' })
@IsObject()
@IsNotEmpty()
data: any;
@ApiProperty({ description: '自定义数据', required: false })
@IsObject()
@IsOptional()
payload?: any;
@ApiProperty({ description: '折叠ID', required: false })
@IsString()
@IsOptional()
collapseId?: string;
@ApiProperty({ description: '声音', required: false })
@IsString()
@IsOptional()
sound?: string;
@ApiProperty({ description: '徽章数', required: false })
@IsOptional()
badge?: number;
}

View File

@@ -0,0 +1,63 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsArray, IsString, IsNotEmpty, IsObject, IsOptional, IsEnum, IsNumber } from 'class-validator';
import { PushType } from '../enums/push-type.enum';
export class SendPushNotificationDto {
@ApiProperty({ description: '用户ID列表' })
@IsArray()
@IsString({ each: true })
userIds: string[];
@ApiProperty({ description: '推送标题' })
@IsString()
@IsNotEmpty()
title: string;
@ApiProperty({ description: '推送内容' })
@IsString()
@IsNotEmpty()
body: string;
@ApiProperty({ description: '自定义数据', required: false })
@IsObject()
@IsOptional()
payload?: any;
@ApiProperty({ description: '推送类型', enum: PushType, required: false })
@IsEnum(PushType)
@IsOptional()
pushType?: PushType;
@ApiProperty({ description: '优先级', required: false })
@IsNumber()
@IsOptional()
priority?: number;
@ApiProperty({ description: '过期时间(秒)', required: false })
@IsNumber()
@IsOptional()
expiry?: number;
@ApiProperty({ description: '折叠ID', required: false })
@IsString()
@IsOptional()
collapseId?: string;
@ApiProperty({ description: '声音', required: false })
@IsString()
@IsOptional()
sound?: string;
@ApiProperty({ description: '徽章数', required: false })
@IsNumber()
@IsOptional()
badge?: number;
@ApiProperty({ description: '是否可变内容', required: false })
@IsOptional()
mutableContent?: boolean;
@ApiProperty({ description: '是否静默推送', required: false })
@IsOptional()
contentAvailable?: boolean;
}

View File

@@ -0,0 +1,29 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsOptional } from 'class-validator';
export class UpdateDeviceTokenDto {
@ApiProperty({ description: '当前设备推送令牌' })
@IsString()
@IsNotEmpty()
currentDeviceToken: string;
@ApiProperty({ description: '新的设备推送令牌' })
@IsString()
@IsNotEmpty()
newDeviceToken: string;
@ApiProperty({ description: '应用版本', required: false })
@IsString()
@IsOptional()
appVersion?: string;
@ApiProperty({ description: '操作系统版本', required: false })
@IsString()
@IsOptional()
osVersion?: string;
@ApiProperty({ description: '设备名称', required: false })
@IsString()
@IsOptional()
deviceName?: string;
}

View File

@@ -0,0 +1,35 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsOptional, IsObject, IsEnum, IsNumber, IsBoolean } from 'class-validator';
import { PushType } from '../enums/push-type.enum';
export class UpdatePushTemplateDto {
@ApiProperty({ description: '模板标题', required: false })
@IsString()
@IsOptional()
title?: string;
@ApiProperty({ description: '模板内容', required: false })
@IsString()
@IsOptional()
body?: string;
@ApiProperty({ description: '负载模板', required: false })
@IsObject()
@IsOptional()
payloadTemplate?: any;
@ApiProperty({ description: '推送类型', enum: PushType, required: false })
@IsEnum(PushType)
@IsOptional()
pushType?: PushType;
@ApiProperty({ description: '优先级', required: false })
@IsNumber()
@IsOptional()
priority?: number;
@ApiProperty({ description: '是否激活', required: false })
@IsBoolean()
@IsOptional()
isActive?: boolean;
}

View File

@@ -0,0 +1,4 @@
export enum DeviceType {
IOS = 'IOS',
ANDROID = 'ANDROID',
}

View File

@@ -0,0 +1,6 @@
export enum PushMessageStatus {
PENDING = 'PENDING',
SENT = 'SENT',
FAILED = 'FAILED',
EXPIRED = 'EXPIRED',
}

View File

@@ -0,0 +1,6 @@
export enum PushType {
ALERT = 'ALERT',
BACKGROUND = 'BACKGROUND',
VOIP = 'VOIP',
LIVEACTIVITY = 'LIVEACTIVITY',
}

View File

@@ -0,0 +1,25 @@
export interface ApnsConfig {
token: {
key: string | Buffer;
keyId: string;
teamId: string;
};
production: boolean;
clientCount?: number;
proxy?: {
host: string;
port: number;
};
connectionRetryLimit?: number;
heartBeat?: number;
requestTimeout?: number;
}
export interface ApnsNotificationOptions {
topic: string;
id?: string;
collapseId?: string;
priority?: number;
pushType?: string;
expiry?: number;
}

View File

@@ -0,0 +1,65 @@
import { PushType } from '../enums/push-type.enum';
export interface PushNotificationRequest {
userIds: string[];
title: string;
body: string;
payload?: any;
pushType?: PushType;
priority?: number;
expiry?: number;
collapseId?: string;
}
export interface PushNotificationByTemplateRequest {
userIds: string[];
templateKey: string;
data: any;
payload?: any;
}
export interface PushResult {
userId: string;
deviceToken: string;
success: boolean;
error?: string;
apnsResponse?: any;
}
export interface BatchPushResult {
totalUsers: number;
totalTokens: number;
successCount: number;
failedCount: number;
results: PushResult[];
}
export interface RenderedTemplate {
title: string;
body: string;
payload?: any;
pushType: PushType;
priority: number;
}
export interface PushStats {
totalSent: number;
totalFailed: number;
successRate: number;
averageDeliveryTime: number;
errorBreakdown: Record<string, number>;
}
export interface QueryOptions {
limit?: number;
offset?: number;
startDate?: Date;
endDate?: Date;
status?: string;
messageType?: string;
}
export interface TimeRange {
startDate: Date;
endDate: Date;
}

View File

@@ -0,0 +1,147 @@
import { Column, Model, Table, DataType, Index } from 'sequelize-typescript';
import { PushType } from '../enums/push-type.enum';
import { PushMessageStatus } from '../enums/push-message-status.enum';
@Table({
tableName: 't_push_messages',
underscored: true,
indexes: [
{
name: 'idx_user_id',
fields: ['user_id'],
},
{
name: 'idx_status',
fields: ['status'],
},
{
name: 'idx_created_at',
fields: ['created_at'],
},
{
name: 'idx_message_type',
fields: ['message_type'],
},
],
})
export class PushMessage extends Model {
@Column({
type: DataType.UUID,
defaultValue: DataType.UUIDV4,
primaryKey: true,
})
declare id: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '用户ID',
})
declare userId: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '设备推送令牌',
})
declare deviceToken: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '消息类型',
})
declare messageType: string;
@Column({
type: DataType.STRING,
allowNull: true,
comment: '推送标题',
})
declare title?: string;
@Column({
type: DataType.TEXT,
allowNull: true,
comment: '推送内容',
})
declare body?: string;
@Column({
type: DataType.JSON,
allowNull: true,
comment: '自定义负载数据',
})
declare payload?: any;
@Column({
type: DataType.ENUM(...Object.values(PushType)),
allowNull: false,
defaultValue: PushType.ALERT,
comment: '推送类型',
})
declare pushType: PushType;
@Column({
type: DataType.TINYINT,
allowNull: false,
defaultValue: 10,
comment: '优先级',
})
declare priority: number;
@Column({
type: DataType.DATE,
allowNull: true,
comment: '过期时间',
})
declare expiry?: Date;
@Column({
type: DataType.STRING,
allowNull: true,
comment: '折叠ID',
})
declare collapseId?: string;
@Column({
type: DataType.ENUM(...Object.values(PushMessageStatus)),
allowNull: false,
defaultValue: PushMessageStatus.PENDING,
comment: '推送状态',
})
declare status: PushMessageStatus;
@Column({
type: DataType.JSON,
allowNull: true,
comment: 'APNs响应数据',
})
declare apnsResponse?: any;
@Column({
type: DataType.TEXT,
allowNull: true,
comment: '错误信息',
})
declare errorMessage?: string;
@Column({
type: DataType.DATE,
allowNull: true,
comment: '发送时间',
})
declare sentAt?: Date;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare createdAt: Date;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare updatedAt: Date;
}

View File

@@ -0,0 +1,95 @@
import { Column, Model, Table, DataType, Index, Unique } from 'sequelize-typescript';
import { PushType } from '../enums/push-type.enum';
@Table({
tableName: 't_push_templates',
underscored: true,
indexes: [
{
name: 'idx_template_key',
fields: ['template_key'],
unique: true,
},
{
name: 'idx_is_active',
fields: ['is_active'],
},
],
})
export class PushTemplate extends Model {
@Column({
type: DataType.UUID,
defaultValue: DataType.UUIDV4,
primaryKey: true,
})
declare id: string;
@Column({
type: DataType.STRING,
allowNull: false,
unique: true,
field: 'template_key',
comment: '模板键',
})
declare templateKey: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '模板标题',
})
declare title: string;
@Column({
type: DataType.TEXT,
allowNull: false,
comment: '模板内容',
})
declare body: string;
@Column({
type: DataType.JSON,
allowNull: true,
field: 'payload_template',
comment: '负载模板',
})
declare payloadTemplate?: any;
@Column({
type: DataType.ENUM(...Object.values(PushType)),
allowNull: false,
defaultValue: PushType.ALERT,
field: 'push_type',
comment: '推送类型',
})
declare pushType: PushType;
@Column({
type: DataType.TINYINT,
allowNull: false,
defaultValue: 10,
comment: '优先级',
})
declare priority: number;
@Column({
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: true,
field: 'is_active',
comment: '是否激活',
})
declare isActive: boolean;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare createdAt: Date;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare updatedAt: Date;
}

View File

@@ -0,0 +1,100 @@
import { Column, Model, Table, DataType, Index, Unique } from 'sequelize-typescript';
import { DeviceType } from '../enums/device-type.enum';
@Table({
tableName: 't_user_push_tokens',
underscored: true,
indexes: [
{
name: 'idx_user_id',
fields: ['user_id'],
},
{
name: 'idx_device_token',
fields: ['device_token'],
},
{
name: 'idx_user_device',
fields: ['user_id', 'device_token'],
unique: true,
},
],
})
export class UserPushToken extends Model {
@Column({
type: DataType.UUID,
defaultValue: DataType.UUIDV4,
primaryKey: true,
})
declare id: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '用户ID',
})
declare userId: string;
@Column({
type: DataType.STRING,
allowNull: false,
comment: '设备推送令牌',
})
declare deviceToken: string;
@Column({
type: DataType.ENUM(...Object.values(DeviceType)),
allowNull: false,
defaultValue: DeviceType.IOS,
comment: '设备类型',
})
declare deviceType: DeviceType;
@Column({
type: DataType.STRING,
allowNull: true,
comment: '应用版本',
})
declare appVersion?: string;
@Column({
type: DataType.STRING,
allowNull: true,
comment: '操作系统版本',
})
declare osVersion?: string;
@Column({
type: DataType.STRING,
allowNull: true,
comment: '设备名称',
})
declare deviceName?: string;
@Column({
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: true,
comment: '是否激活',
})
declare isActive: boolean;
@Column({
type: DataType.DATE,
allowNull: true,
comment: '最后使用时间',
})
declare lastUsedAt?: Date;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare createdAt: Date;
@Column({
type: DataType.DATE,
defaultValue: DataType.NOW,
})
declare updatedAt: Date;
}

View File

@@ -0,0 +1,387 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from 'sequelize';
import { PushMessage } from './models/push-message.model';
import { PushMessageStatus } from './enums/push-message-status.enum';
import { PushStats, QueryOptions, TimeRange } from './interfaces/push-notification.interface';
export interface CreatePushMessageDto {
userId: string;
deviceToken: string;
messageType: string;
title?: string;
body?: string;
payload?: any;
pushType?: string;
priority?: number;
expiry?: Date;
collapseId?: string;
}
@Injectable()
export class PushMessageService {
private readonly logger = new Logger(PushMessageService.name);
constructor(
@InjectModel(PushMessage)
private readonly messageModel: typeof PushMessage,
) { }
/**
* 创建推送消息记录
*/
async createMessage(messageData: CreatePushMessageDto): Promise<PushMessage> {
try {
this.logger.log(`Creating push message for user ${messageData.userId}`);
const message = await this.messageModel.create({
userId: messageData.userId,
deviceToken: messageData.deviceToken,
messageType: messageData.messageType,
title: messageData.title,
body: messageData.body,
payload: messageData.payload,
pushType: messageData.pushType,
priority: messageData.priority || 10,
expiry: messageData.expiry,
collapseId: messageData.collapseId,
status: PushMessageStatus.PENDING,
});
this.logger.log(`Successfully created push message with ID: ${message.id}`);
return message;
} catch (error) {
this.logger.error(`Failed to create push message: ${error.message}`, error);
throw error;
}
}
/**
* 更新消息状态
*/
async updateMessageStatus(id: string, status: PushMessageStatus, response?: any, errorMessage?: string): Promise<void> {
try {
this.logger.log(`Updating push message status to ${status} for ID: ${id}`);
const updateData: any = {
status,
};
if (status === PushMessageStatus.SENT) {
updateData.sentAt = new Date();
}
if (response) {
updateData.apnsResponse = response;
}
if (errorMessage) {
updateData.errorMessage = errorMessage;
}
await this.messageModel.update(updateData, {
where: {
id,
},
});
this.logger.log(`Successfully updated push message status for ID: ${id}`);
} catch (error) {
this.logger.error(`Failed to update push message status: ${error.message}`, error);
throw error;
}
}
/**
* 批量更新消息状态
*/
async updateMessageStatusBatch(ids: string[], status: PushMessageStatus, response?: any, errorMessage?: string): Promise<void> {
try {
this.logger.log(`Batch updating ${ids.length} push messages to status: ${status}`);
const updateData: any = {
status,
};
if (status === PushMessageStatus.SENT) {
updateData.sentAt = new Date();
}
if (response) {
updateData.apnsResponse = response;
}
if (errorMessage) {
updateData.errorMessage = errorMessage;
}
await this.messageModel.update(updateData, {
where: {
id: {
[Op.in]: ids,
},
},
});
this.logger.log(`Successfully batch updated ${ids.length} push messages`);
} catch (error) {
this.logger.error(`Failed to batch update push messages: ${error.message}`, error);
throw error;
}
}
/**
* 获取消息历史
*/
async getMessageHistory(userId: string, options: QueryOptions = {}): Promise<PushMessage[]> {
try {
const whereClause: any = {
userId,
};
if (options.status) {
whereClause.status = options.status;
}
if (options.messageType) {
whereClause.messageType = options.messageType;
}
if (options.startDate || options.endDate) {
whereClause.createdAt = {};
if (options.startDate) {
whereClause.createdAt[Op.gte] = options.startDate;
}
if (options.endDate) {
whereClause.createdAt[Op.lte] = options.endDate;
}
}
const messages = await this.messageModel.findAll({
where: whereClause,
order: [['createdAt', 'DESC']],
limit: options.limit,
offset: options.offset,
});
this.logger.log(`Found ${messages.length} messages for user ${userId}`);
return messages;
} catch (error) {
this.logger.error(`Failed to get message history: ${error.message}`, error);
throw error;
}
}
/**
* 获取消息统计
*/
async getMessageStats(userId?: string, timeRange?: TimeRange): Promise<PushStats> {
try {
const whereClause: any = {};
if (userId) {
whereClause.userId = userId;
}
if (timeRange) {
whereClause.createdAt = {
[Op.between]: [timeRange.startDate, timeRange.endDate],
};
}
const totalSent = await this.messageModel.count({
where: {
...whereClause,
status: PushMessageStatus.SENT,
},
});
const totalFailed = await this.messageModel.count({
where: {
...whereClause,
status: PushMessageStatus.FAILED,
},
});
const total = totalSent + totalFailed;
const successRate = total > 0 ? (totalSent / total) * 100 : 0;
// 获取错误分布
const errorMessages = await this.messageModel.findAll({
where: {
...whereClause,
status: PushMessageStatus.FAILED,
errorMessage: {
[Op.not]: null,
},
},
attributes: ['errorMessage'],
});
const errorBreakdown: Record<string, number> = {};
errorMessages.forEach((message) => {
if (message.errorMessage) {
const errorKey = this.categorizeError(message.errorMessage);
errorBreakdown[errorKey] = (errorBreakdown[errorKey] || 0) + 1;
}
});
// 计算平均发送时间(简化版本)
const averageDeliveryTime = await this.calculateAverageDeliveryTime(whereClause);
const stats: PushStats = {
totalSent,
totalFailed,
successRate,
averageDeliveryTime,
errorBreakdown,
};
this.logger.log(`Generated message stats: ${JSON.stringify(stats)}`);
return stats;
} catch (error) {
this.logger.error(`Failed to get message stats: ${error.message}`, error);
throw error;
}
}
/**
* 清理过期消息
*/
async cleanupExpiredMessages(): Promise<number> {
try {
this.logger.log('Starting cleanup of expired messages');
// 清理30天前的消息
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const result = await this.messageModel.destroy({
where: {
createdAt: {
[Op.lt]: thirtyDaysAgo,
},
},
});
this.logger.log(`Cleaned up ${result} expired messages`);
return result;
} catch (error) {
this.logger.error(`Failed to cleanup expired messages: ${error.message}`, error);
throw error;
}
}
/**
* 获取待发送的消息
*/
async getPendingMessages(limit: number = 100): Promise<PushMessage[]> {
try {
const messages = await this.messageModel.findAll({
where: {
status: PushMessageStatus.PENDING,
[Op.or]: [
{
expiry: {
[Op.or]: [
{ [Op.is]: null },
{ [Op.gt]: new Date() },
],
},
},
],
},
order: [['priority', 'DESC'], ['createdAt', 'ASC']],
limit,
});
return messages;
} catch (error) {
this.logger.error(`Failed to get pending messages: ${error.message}`, error);
throw error;
}
}
/**
* 根据设备令牌获取待发送消息
*/
async getPendingMessagesByDeviceToken(deviceToken: string): Promise<PushMessage[]> {
try {
const messages = await this.messageModel.findAll({
where: {
deviceToken,
status: PushMessageStatus.PENDING,
[Op.or]: [
{
expiry: {
[Op.or]: [
{ [Op.is]: null },
{ [Op.gt]: new Date() },
],
},
},
],
},
order: [['priority', 'DESC'], ['createdAt', 'ASC']],
});
return messages;
} catch (error) {
this.logger.error(`Failed to get pending messages by device token: ${error.message}`, error);
throw error;
}
}
/**
* 分类错误信息
*/
private categorizeError(errorMessage: string): string {
if (errorMessage.includes('Unregistered') || errorMessage.includes('BadDeviceToken')) {
return 'Invalid Token';
} else if (errorMessage.includes('DeviceTokenNotForTopic')) {
return 'Topic Mismatch';
} else if (errorMessage.includes('TooManyRequests')) {
return 'Rate Limit';
} else if (errorMessage.includes('InternalServerError')) {
return 'Server Error';
} else if (errorMessage.includes('timeout') || errorMessage.includes('Timeout')) {
return 'Timeout';
} else {
return 'Other';
}
}
/**
* 计算平均发送时间
*/
private async calculateAverageDeliveryTime(whereClause: any): Promise<number> {
try {
const messages = await this.messageModel.findAll({
where: {
...whereClause,
status: PushMessageStatus.SENT,
sentAt: {
[Op.not]: null,
},
},
attributes: ['createdAt', 'sentAt'],
});
if (messages.length === 0) {
return 0;
}
const totalDeliveryTime = messages.reduce((sum, message) => {
if (message.sentAt && message.createdAt) {
return sum + (message.sentAt.getTime() - message.createdAt.getTime());
}
return sum;
}, 0);
return totalDeliveryTime / messages.length;
} catch (error) {
this.logger.error(`Failed to calculate average delivery time: ${error.message}`, error);
return 0;
}
}
}

View File

@@ -0,0 +1,85 @@
import { Controller, Post, Put, Delete, Body, Param, Get, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { PushNotificationsService } from './push-notifications.service';
import { RegisterDeviceTokenDto } from './dto/register-device-token.dto';
import { UpdateDeviceTokenDto } from './dto/update-device-token.dto';
import { SendPushNotificationDto } from './dto/send-push-notification.dto';
import { SendPushByTemplateDto } from './dto/send-push-by-template.dto';
import { PushResponseDto, BatchPushResponseDto, RegisterTokenResponseDto, UpdateTokenResponseDto, UnregisterTokenResponseDto } from './dto/push-response.dto';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { AccessTokenPayload } from '../users/services/apple-auth.service';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { Public } from '../common/decorators/public.decorator';
@ApiTags('推送通知')
@Controller('push-notifications')
@UseGuards(JwtAuthGuard)
export class PushNotificationsController {
constructor(private readonly pushNotificationsService: PushNotificationsService) { }
@Post('register-token')
@ApiOperation({ summary: '注册设备推送令牌' })
@ApiResponse({ status: 200, description: '注册成功', type: RegisterTokenResponseDto })
async registerToken(
@CurrentUser() user: AccessTokenPayload,
@Body() registerTokenDto: RegisterDeviceTokenDto,
): Promise<RegisterTokenResponseDto> {
return this.pushNotificationsService.registerToken(user.sub, registerTokenDto);
}
@Put('update-token')
@ApiOperation({ summary: '更新设备推送令牌' })
@ApiResponse({ status: 200, description: '更新成功', type: UpdateTokenResponseDto })
async updateToken(
@CurrentUser() user: AccessTokenPayload,
@Body() updateTokenDto: UpdateDeviceTokenDto,
): Promise<UpdateTokenResponseDto> {
return this.pushNotificationsService.updateToken(user.sub, updateTokenDto);
}
@Delete('unregister-token')
@ApiOperation({ summary: '注销设备推送令牌' })
@ApiResponse({ status: 200, description: '注销成功', type: UnregisterTokenResponseDto })
async unregisterToken(
@CurrentUser() user: AccessTokenPayload,
@Body() body: { deviceToken: string },
): Promise<UnregisterTokenResponseDto> {
return this.pushNotificationsService.unregisterToken(user.sub, body.deviceToken);
}
@Post('send')
@ApiOperation({ summary: '发送推送通知' })
@ApiResponse({ status: 200, description: '发送成功', type: PushResponseDto })
async sendNotification(
@Body() sendNotificationDto: SendPushNotificationDto,
): Promise<PushResponseDto> {
return this.pushNotificationsService.sendNotification(sendNotificationDto);
}
@Post('send-by-template')
@ApiOperation({ summary: '使用模板发送推送' })
@ApiResponse({ status: 200, description: '发送成功', type: PushResponseDto })
async sendNotificationByTemplate(
@Body() sendByTemplateDto: SendPushByTemplateDto,
): Promise<PushResponseDto> {
return this.pushNotificationsService.sendNotificationByTemplate(sendByTemplateDto);
}
@Post('send-batch')
@ApiOperation({ summary: '批量发送推送' })
@ApiResponse({ status: 200, description: '发送成功', type: BatchPushResponseDto })
async sendBatchNotifications(
@Body() sendBatchDto: SendPushNotificationDto,
): Promise<BatchPushResponseDto> {
return this.pushNotificationsService.sendBatchNotifications(sendBatchDto);
}
@Post('send-silent')
@ApiOperation({ summary: '发送静默推送' })
@ApiResponse({ status: 200, description: '发送成功', type: PushResponseDto })
async sendSilentNotification(
@Body() body: { userId: string; payload: any },
): Promise<PushResponseDto> {
return this.pushNotificationsService.sendSilentNotification(body.userId, body.payload);
}
}

View File

@@ -0,0 +1,45 @@
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { PushNotificationsController } from './push-notifications.controller';
import { PushTemplateController } from './push-template.controller';
import { PushNotificationsService } from './push-notifications.service';
import { ApnsProvider } from './apns.provider';
import { PushTokenService } from './push-token.service';
import { PushTemplateService } from './push-template.service';
import { PushMessageService } from './push-message.service';
import { UserPushToken } from './models/user-push-token.model';
import { PushMessage } from './models/push-message.model';
import { PushTemplate } from './models/push-template.model';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from '../database/database.module';
@Module({
imports: [
ConfigModule,
DatabaseModule,
SequelizeModule.forFeature([
UserPushToken,
PushMessage,
PushTemplate,
]),
],
controllers: [
PushNotificationsController,
PushTemplateController,
],
providers: [
ApnsProvider,
PushNotificationsService,
PushTokenService,
PushTemplateService,
PushMessageService,
],
exports: [
ApnsProvider,
PushNotificationsService,
PushTokenService,
PushTemplateService,
PushMessageService,
],
})
export class PushNotificationsModule { }

View File

@@ -0,0 +1,502 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ApnsProvider } from './apns.provider';
import { PushTokenService } from './push-token.service';
import { PushTemplateService } from './push-template.service';
import { PushMessageService, CreatePushMessageDto } from './push-message.service';
import { SendPushNotificationDto } from './dto/send-push-notification.dto';
import { SendPushByTemplateDto } from './dto/send-push-by-template.dto';
import { PushResult, BatchPushResult } from './interfaces/push-notification.interface';
import { PushResponseDto, BatchPushResponseDto } from './dto/push-response.dto';
import { ResponseCode } from '../base.dto';
import { PushType } from './enums/push-type.enum';
import { PushMessageStatus } from './enums/push-message-status.enum';
@Injectable()
export class PushNotificationsService {
private readonly logger = new Logger(PushNotificationsService.name);
private readonly bundleId: string;
constructor(
private readonly apnsProvider: ApnsProvider,
private readonly pushTokenService: PushTokenService,
private readonly pushTemplateService: PushTemplateService,
private readonly pushMessageService: PushMessageService,
private readonly configService: ConfigService,
) {
this.bundleId = this.configService.get<string>('APNS_BUNDLE_ID') || '';
}
/**
* 发送单个推送通知
*/
async sendNotification(notificationData: SendPushNotificationDto): Promise<PushResponseDto> {
try {
this.logger.log(`Sending push notification to ${notificationData.userIds.length} users`);
const results: PushResult[] = [];
let sentCount = 0;
let failedCount = 0;
// 获取所有用户的设备令牌
const userTokensMap = await this.pushTokenService.getDeviceTokensByUserIds(notificationData.userIds);
// 为每个用户创建消息记录并发送推送
for (const userId of notificationData.userIds) {
const deviceTokens = userTokensMap.get(userId) || [];
if (deviceTokens.length === 0) {
this.logger.warn(`No active device tokens found for user ${userId}`);
results.push({
userId,
deviceToken: '',
success: false,
error: 'No active device tokens found',
});
failedCount++;
continue;
}
// 为每个设备令牌创建消息记录
for (const deviceToken of deviceTokens) {
try {
// 创建消息记录
const messageData: CreatePushMessageDto = {
userId,
deviceToken,
messageType: 'manual',
title: notificationData.title,
body: notificationData.body,
payload: notificationData.payload,
pushType: notificationData.pushType,
priority: notificationData.priority,
expiry: notificationData.expiry ? new Date(Date.now() + notificationData.expiry * 1000) : undefined,
collapseId: notificationData.collapseId,
};
const message = await this.pushMessageService.createMessage(messageData);
// 创建APNs通知
const apnsNotification = this.apnsProvider.createNotification({
title: notificationData.title,
body: notificationData.body,
payload: notificationData.payload,
pushType: notificationData.pushType,
priority: notificationData.priority,
expiry: notificationData.expiry,
collapseId: notificationData.collapseId,
topic: this.bundleId,
sound: notificationData.sound,
badge: notificationData.badge,
mutableContent: notificationData.mutableContent,
contentAvailable: notificationData.contentAvailable,
});
// 发送推送
const apnsResults = await this.apnsProvider.send(apnsNotification, [deviceToken]);
// 处理结果
if (apnsResults.sent.length > 0) {
await this.pushMessageService.updateMessageStatus(message.id, PushMessageStatus.SENT, apnsResults);
await this.pushTokenService.updateLastUsedTime(deviceToken);
results.push({
userId,
deviceToken,
success: true,
apnsResponse: apnsResults,
});
sentCount++;
} else {
const failure = apnsResults.failed[0];
const errorMessage = failure.error ? failure.error.message : `APNs Error: ${failure.status}`;
await this.pushMessageService.updateMessageStatus(
message.id,
PushMessageStatus.FAILED,
failure.response,
errorMessage
);
// 如果是无效令牌,停用该令牌
if (failure.status === '410' || failure.response?.reason === 'Unregistered') {
await this.pushTokenService.unregisterToken(userId, deviceToken);
}
results.push({
userId,
deviceToken,
success: false,
error: errorMessage,
apnsResponse: failure.response,
});
failedCount++;
}
} catch (error) {
this.logger.error(`Failed to send push to user ${userId}, device ${deviceToken}: ${error.message}`, error);
results.push({
userId,
deviceToken,
success: false,
error: error.message,
});
failedCount++;
}
}
}
const success = failedCount === 0;
return {
code: success ? ResponseCode.SUCCESS : ResponseCode.ERROR,
message: success ? '推送发送成功' : '部分推送发送失败',
data: {
success,
sentCount,
failedCount,
results,
},
};
} catch (error) {
this.logger.error(`Failed to send push notification: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `推送发送失败: ${error.message}`,
data: {
success: false,
sentCount: 0,
failedCount: notificationData.userIds.length,
results: [],
},
};
}
}
/**
* 使用模板发送推送通知
*/
async sendNotificationByTemplate(templateData: SendPushByTemplateDto): Promise<PushResponseDto> {
try {
this.logger.log(`Sending push notification using template: ${templateData.templateKey}`);
// 渲染模板
const renderedTemplate = await this.pushTemplateService.renderTemplate(
templateData.templateKey,
templateData.data
);
// 构建推送数据
const notificationData: SendPushNotificationDto = {
userIds: templateData.userIds,
title: renderedTemplate.title,
body: renderedTemplate.body,
payload: { ...renderedTemplate.payload, ...templateData.payload },
pushType: renderedTemplate.pushType,
priority: renderedTemplate.priority,
collapseId: templateData.collapseId,
sound: templateData.sound,
badge: templateData.badge,
};
// 发送推送
return this.sendNotification(notificationData);
} catch (error) {
this.logger.error(`Failed to send push notification by template: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `模板推送发送失败: ${error.message}`,
data: {
success: false,
sentCount: 0,
failedCount: templateData.userIds.length,
results: [],
},
};
}
}
/**
* 批量发送推送通知
*/
async sendBatchNotifications(notificationData: SendPushNotificationDto): Promise<BatchPushResponseDto> {
try {
this.logger.log(`Sending batch push notification to ${notificationData.userIds.length} users`);
const results: PushResult[] = [];
let totalUsers = notificationData.userIds.length;
let totalTokens = 0;
let successCount = 0;
let failedCount = 0;
// 获取所有用户的设备令牌
const userTokensMap = await this.pushTokenService.getDeviceTokensByUserIds(notificationData.userIds);
// 统计总令牌数
for (const tokens of userTokensMap.values()) {
totalTokens += tokens.length;
}
// 创建APNs通知
const apnsNotification = this.apnsProvider.createNotification({
title: notificationData.title,
body: notificationData.body,
payload: notificationData.payload,
pushType: notificationData.pushType,
priority: notificationData.priority,
expiry: notificationData.expiry,
collapseId: notificationData.collapseId,
topic: this.bundleId,
sound: notificationData.sound,
badge: notificationData.badge,
mutableContent: notificationData.mutableContent,
contentAvailable: notificationData.contentAvailable,
});
// 批量发送推送
const allDeviceTokens = Array.from(userTokensMap.values()).flat();
if (allDeviceTokens.length === 0) {
return {
code: ResponseCode.ERROR,
message: '没有找到有效的设备令牌',
data: {
totalUsers,
totalTokens: 0,
successCount: 0,
failedCount: totalUsers,
results: [],
},
};
}
const apnsResults = await this.apnsProvider.send(apnsNotification, allDeviceTokens);
// 处理结果并创建消息记录
for (const [userId, deviceTokens] of userTokensMap.entries()) {
for (const deviceToken of deviceTokens) {
try {
// 创建消息记录
const messageData: CreatePushMessageDto = {
userId,
deviceToken,
messageType: 'batch',
title: notificationData.title,
body: notificationData.body,
payload: notificationData.payload,
pushType: notificationData.pushType,
priority: notificationData.priority,
expiry: notificationData.expiry ? new Date(Date.now() + notificationData.expiry * 1000) : undefined,
collapseId: notificationData.collapseId,
};
const message = await this.pushMessageService.createMessage(messageData);
// 查找对应的APNs结果
const apnsResult = apnsResults.sent.find(s => s.device === deviceToken) ||
apnsResults.failed.find(f => f.device === deviceToken);
if (apnsResult) {
if ('device' in apnsResult && apnsResult.device === deviceToken) {
// 成功发送
await this.pushMessageService.updateMessageStatus(message.id, PushMessageStatus.SENT, apnsResult);
await this.pushTokenService.updateLastUsedTime(deviceToken);
results.push({
userId,
deviceToken,
success: true,
apnsResponse: apnsResult,
});
successCount++;
} else {
// 发送失败
const failure = apnsResult as any;
const errorMessage = failure.error ? failure.error.message : `APNs Error: ${failure.status}`;
await this.pushMessageService.updateMessageStatus(
message.id,
PushMessageStatus.FAILED,
failure.response,
errorMessage
);
// 如果是无效令牌,停用该令牌
if (failure.status === '410' || failure.response?.reason === 'Unregistered') {
await this.pushTokenService.unregisterToken(userId, deviceToken);
}
results.push({
userId,
deviceToken,
success: false,
error: errorMessage,
apnsResponse: failure.response,
});
failedCount++;
}
} else {
// 未找到结果,标记为失败
await this.pushMessageService.updateMessageStatus(
message.id,
PushMessageStatus.FAILED,
null,
'No APNs result found'
);
results.push({
userId,
deviceToken,
success: false,
error: 'No APNs result found',
});
failedCount++;
}
} catch (error) {
this.logger.error(`Failed to process batch push result for user ${userId}, device ${deviceToken}: ${error.message}`, error);
results.push({
userId,
deviceToken,
success: false,
error: error.message,
});
failedCount++;
}
}
}
const success = failedCount === 0;
return {
code: success ? ResponseCode.SUCCESS : ResponseCode.ERROR,
message: success ? '批量推送发送成功' : '部分批量推送发送失败',
data: {
totalUsers,
totalTokens,
successCount,
failedCount,
results,
},
};
} catch (error) {
this.logger.error(`Failed to send batch push notification: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `批量推送发送失败: ${error.message}`,
data: {
totalUsers: notificationData.userIds.length,
totalTokens: 0,
successCount: 0,
failedCount: notificationData.userIds.length,
results: [],
},
};
}
}
/**
* 发送静默推送
*/
async sendSilentNotification(userId: string, payload: any): Promise<PushResponseDto> {
try {
this.logger.log(`Sending silent push notification to user ${userId}`);
const notificationData: SendPushNotificationDto = {
userIds: [userId],
title: '',
body: '',
payload,
pushType: PushType.BACKGROUND,
contentAvailable: true,
};
return this.sendNotification(notificationData);
} catch (error) {
this.logger.error(`Failed to send silent push notification: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `静默推送发送失败: ${error.message}`,
data: {
success: false,
sentCount: 0,
failedCount: 1,
results: [],
},
};
}
}
/**
* 注册设备令牌
*/
async registerToken(userId: string, tokenData: any): Promise<any> {
try {
const token = await this.pushTokenService.registerToken(userId, tokenData);
return {
code: ResponseCode.SUCCESS,
message: '设备令牌注册成功',
data: {
success: true,
tokenId: token.id,
},
};
} catch (error) {
this.logger.error(`Failed to register device token: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `设备令牌注册失败: ${error.message}`,
data: {
success: false,
tokenId: '',
},
};
}
}
/**
* 更新设备令牌
*/
async updateToken(userId: string, tokenData: any): Promise<any> {
try {
const token = await this.pushTokenService.updateToken(userId, tokenData);
return {
code: ResponseCode.SUCCESS,
message: '设备令牌更新成功',
data: {
success: true,
tokenId: token.id,
},
};
} catch (error) {
this.logger.error(`Failed to update device token: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `设备令牌更新失败: ${error.message}`,
data: {
success: false,
tokenId: '',
},
};
}
}
/**
* 注销设备令牌
*/
async unregisterToken(userId: string, deviceToken: string): Promise<any> {
try {
await this.pushTokenService.unregisterToken(userId, deviceToken);
return {
code: ResponseCode.SUCCESS,
message: '设备令牌注销成功',
data: {
success: true,
},
};
} catch (error) {
this.logger.error(`Failed to unregister device token: ${error.message}`, error);
return {
code: ResponseCode.ERROR,
message: `设备令牌注销失败: ${error.message}`,
data: {
success: false,
},
};
}
}
}

View File

@@ -0,0 +1,104 @@
import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { PushTemplateService } from './push-template.service';
import { CreatePushTemplateDto } from './dto/create-push-template.dto';
import { UpdatePushTemplateDto } from './dto/update-push-template.dto';
import { PushTemplate } from './models/push-template.model';
import { CurrentUser } from '../common/decorators/current-user.decorator';
import { AccessTokenPayload } from '../users/services/apple-auth.service';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
@ApiTags('推送模板')
@Controller('push-notifications/templates')
@UseGuards(JwtAuthGuard)
export class PushTemplateController {
constructor(private readonly pushTemplateService: PushTemplateService) { }
@Get()
@ApiOperation({ summary: '获取所有推送模板' })
@ApiResponse({ status: 200, description: '获取成功', type: [PushTemplate] })
async getAllTemplates(): Promise<PushTemplate[]> {
return this.pushTemplateService.getAllTemplates();
}
@Get('active')
@ApiOperation({ summary: '获取所有活跃推送模板' })
@ApiResponse({ status: 200, description: '获取成功', type: [PushTemplate] })
async getActiveTemplates(): Promise<PushTemplate[]> {
return this.pushTemplateService.getActiveTemplates();
}
@Get(':templateKey')
@ApiOperation({ summary: '获取推送模板' })
@ApiParam({ name: 'templateKey', description: '模板键' })
@ApiResponse({ status: 200, description: '获取成功', type: PushTemplate })
async getTemplate(@Param('templateKey') templateKey: string): Promise<PushTemplate> {
return this.pushTemplateService.getTemplate(templateKey);
}
@Get('id/:id')
@ApiOperation({ summary: '根据ID获取推送模板' })
@ApiParam({ name: 'id', description: '模板ID' })
@ApiResponse({ status: 200, description: '获取成功', type: PushTemplate })
async getTemplateById(@Param('id') id: string): Promise<PushTemplate> {
return this.pushTemplateService.getTemplateById(id);
}
@Post()
@ApiOperation({ summary: '创建推送模板' })
@ApiResponse({ status: 201, description: '创建成功', type: PushTemplate })
async createTemplate(
@Body() createTemplateDto: CreatePushTemplateDto,
): Promise<PushTemplate> {
return this.pushTemplateService.createTemplate(createTemplateDto);
}
@Put(':id')
@ApiOperation({ summary: '更新推送模板' })
@ApiParam({ name: 'id', description: '模板ID' })
@ApiResponse({ status: 200, description: '更新成功', type: PushTemplate })
async updateTemplate(
@Param('id') id: string,
@Body() updateTemplateDto: UpdatePushTemplateDto,
): Promise<PushTemplate> {
return this.pushTemplateService.updateTemplate(id, updateTemplateDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除推送模板' })
@ApiParam({ name: 'id', description: '模板ID' })
@ApiResponse({ status: 200, description: '删除成功' })
async deleteTemplate(@Param('id') id: string): Promise<void> {
return this.pushTemplateService.deleteTemplate(id);
}
@Put(':id/toggle')
@ApiOperation({ summary: '激活/停用模板' })
@ApiParam({ name: 'id', description: '模板ID' })
@ApiResponse({ status: 200, description: '操作成功', type: PushTemplate })
async toggleTemplateStatus(
@Param('id') id: string,
@Body() body: { isActive: boolean },
): Promise<PushTemplate> {
return this.pushTemplateService.toggleTemplateStatus(id, body.isActive);
}
@Post('validate')
@ApiOperation({ summary: '验证模板变量' })
@ApiResponse({ status: 200, description: '验证成功' })
async validateTemplateVariables(
@Body() body: { template: string; requiredVariables: string[] },
): Promise<{ isValid: boolean; missingVariables: string[] }> {
return this.pushTemplateService.validateTemplateVariables(body.template, body.requiredVariables);
}
@Post('extract-variables')
@ApiOperation({ summary: '提取模板变量' })
@ApiResponse({ status: 200, description: '提取成功' })
async extractTemplateVariables(
@Body() body: { template: string },
): Promise<{ variables: string[] }> {
const variables = this.pushTemplateService.extractTemplateVariables(body.template);
return { variables };
}
}

View File

@@ -0,0 +1,280 @@
import { Injectable, Logger, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { PushTemplate } from './models/push-template.model';
import { CreatePushTemplateDto } from './dto/create-push-template.dto';
import { UpdatePushTemplateDto } from './dto/update-push-template.dto';
import { RenderedTemplate } from './interfaces/push-notification.interface';
@Injectable()
export class PushTemplateService {
private readonly logger = new Logger(PushTemplateService.name);
constructor(
@InjectModel(PushTemplate)
private readonly templateModel: typeof PushTemplate,
) { }
/**
* 创建推送模板
*/
async createTemplate(templateData: CreatePushTemplateDto): Promise<PushTemplate> {
try {
this.logger.log(`Creating push template with key: ${templateData.templateKey}`);
// 检查模板键是否已存在
const existingTemplate = await this.templateModel.findOne({
where: {
templateKey: templateData.templateKey,
},
});
if (existingTemplate) {
throw new ConflictException(`Template with key '${templateData.templateKey}' already exists`);
}
const template = await this.templateModel.create({
templateKey: templateData.templateKey,
title: templateData.title,
body: templateData.body,
payloadTemplate: templateData.payloadTemplate,
pushType: templateData.pushType,
priority: templateData.priority || 10,
isActive: true,
});
this.logger.log(`Successfully created push template with key: ${templateData.templateKey}`);
return template;
} catch (error) {
this.logger.error(`Failed to create push template: ${error.message}`, error);
throw error;
}
}
/**
* 更新推送模板
*/
async updateTemplate(id: string, templateData: UpdatePushTemplateDto): Promise<PushTemplate> {
try {
this.logger.log(`Updating push template with ID: ${id}`);
const template = await this.templateModel.findByPk(id);
if (!template) {
throw new NotFoundException(`Template with ID ${id} not found`);
}
await template.update(templateData);
this.logger.log(`Successfully updated push template with ID: ${id}`);
return template;
} catch (error) {
this.logger.error(`Failed to update push template: ${error.message}`, error);
throw error;
}
}
/**
* 删除推送模板
*/
async deleteTemplate(id: string): Promise<void> {
try {
this.logger.log(`Deleting push template with ID: ${id}`);
const template = await this.templateModel.findByPk(id);
if (!template) {
throw new NotFoundException(`Template with ID ${id} not found`);
}
await template.destroy();
this.logger.log(`Successfully deleted push template with ID: ${id}`);
} catch (error) {
this.logger.error(`Failed to delete push template: ${error.message}`, error);
throw error;
}
}
/**
* 获取模板
*/
async getTemplate(templateKey: string): Promise<PushTemplate> {
try {
const template = await this.templateModel.findOne({
where: {
templateKey,
isActive: true,
},
});
if (!template) {
throw new NotFoundException(`Template with key '${templateKey}' not found or inactive`);
}
return template;
} catch (error) {
this.logger.error(`Failed to get push template: ${error.message}`, error);
throw error;
}
}
/**
* 根据ID获取模板
*/
async getTemplateById(id: string): Promise<PushTemplate> {
try {
const template = await this.templateModel.findByPk(id);
if (!template) {
throw new NotFoundException(`Template with ID ${id} not found`);
}
return template;
} catch (error) {
this.logger.error(`Failed to get push template by ID: ${error.message}`, error);
throw error;
}
}
/**
* 获取所有模板
*/
async getAllTemplates(): Promise<PushTemplate[]> {
try {
const templates = await this.templateModel.findAll({
order: [['createdAt', 'DESC']],
});
return templates;
} catch (error) {
this.logger.error(`Failed to get all push templates: ${error.message}`, error);
throw error;
}
}
/**
* 获取所有活跃模板
*/
async getActiveTemplates(): Promise<PushTemplate[]> {
try {
const templates = await this.templateModel.findAll({
where: {
isActive: true,
},
order: [['createdAt', 'DESC']],
});
return templates;
} catch (error) {
this.logger.error(`Failed to get active push templates: ${error.message}`, error);
throw error;
}
}
/**
* 渲染模板
*/
async renderTemplate(templateKey: string, data: any): Promise<RenderedTemplate> {
try {
this.logger.log(`Rendering template with key: ${templateKey}`);
const template = await this.getTemplate(templateKey);
// 简单的模板变量替换
const renderedTitle = this.replaceVariables(template.title, data);
const renderedBody = this.replaceVariables(template.body, data);
const renderedPayload = template.payloadTemplate
? this.replaceVariables(JSON.stringify(template.payloadTemplate), data)
: null;
const renderedTemplate: RenderedTemplate = {
title: renderedTitle,
body: renderedBody,
payload: renderedPayload ? JSON.parse(renderedPayload) : undefined,
pushType: template.pushType,
priority: template.priority,
};
this.logger.log(`Successfully rendered template with key: ${templateKey}`);
return renderedTemplate;
} catch (error) {
this.logger.error(`Failed to render template: ${error.message}`, error);
throw error;
}
}
/**
* 激活/停用模板
*/
async toggleTemplateStatus(id: string, isActive: boolean): Promise<PushTemplate> {
try {
this.logger.log(`Toggling template status for ID: ${id} to ${isActive}`);
const template = await this.templateModel.findByPk(id);
if (!template) {
throw new NotFoundException(`Template with ID ${id} not found`);
}
await template.update({
isActive,
});
this.logger.log(`Successfully toggled template status for ID: ${id}`);
return template;
} catch (error) {
this.logger.error(`Failed to toggle template status: ${error.message}`, error);
throw error;
}
}
/**
* 替换模板变量
*/
private replaceVariables(template: string, data: any): string {
if (!template || !data) {
return template;
}
let result = template;
// 替换 {{variable}} 格式的变量
Object.keys(data).forEach(key => {
const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
result = result.replace(regex, data[key]);
});
return result;
}
/**
* 验证模板变量
*/
validateTemplateVariables(template: string, requiredVariables: string[]): { isValid: boolean; missingVariables: string[] } {
const variableRegex = /{{\s*([^}]+)\s*}}/g;
const foundVariables: string[] = [];
let match;
while ((match = variableRegex.exec(template)) !== null) {
foundVariables.push(match[1].trim());
}
const missingVariables = requiredVariables.filter(variable => !foundVariables.includes(variable));
return {
isValid: missingVariables.length === 0,
missingVariables,
};
}
/**
* 获取模板变量列表
*/
extractTemplateVariables(template: string): string[] {
const variableRegex = /{{\s*([^}]+)\s*}}/g;
const variables: string[] = [];
let match;
while ((match = variableRegex.exec(template)) !== null) {
variables.push(match[1].trim());
}
return [...new Set(variables)]; // 去重
}
}

View File

@@ -0,0 +1,332 @@
import { Injectable, Logger, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from 'sequelize';
import { UserPushToken } from './models/user-push-token.model';
import { DeviceType } from './enums/device-type.enum';
import { RegisterDeviceTokenDto } from './dto/register-device-token.dto';
import { UpdateDeviceTokenDto } from './dto/update-device-token.dto';
@Injectable()
export class PushTokenService {
private readonly logger = new Logger(PushTokenService.name);
constructor(
@InjectModel(UserPushToken)
private readonly pushTokenModel: typeof UserPushToken,
) { }
/**
* 注册设备令牌
*/
async registerToken(userId: string, tokenData: RegisterDeviceTokenDto): Promise<UserPushToken> {
try {
this.logger.log(`Registering push token for user ${userId}`);
// 检查是否已存在相同的令牌
const existingToken = await this.pushTokenModel.findOne({
where: {
userId,
deviceToken: tokenData.deviceToken,
},
});
if (existingToken) {
// 更新现有令牌信息
await existingToken.update({
deviceType: tokenData.deviceType,
appVersion: tokenData.appVersion,
osVersion: tokenData.osVersion,
deviceName: tokenData.deviceName,
isActive: true,
lastUsedAt: new Date(),
});
this.logger.log(`Updated existing push token for user ${userId}`);
return existingToken;
}
// 检查用户是否已有其他设备的令牌,可以选择是否停用旧令牌
const userTokens = await this.pushTokenModel.findAll({
where: {
userId,
isActive: true,
},
});
// 创建新令牌
const newToken = await this.pushTokenModel.create({
userId,
deviceToken: tokenData.deviceToken,
deviceType: tokenData.deviceType,
appVersion: tokenData.appVersion,
osVersion: tokenData.osVersion,
deviceName: tokenData.deviceName,
isActive: true,
lastUsedAt: new Date(),
});
this.logger.log(`Successfully registered new push token for user ${userId}`);
return newToken;
} catch (error) {
this.logger.error(`Failed to register push token for user ${userId}: ${error.message}`, error);
throw error;
}
}
/**
* 更新设备令牌
*/
async updateToken(userId: string, tokenData: UpdateDeviceTokenDto): Promise<UserPushToken> {
try {
this.logger.log(`Updating push token for user ${userId}`);
// 查找当前令牌
const currentToken = await this.pushTokenModel.findOne({
where: {
userId,
deviceToken: tokenData.currentDeviceToken,
isActive: true,
},
});
if (!currentToken) {
throw new NotFoundException('Current device token not found or inactive');
}
// 检查新令牌是否已存在
const existingNewToken = await this.pushTokenModel.findOne({
where: {
userId,
deviceToken: tokenData.newDeviceToken,
},
});
if (existingNewToken) {
// 如果新令牌已存在,激活它并停用当前令牌
await existingNewToken.update({
isActive: true,
lastUsedAt: new Date(),
appVersion: tokenData.appVersion || existingNewToken.appVersion,
osVersion: tokenData.osVersion || existingNewToken.osVersion,
deviceName: tokenData.deviceName || existingNewToken.deviceName,
});
await currentToken.update({
isActive: false,
});
this.logger.log(`Activated existing new token and deactivated old token for user ${userId}`);
return existingNewToken;
}
// 更新当前令牌为新令牌
await currentToken.update({
deviceToken: tokenData.newDeviceToken,
appVersion: tokenData.appVersion,
osVersion: tokenData.osVersion,
deviceName: tokenData.deviceName,
lastUsedAt: new Date(),
});
this.logger.log(`Successfully updated push token for user ${userId}`);
return currentToken;
} catch (error) {
this.logger.error(`Failed to update push token for user ${userId}: ${error.message}`, error);
throw error;
}
}
/**
* 注销设备令牌
*/
async unregisterToken(userId: string, deviceToken: string): Promise<void> {
try {
this.logger.log(`Unregistering push token for user ${userId}`);
const token = await this.pushTokenModel.findOne({
where: {
userId,
deviceToken,
isActive: true,
},
});
if (!token) {
throw new NotFoundException('Device token not found or inactive');
}
await token.update({
isActive: false,
});
this.logger.log(`Successfully unregistered push token for user ${userId}`);
} catch (error) {
this.logger.error(`Failed to unregister push token for user ${userId}: ${error.message}`, error);
throw error;
}
}
/**
* 获取用户的所有有效令牌
*/
async getActiveTokens(userId: string): Promise<UserPushToken[]> {
try {
const tokens = await this.pushTokenModel.findAll({
where: {
userId,
isActive: true,
},
order: [['lastUsedAt', 'DESC']],
});
this.logger.log(`Found ${tokens.length} active tokens for user ${userId}`);
return tokens;
} catch (error) {
this.logger.error(`Failed to get active tokens for user ${userId}: ${error.message}`, error);
throw error;
}
}
/**
* 获取用户的所有令牌(包括非活跃的)
*/
async getAllTokens(userId: string): Promise<UserPushToken[]> {
try {
const tokens = await this.pushTokenModel.findAll({
where: {
userId,
},
order: [['createdAt', 'DESC']],
});
this.logger.log(`Found ${tokens.length} total tokens for user ${userId}`);
return tokens;
} catch (error) {
this.logger.error(`Failed to get all tokens for user ${userId}: ${error.message}`, error);
throw error;
}
}
/**
* 验证令牌有效性
*/
async validateToken(deviceToken: string): Promise<boolean> {
try {
const token = await this.pushTokenModel.findOne({
where: {
deviceToken,
isActive: true,
},
});
return !!token;
} catch (error) {
this.logger.error(`Failed to validate token: ${error.message}`, error);
return false;
}
}
/**
* 清理无效令牌
*/
async cleanupInvalidTokens(): Promise<number> {
try {
this.logger.log('Starting cleanup of invalid tokens');
// 清理超过30天未使用的令牌
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const result = await this.pushTokenModel.update(
{
isActive: false,
},
{
where: {
isActive: true,
lastUsedAt: {
[Op.lt]: thirtyDaysAgo,
},
},
},
);
const cleanedCount = result[0];
this.logger.log(`Cleaned up ${cleanedCount} inactive tokens`);
return cleanedCount;
} catch (error) {
this.logger.error(`Failed to cleanup invalid tokens: ${error.message}`, error);
throw error;
}
}
/**
* 根据设备令牌获取用户ID
*/
async getUserIdByDeviceToken(deviceToken: string): Promise<string | null> {
try {
const token = await this.pushTokenModel.findOne({
where: {
deviceToken,
isActive: true,
},
});
return token ? token.userId : null;
} catch (error) {
this.logger.error(`Failed to get user ID by device token: ${error.message}`, error);
return null;
}
}
/**
* 批量获取用户的设备令牌
*/
async getDeviceTokensByUserIds(userIds: string[]): Promise<Map<string, string[]>> {
try {
const tokens = await this.pushTokenModel.findAll({
where: {
userId: {
[Op.in]: userIds,
},
isActive: true,
},
});
const userTokensMap = new Map<string, string[]>();
tokens.forEach((token) => {
if (!userTokensMap.has(token.userId)) {
userTokensMap.set(token.userId, []);
}
userTokensMap.get(token.userId)!.push(token.deviceToken);
});
return userTokensMap;
} catch (error) {
this.logger.error(`Failed to get device tokens by user IDs: ${error.message}`, error);
throw error;
}
}
/**
* 更新令牌最后使用时间
*/
async updateLastUsedTime(deviceToken: string): Promise<void> {
try {
await this.pushTokenModel.update(
{
lastUsedAt: new Date(),
},
{
where: {
deviceToken,
isActive: true,
},
},
);
} catch (error) {
this.logger.error(`Failed to update last used time: ${error.message}`, error);
}
}
}