Compare commits

..

6 Commits

Author SHA1 Message Date
f2b1043cbc refactor: 统一代码缩进与引号风格,新增CORS配置
1.  修正所有文件的缩进为4空格,将单引号统一改为双引号
2.  新增CORS_ORIGIN环境变量配置并从env读取CORS允许源
3.  新增prettier配置文件统一代码格式
4.  为main.ts添加启动日志输出
2026-07-02 16:03:42 +08:00
0eeeea0c4d feat: 新增剧集封面、集数管理与上传优化功能
1. 新增Cover实体类并注册到数据库模块
2. 为剧集添加总集数字段及自动创建集数槽功能
3. 新增管理员更新剧集集数接口
4. 优化发布剧集列表:支持标题过滤与默认分页大小10
5. 扩展MediaUploadJob实体字段,完善媒体上传流程
6. 重构订单与媒体服务,新增数据库持久化支持
7. 新增剧集标题过滤的端到端测试用例
2026-07-02 15:46:29 +08:00
f342312b92 refactor: 重构项目支持TypeORM数据库持久化
新增数据库实体类与服务实现,将内存存储扩展为支持数据库的完整实现,包括:
1. 新增Drama和Episode实体类,添加多个业务字段
2. 重构DramasService实现数据库CRUD与业务逻辑
3. 升级相关服务类为异步方法适配数据库操作
4. 更新测试用例适配异步接口变更
5. 完善分页、数据转换等辅助工具方法
2026-07-01 21:49:36 +08:00
d3083bf16b feat: 新增数据库持久化支持并完善后台管理功能
- 引入dotenv加载环境变量,新增数据库同步配置项
- 为用户服务、管理员服务、数据服务添加数据库持久化逻辑
- 新增管理员用户邮箱字段,完善权限校验逻辑
- 添加数据库初始化与种子数据脚本
- 新增e2e测试验证管理员数据持久化
2026-07-01 17:11:29 +08:00
026665b2cc feat: 添加数据分析模块、媒体上传功能与剧集管理完善
本次提交新增了完整的数据分析模块,包括数据同步、指标统计接口;实现了基于BytePlus的直传媒体上传流程,包含上传任务创建、完成、审核同步等功能;同时完善了剧集管理功能,新增了剧集配置、更新接口,扩展了审核状态枚举,补充了剧集与剧集指标的关联逻辑,还添加了播放器对外接口与相关测试用例。
2026-07-01 16:36:06 +08:00
5fa8c5e0a9 feat(dramas,media): add video resolution fields and fix quote style
1. 为剧集剧集添加width和height字段,支持存储视频分辨率信息
2. 统一将media.controller.ts中的单引号改为双引号,保持代码风格一致
2026-07-01 16:04:49 +08:00
51 changed files with 3517 additions and 375 deletions

8
.env
View File

@@ -1,5 +1,8 @@
PORT=3030
JWT_SECRET=change-me
ADMIN_JWT_SECRET=change-me-admin
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
# MySQL settings for the production TypeORM layer.
# The current scaffold defines entities and API boundaries; repository persistence can be enabled when the database is ready.
@@ -8,3 +11,8 @@ DB_PORT=22246
DB_USERNAME=root
DB_PASSWORD=zhxiao1124..
DB_DATABASE=onion_tiktok
# CORS settings
CORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173
DB_SYNCHRONIZE = true

View File

@@ -11,3 +11,8 @@ DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=
DB_DATABASE=cth_tk_backend
# CORS settings
CORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173
DB_SYNCHRONIZE = true

BIN
.pnpm-store/v11/index.db Normal file

Binary file not shown.

9
.prettierrc Normal file
View File

@@ -0,0 +1,9 @@
{
"tabWidth": 4,
"singleQuote": false,
"trailingComma": "all",
"printWidth": 390,
"eslintIntegration": true,
"bracketSpacing": true,
"stylelintIntegration": true
}

View File

@@ -23,6 +23,7 @@
"bcrypt": "^6.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"dotenv": "17.4.1",
"mysql2": "^3.0.0",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",

3
pnpm-lock.yaml generated
View File

@@ -44,6 +44,9 @@ importers:
class-validator:
specifier: ^0.14.0
version: 0.14.4
dotenv:
specifier: 17.4.1
version: 17.4.1
mysql2:
specifier: ^3.0.0
version: 3.22.5(@types/node@24.13.2)

View File

@@ -1,27 +1,31 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AdminModule } from './modules/admin/admin.module';
import { AuthModule } from './modules/auth/auth.module';
import { DramasModule } from './modules/dramas/dramas.module';
import { HealthModule } from './modules/health/health.module';
import { LogsModule } from './modules/logs/logs.module';
import { MediaModule } from './modules/media/media.module';
import { OrdersModule } from './modules/orders/orders.module';
import { PlayerModule } from './modules/player/player.module';
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { AdminModule } from "./modules/admin/admin.module";
import { AuthModule } from "./modules/auth/auth.module";
import { DataModule } from "./modules/data/data.module";
import { DatabaseModule } from "./modules/database/database.module";
import { DramasModule } from "./modules/dramas/dramas.module";
import { HealthModule } from "./modules/health/health.module";
import { LogsModule } from "./modules/logs/logs.module";
import { MediaModule } from "./modules/media/media.module";
import { OrdersModule } from "./modules/orders/orders.module";
import { PlayerModule } from "./modules/player/player.module";
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
AdminModule,
HealthModule,
LogsModule,
DramasModule,
MediaModule,
AuthModule,
OrdersModule,
PlayerModule,
],
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
DatabaseModule,
AdminModule,
HealthModule,
LogsModule,
DramasModule,
DataModule,
MediaModule,
AuthModule,
OrdersModule,
PlayerModule,
],
})
export class AppModule {}

View File

@@ -8,35 +8,27 @@ import { RequestIdMiddleware } from "./common/middleware/request-id.middleware";
import { LogsService } from "./modules/logs/logs.service";
export function bootstrapApp(app: INestApplication) {
app.enableCors({
origin: process.env.CORS_ORIGIN?.split(',') ?? [
'http://localhost:5173',
'http://127.0.0.1:5173',
],
credentials: true,
});
app.use(RequestIdMiddleware);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
app.enableCors({
origin: process.env.CORS_ORIGIN?.split(","),
credentials: true,
});
app.use(RequestIdMiddleware);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
const logsService = app.get(LogsService);
app.useGlobalFilters(new HttpExceptionFilter(logsService));
app.useGlobalInterceptors(
new RequestLoggingInterceptor(logsService, app.get(Reflector)),
new ResponseInterceptor(),
);
const logsService = app.get(LogsService);
const config = new DocumentBuilder()
.setTitle("TikTok Short Drama Backend")
.setDescription("RESTful API for TikTok short drama backend services.")
.setVersion("1.0")
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("/api/docs", app, document);
app.useGlobalFilters(new HttpExceptionFilter(logsService));
app.useGlobalInterceptors(new RequestLoggingInterceptor(logsService, app.get(Reflector)), new ResponseInterceptor());
const config = new DocumentBuilder().setTitle("TikTok Short Drama Backend").setDescription("RESTful API for TikTok short drama backend services.").setVersion("1.0").addBearerAuth().build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("/api/docs", app, document);
}

View File

@@ -1,11 +1,13 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { bootstrapApp } from './bootstrap';
import "dotenv/config";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { bootstrapApp } from "./bootstrap";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
bootstrapApp(app);
await app.listen(process.env.PORT ?? 3000);
const app = await NestFactory.create(AppModule);
bootstrapApp(app);
await app.listen(process.env.PORT ?? 3000);
console.log(`Application is running on: ${await app.getUrl()}`);
}
void bootstrap();

View File

@@ -2,17 +2,24 @@ import {
ConflictException,
Injectable,
NotFoundException,
OnModuleInit,
Optional,
UnauthorizedException,
UnprocessableEntityException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectDataSource } from '@nestjs/typeorm';
import * as bcrypt from 'bcrypt';
import { DataSource } from 'typeorm';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { AdminLoginDto } from './dto/admin-login.dto';
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateAdminProfileDto } from './dto/update-admin-profile.dto';
import { AdminUser } from './entities/admin-user.entity';
import { Permission } from './entities/permission.entity';
import { Role } from './entities/role.entity';
import {
AdminUserRecord,
AdminUserView,
@@ -26,7 +33,7 @@ interface PaginationInput {
}
@Injectable()
export class AdminService {
export class AdminService implements OnModuleInit {
private permissionSequence = 1;
private roleSequence = 1;
private adminSequence = 1;
@@ -34,8 +41,22 @@ export class AdminService {
private readonly roles: RoleRecord[] = [];
private readonly admins: AdminUserRecord[] = [];
constructor(private readonly jwtService: JwtService) {
this.seed();
constructor(
private readonly jwtService: JwtService,
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {
if (!this.hasDatabase()) {
this.seedMemory();
}
}
async onModuleInit() {
if (this.hasDatabase()) {
await this.seedDatabase();
await this.loadDatabaseRecords();
}
}
async login(dto: AdminLoginDto) {
@@ -58,7 +79,17 @@ export class AdminService {
};
}
createPermission(dto: CreatePermissionDto): PermissionRecord {
async createPermission(dto: CreatePermissionDto): Promise<PermissionRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Permission);
if (await repository.findOne({ where: { code: dto.code } })) {
throw new ConflictException('Permission code already exists');
}
const saved = await repository.save(repository.create(dto));
await this.loadDatabaseRecords();
return this.toPermissionRecord(saved);
}
if (this.permissions.some((item) => item.code === dto.code)) {
throw new ConflictException('Permission code already exists');
}
@@ -77,13 +108,34 @@ export class AdminService {
return permission;
}
listPermissions(
async listPermissions(
pagination: PaginationInput,
): PaginatedResponse<PermissionRecord> {
): Promise<PaginatedResponse<PermissionRecord>> {
if (this.hasDatabase()) {
await this.loadDatabaseRecords();
}
return this.paginate([...this.permissions], pagination);
}
createRole(dto: CreateRoleDto): RoleRecord {
async createRole(dto: CreateRoleDto): Promise<RoleRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Role);
if (await repository.findOne({ where: { code: dto.code } })) {
throw new ConflictException('Role code already exists');
}
const saved = await repository.save(
repository.create({
code: dto.code,
name: dto.name,
description: dto.description,
permissionIds: dto.permissionIds ?? [],
}),
);
await this.loadDatabaseRecords();
return this.roles.find((role) => role.id === Number(saved.id)) as RoleRecord;
}
if (this.roles.some((item) => item.code === dto.code)) {
throw new ConflictException('Role code already exists');
}
@@ -107,11 +159,27 @@ export class AdminService {
return role;
}
listRoles(pagination: PaginationInput): PaginatedResponse<RoleRecord> {
async listRoles(pagination: PaginationInput): Promise<PaginatedResponse<RoleRecord>> {
if (this.hasDatabase()) {
await this.loadDatabaseRecords();
}
return this.paginate([...this.roles], pagination);
}
updateRolePermissions(id: number, permissionIds: number[]): RoleRecord {
async updateRolePermissions(id: number, permissionIds: number[]): Promise<RoleRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Role);
const role = await repository.findOne({ where: { id } });
if (!role) {
throw new NotFoundException('Role not found');
}
role.permissionIds = [...new Set(permissionIds)];
await repository.save(role);
await this.loadDatabaseRecords();
return this.roles.find((item) => item.id === id) as RoleRecord;
}
const role = this.roles.find((item) => item.id === id);
if (!role) {
throw new NotFoundException('Role not found');
@@ -126,7 +194,29 @@ export class AdminService {
return role;
}
createAdminUser(dto: CreateAdminUserDto): AdminUserView {
async createAdminUser(dto: CreateAdminUserDto): Promise<AdminUserView> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(AdminUser);
if (await repository.findOne({ where: { username: dto.username } })) {
throw new ConflictException('Admin username already exists');
}
const saved = await repository.save(
repository.create({
username: dto.username,
passwordHash: bcrypt.hashSync(dto.password, 10),
nickname: dto.nickname,
email: dto.email,
status: 'active',
isSuperAdmin: false,
roleIds: dto.roleIds ?? [],
}),
);
await this.loadDatabaseRecords();
return this.toAdminView(
this.admins.find((admin) => admin.id === Number(saved.id)) as AdminUserRecord,
);
}
if (this.admins.some((item) => item.username === dto.username)) {
throw new ConflictException('Admin username already exists');
}
@@ -149,19 +239,35 @@ export class AdminService {
return this.toAdminView(admin);
}
listAdminUsers(
async listAdminUsers(
pagination: PaginationInput,
): PaginatedResponse<AdminUserView> {
): Promise<PaginatedResponse<AdminUserView>> {
if (this.hasDatabase()) {
await this.loadDatabaseRecords();
}
return this.paginate(
this.admins.map((admin) => this.toAdminView(admin)),
pagination,
);
}
updateAdminStatus(
async updateAdminStatus(
id: number,
status: 'active' | 'disabled',
): AdminUserView {
): Promise<AdminUserView> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(AdminUser);
const admin = await repository.findOne({ where: { id } });
if (!admin) {
throw new NotFoundException('Admin user not found');
}
admin.status = status;
await repository.save(admin);
await this.loadDatabaseRecords();
return this.toAdminView(this.findAdminById(id) as AdminUserRecord);
}
const admin = this.findAdminById(id);
if (!admin) {
throw new NotFoundException('Admin user not found');
@@ -172,7 +278,19 @@ export class AdminService {
return this.toAdminView(admin);
}
updateAdminRoles(id: number, roleIds: number[]): AdminUserView {
async updateAdminRoles(id: number, roleIds: number[]): Promise<AdminUserView> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(AdminUser);
const admin = await repository.findOne({ where: { id } });
if (!admin) {
throw new NotFoundException('Admin user not found');
}
admin.roleIds = [...new Set(roleIds)];
await repository.save(admin);
await this.loadDatabaseRecords();
return this.toAdminView(this.findAdminById(id) as AdminUserRecord);
}
const admin = this.findAdminById(id);
if (!admin) {
throw new NotFoundException('Admin user not found');
@@ -183,10 +301,23 @@ export class AdminService {
return this.toAdminView(admin);
}
updateProfile(
async updateProfile(
adminId: number,
dto: UpdateAdminProfileDto,
): AdminUserView {
): Promise<AdminUserView> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(AdminUser);
const admin = await repository.findOne({ where: { id: adminId } });
if (!admin) {
throw new NotFoundException('Admin user not found');
}
admin.nickname = dto.nickname;
admin.email = dto.email;
await repository.save(admin);
await this.loadDatabaseRecords();
return this.toAdminView(this.findAdminById(adminId) as AdminUserRecord);
}
const admin = this.findAdminById(adminId);
if (!admin) {
throw new NotFoundException('Admin user not found');
@@ -198,11 +329,26 @@ export class AdminService {
return this.toAdminView(admin);
}
changePassword(
async changePassword(
adminId: number,
oldPassword: string,
newPassword: string,
): Record<string, never> {
): Promise<Record<string, never>> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(AdminUser);
const admin = await repository.findOne({ where: { id: adminId } });
if (!admin) {
throw new NotFoundException('Admin user not found');
}
if (!bcrypt.compareSync(oldPassword, admin.passwordHash)) {
throw new UnprocessableEntityException('Old password is incorrect');
}
admin.passwordHash = bcrypt.hashSync(newPassword, 10);
await repository.save(admin);
await this.loadDatabaseRecords();
return {};
}
const admin = this.findAdminById(adminId);
if (!admin) {
throw new NotFoundException('Admin user not found');
@@ -256,7 +402,7 @@ export class AdminService {
};
}
private seed() {
private seedMemory() {
const codes = [
['permission:read', '查看权限'],
['permission:create', '创建权限'],
@@ -275,6 +421,8 @@ export class AdminService {
['episode:update', '更新剧集'],
['media:read', '查看媒体'],
['media:create', '创建媒体'],
['data:read', '查看数据'],
['data:sync', '同步数据'],
['payment:read', '查看支付记录'],
['log:read', '查看日志'],
];
@@ -298,6 +446,141 @@ export class AdminService {
});
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private async seedDatabase() {
const dataSource = this.dataSource as DataSource;
const permissionRepository = dataSource.getRepository(Permission);
for (const [code, name] of this.permissionSeeds()) {
const existing = await permissionRepository.findOne({ where: { code } });
if (!existing) {
await permissionRepository.save(
permissionRepository.create({ code, name }),
);
} else if (existing.name !== name) {
existing.name = name;
await permissionRepository.save(existing);
}
}
const adminRepository = dataSource.getRepository(AdminUser);
const username = process.env.ADMIN_USERNAME ?? 'admin';
const existingAdmin = await adminRepository.findOne({ where: { username } });
if (!existingAdmin) {
await adminRepository.save(
adminRepository.create({
username,
passwordHash: bcrypt.hashSync(process.env.ADMIN_PASSWORD ?? 'admin123', 10),
nickname: 'Super Admin',
email: process.env.ADMIN_EMAIL ?? 'admin@example.com',
status: 'active',
isSuperAdmin: true,
roleIds: [],
}),
);
}
}
private async loadDatabaseRecords() {
const dataSource = this.dataSource as DataSource;
const permissions = await dataSource.getRepository(Permission).find({
order: { id: 'ASC' },
});
this.permissions.splice(
0,
this.permissions.length,
...permissions.map((permission) => this.toPermissionRecord(permission)),
);
const roles = await dataSource.getRepository(Role).find({
order: { id: 'ASC' },
});
this.roles.splice(
0,
this.roles.length,
...roles.map((role) => this.toRoleRecord(role)),
);
const admins = await dataSource.getRepository(AdminUser).find({
order: { id: 'ASC' },
});
this.admins.splice(
0,
this.admins.length,
...admins.map((admin) => this.toAdminRecord(admin)),
);
}
private permissionSeeds() {
return [
['permission:read', '查看权限'],
['permission:create', '创建权限'],
['role:read', '查看角色'],
['role:create', '创建角色'],
['role:update', '更新角色'],
['admin-user:read', '查看人员'],
['admin-user:create', '创建人员'],
['admin-user:update', '更新人员'],
['user:read', '查看用户'],
['user:update', '更新用户'],
['drama:read', '查看短剧'],
['drama:create', '创建短剧'],
['drama:update', '更新短剧'],
['episode:create', '创建剧集'],
['episode:update', '更新剧集'],
['media:read', '查看媒体'],
['media:create', '创建媒体'],
['data:read', '查看数据'],
['data:sync', '同步数据'],
['payment:read', '查看支付记录'],
['log:read', '查看日志'],
] as const;
}
private toPermissionRecord(permission: Permission): PermissionRecord {
return {
id: Number(permission.id),
code: permission.code,
name: permission.name,
description: permission.description,
createdAt: permission.createdAt?.toISOString?.() ?? new Date().toISOString(),
updatedAt: permission.updatedAt?.toISOString?.() ?? new Date().toISOString(),
};
}
private toRoleRecord(role: Role): RoleRecord {
const permissionIds = role.permissionIds ?? [];
return {
id: Number(role.id),
code: role.code,
name: role.name,
description: role.description,
permissionIds,
permissions: this.permissions.filter((permission) =>
permissionIds.includes(permission.id),
),
createdAt: role.createdAt?.toISOString?.() ?? new Date().toISOString(),
updatedAt: role.updatedAt?.toISOString?.() ?? new Date().toISOString(),
};
}
private toAdminRecord(admin: AdminUser): AdminUserRecord {
return {
id: Number(admin.id),
username: admin.username,
passwordHash: admin.passwordHash,
nickname: admin.nickname,
email: admin.email,
status: admin.status as 'active' | 'disabled',
isSuperAdmin: admin.isSuperAdmin,
roleIds: admin.roleIds ?? [],
createdAt: admin.createdAt?.toISOString?.() ?? new Date().toISOString(),
updatedAt: admin.updatedAt?.toISOString?.() ?? new Date().toISOString(),
};
}
private paginate<T>(
records: T[],
input: PaginationInput,

View File

@@ -22,6 +22,9 @@ export class AdminUser {
@Column({ type: 'varchar', length: 128, nullable: true })
nickname?: string;
@Column({ type: 'varchar', length: 255, nullable: true })
email?: string;
@Column({ type: 'varchar', length: 32, default: 'active' })
status: string;

View File

@@ -38,7 +38,7 @@ export class AdminJwtAuthGuard implements CanActivate {
throw new UnauthorizedException('Admin not authenticated');
}
const adminUser = this.adminService.findAdminById(payload.sub);
const adminUser = await this.adminService.findAdminById(payload.sub);
if (!adminUser || adminUser.status !== 'active') {
throw new UnauthorizedException('Admin not authenticated');
}

View File

@@ -14,7 +14,7 @@ export class PermissionsGuard implements CanActivate {
private readonly adminService: AdminService,
) {}
canActivate(context: ExecutionContext): boolean {
async canActivate(context: ExecutionContext): Promise<boolean> {
const required =
this.reflector.getAllAndOverride<string[]>(
REQUIRED_PERMISSIONS_METADATA,
@@ -38,7 +38,9 @@ export class PermissionsGuard implements CanActivate {
return true;
}
const permissions = this.adminService.getPermissionCodesForAdmin(adminUser.id);
const permissions = await this.adminService.getPermissionCodesForAdmin(
adminUser.id,
);
const allowed = required.every((permission) =>
permissions.includes(permission),
);

View File

@@ -12,7 +12,7 @@ export class AuthService {
async loginWithTikTok(dto: TikTokLoginDto) {
const tiktokOpenId = dto.mockOpenId ?? this.resolveOpenIdFromCode(dto.code);
const result = this.usersService.upsertTikTokUser({
const result = await this.usersService.upsertTikTokUser({
tiktokOpenId,
tiktokUnionId: dto.tiktokUnionId,
nickname: dto.nickname,

View File

@@ -28,7 +28,7 @@ export class JwtAuthGuard implements CanActivate {
try {
const payload = await this.jwtService.verifyAsync<{ sub: number }>(token);
const user = this.usersService.findById(payload.sub);
const user = await this.usersService.findById(payload.sub);
if (!user || user.status !== 'active') {
throw new UnauthorizedException('Not authenticated');
}

View File

@@ -0,0 +1,64 @@
import { Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
import { PermissionsGuard } from '../admin/guards/permissions.guard';
import { DataService } from './data.service';
@ApiTags('Data')
@Controller('/api/admin/v1/data')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
export class DataController {
constructor(private readonly dataService: DataService) {}
@Post('/sync')
@RequirePermissions('data:sync')
sync(@Body() body: { dramaId?: number }) {
return this.dataService.sync(body);
}
@Get('/overview')
@RequirePermissions('data:read')
getOverview() {
return this.dataService.getOverview();
}
@Get('/dramas')
@RequirePermissions('data:read')
listDramaMetrics(
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.dataService.listDramaMetrics({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get('/episodes')
@RequirePermissions('data:read')
listEpisodeMetrics(
@Query('dramaId') dramaId?: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.dataService.listEpisodeMetrics({
dramaId: dramaId ? Number(dramaId) : undefined,
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get('/sync-jobs')
@RequirePermissions('data:read')
listSyncJobs(
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.dataService.listSyncJobs({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { AdminModule } from '../admin/admin.module';
import { DramasModule } from '../dramas/dramas.module';
import { DataController } from './data.controller';
import { DataService } from './data.service';
import { TikTokDataProvider } from './providers/tiktok-data.provider';
@Module({
imports: [AdminModule, DramasModule],
controllers: [DataController],
providers: [DataService, TikTokDataProvider],
})
export class DataModule {}

View File

@@ -0,0 +1,312 @@
import { Injectable, Optional } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { DramasService } from '../dramas/dramas.service';
import { DataSyncJob } from './entities/data-sync-job.entity';
import { DramaMetric } from './entities/drama-metric.entity';
import { EpisodeMetric } from './entities/episode-metric.entity';
import { TikTokDataProvider } from './providers/tiktok-data.provider';
interface PaginationInput {
page: number;
pageSize: number;
}
interface SyncInput {
dramaId?: number;
}
export interface DramaMetricRecord {
dramaId: number;
title: string;
plays: number;
likes: number;
shares: number;
comments: number;
completionRate: number;
averageWatchSeconds: number;
syncedAt: string;
}
export interface EpisodeMetricRecord {
dramaId: number;
episodeId: number;
title: string;
episodeNo: number;
plays: number;
likes: number;
shares: number;
comments: number;
completionRate: number;
averageWatchSeconds: number;
syncedAt: string;
}
export interface SyncJobRecord {
id: number;
jobId: string;
status: 'completed' | 'failed';
dramaId?: number;
dramaCount: number;
episodeCount: number;
createdAt: string;
}
@Injectable()
export class DataService {
private syncJobSequence = 1;
private readonly dramaMetrics = new Map<number, DramaMetricRecord>();
private readonly episodeMetrics = new Map<number, EpisodeMetricRecord>();
private readonly syncJobs: SyncJobRecord[] = [];
constructor(
private readonly dramasService: DramasService,
private readonly tiktokDataProvider: TikTokDataProvider,
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {}
async sync(input: SyncInput = {}) {
const now = new Date().toISOString();
const dramas = (await this.dramasService.listAllDramas()).filter(
(drama) => !input.dramaId || drama.id === input.dramaId,
);
const dramaIds = new Set(dramas.map((drama) => drama.id));
const episodes = (await this.dramasService.listAllEpisodes()).filter(
(episode) => dramaIds.has(episode.dramaId),
);
const dramaRecords = dramas.map((drama) => ({
dramaId: drama.id,
title: drama.title,
...this.tiktokDataProvider.getDramaMetrics(drama),
syncedAt: now,
}));
const episodeRecords = episodes.map((episode) => ({
dramaId: episode.dramaId,
episodeId: episode.id,
title: episode.title,
episodeNo: episode.episodeNo,
...this.tiktokDataProvider.getEpisodeMetrics(episode),
syncedAt: now,
}));
for (const record of dramaRecords) {
this.dramaMetrics.set(record.dramaId, record);
}
for (const record of episodeRecords) {
this.episodeMetrics.set(record.episodeId, record);
}
const job: SyncJobRecord = {
id: this.syncJobSequence++,
jobId: `DATA_SYNC_${Date.now()}_${this.syncJobSequence}`,
status: 'completed',
dramaId: input.dramaId,
dramaCount: dramas.length,
episodeCount: episodes.length,
createdAt: now,
};
this.syncJobs.unshift(job);
if (this.hasDatabase()) {
const dramaMetricRepository = this.dataSource.getRepository(DramaMetric);
const episodeMetricRepository = this.dataSource.getRepository(EpisodeMetric);
const syncJobRepository = this.dataSource.getRepository(DataSyncJob);
for (const record of dramaRecords) {
const existing = await dramaMetricRepository.findOne({
where: { dramaId: record.dramaId },
});
await dramaMetricRepository.save(
dramaMetricRepository.create({
...existing,
...record,
syncedAt: new Date(record.syncedAt),
}),
);
}
for (const record of episodeRecords) {
const existing = await episodeMetricRepository.findOne({
where: { episodeId: record.episodeId },
});
await episodeMetricRepository.save(
episodeMetricRepository.create({
...existing,
...record,
syncedAt: new Date(record.syncedAt),
}),
);
}
await syncJobRepository.save(
syncJobRepository.create({
...job,
createdAt: new Date(job.createdAt),
}),
);
}
return job;
}
async getOverview() {
const dramaRecords = this.hasDatabase()
? (await this.dataSource.getRepository(DramaMetric).find()).map((record) =>
this.toDramaMetricRecord(record),
)
: Array.from(this.dramaMetrics.values());
const episodeRecords = this.hasDatabase()
? (await this.dataSource.getRepository(EpisodeMetric).find()).map((record) =>
this.toEpisodeMetricRecord(record),
)
: Array.from(this.episodeMetrics.values());
const latestJob = this.hasDatabase()
? (
await this.dataSource.getRepository(DataSyncJob).find({
order: { id: 'DESC' },
take: 1,
})
)[0]
: undefined;
return {
totalDramas: dramaRecords.length,
totalEpisodes: episodeRecords.length,
totalPlays: episodeRecords.reduce((sum, item) => sum + item.plays, 0),
totalLikes: episodeRecords.reduce((sum, item) => sum + item.likes, 0),
totalShares: episodeRecords.reduce((sum, item) => sum + item.shares, 0),
totalComments: episodeRecords.reduce((sum, item) => sum + item.comments, 0),
latestSyncedAt: latestJob?.createdAt?.toISOString?.() ?? this.syncJobs[0]?.createdAt,
};
}
async listDramaMetrics(input: PaginationInput): Promise<PaginatedResponse<DramaMetricRecord>> {
if (this.hasDatabase()) {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const repository = this.dataSource.getRepository(DramaMetric);
const [records, total] = await repository.findAndCount({
order: { dramaId: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return {
list: records.map((record) => this.toDramaMetricRecord(record)),
pagination: { page, pageSize, total },
};
}
return this.paginate(Array.from(this.dramaMetrics.values()), input);
}
async listEpisodeMetrics(
input: PaginationInput & { dramaId?: number },
): Promise<PaginatedResponse<EpisodeMetricRecord>> {
if (this.hasDatabase()) {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const repository = this.dataSource.getRepository(EpisodeMetric);
const [records, total] = await repository.findAndCount({
where: input.dramaId ? { dramaId: input.dramaId } : {},
order: { episodeNo: 'ASC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return {
list: records.map((record) => this.toEpisodeMetricRecord(record)),
pagination: { page, pageSize, total },
};
}
const records = Array.from(this.episodeMetrics.values()).filter(
(item) => !input.dramaId || item.dramaId === input.dramaId,
);
return this.paginate(records, input);
}
async listSyncJobs(input: PaginationInput): Promise<PaginatedResponse<SyncJobRecord>> {
if (this.hasDatabase()) {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const repository = this.dataSource.getRepository(DataSyncJob);
const [records, total] = await repository.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return {
list: records.map((record) => this.toSyncJobRecord(record)),
pagination: { page, pageSize, total },
};
}
return this.paginate(this.syncJobs, input);
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private toDramaMetricRecord(record: DramaMetric): DramaMetricRecord {
return {
dramaId: Number(record.dramaId),
title: record.title,
plays: Number(record.plays),
likes: Number(record.likes),
shares: Number(record.shares),
comments: Number(record.comments),
completionRate: record.completionRate,
averageWatchSeconds: record.averageWatchSeconds,
syncedAt: record.syncedAt.toISOString(),
};
}
private toEpisodeMetricRecord(record: EpisodeMetric): EpisodeMetricRecord {
return {
dramaId: Number(record.dramaId),
episodeId: Number(record.episodeId),
title: record.title,
episodeNo: record.episodeNo,
plays: Number(record.plays),
likes: Number(record.likes),
shares: Number(record.shares),
comments: Number(record.comments),
completionRate: record.completionRate,
averageWatchSeconds: record.averageWatchSeconds,
syncedAt: record.syncedAt.toISOString(),
};
}
private toSyncJobRecord(record: DataSyncJob): SyncJobRecord {
return {
id: Number(record.id),
jobId: record.jobId,
status: record.status as 'completed' | 'failed',
dramaId: record.dramaId ? Number(record.dramaId) : undefined,
dramaCount: record.dramaCount,
episodeCount: record.episodeCount,
createdAt: record.createdAt.toISOString(),
};
}
private paginate<T>(records: T[], input: PaginationInput): PaginatedResponse<T> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const start = (page - 1) * pageSize;
return {
list: records.slice(start, start + pageSize),
pagination: {
page,
pageSize,
total: records.length,
},
};
}
}

View File

@@ -0,0 +1,26 @@
import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';
@Entity('data_sync_jobs')
export class DataSyncJob {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ type: 'varchar', length: 128 })
jobId: string;
@Column({ type: 'varchar', length: 32 })
status: string;
@Column({ type: 'bigint', nullable: true })
dramaId?: number;
@Column({ type: 'int', default: 0 })
dramaCount: number;
@Column({ type: 'int', default: 0 })
episodeCount: number;
@CreateDateColumn()
createdAt: Date;
}

View File

@@ -0,0 +1,48 @@
import {
Column,
CreateDateColumn,
Entity,
Index,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('drama_metrics')
export class DramaMetric {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ type: 'bigint' })
dramaId: number;
@Column({ type: 'varchar', length: 255 })
title: string;
@Column({ type: 'bigint', default: 0 })
plays: number;
@Column({ type: 'bigint', default: 0 })
likes: number;
@Column({ type: 'bigint', default: 0 })
shares: number;
@Column({ type: 'bigint', default: 0 })
comments: number;
@Column({ type: 'float', default: 0 })
completionRate: number;
@Column({ type: 'int', default: 0 })
averageWatchSeconds: number;
@Column({ type: 'datetime' })
syncedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@@ -0,0 +1,55 @@
import {
Column,
CreateDateColumn,
Entity,
Index,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity('episode_metrics')
export class EpisodeMetric {
@PrimaryGeneratedColumn()
id: number;
@Index()
@Column({ type: 'bigint' })
dramaId: number;
@Index({ unique: true })
@Column({ type: 'bigint' })
episodeId: number;
@Column({ type: 'varchar', length: 255 })
title: string;
@Column({ type: 'int' })
episodeNo: number;
@Column({ type: 'bigint', default: 0 })
plays: number;
@Column({ type: 'bigint', default: 0 })
likes: number;
@Column({ type: 'bigint', default: 0 })
shares: number;
@Column({ type: 'bigint', default: 0 })
comments: number;
@Column({ type: 'float', default: 0 })
completionRate: number;
@Column({ type: 'int', default: 0 })
averageWatchSeconds: number;
@Column({ type: 'datetime' })
syncedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}

View File

@@ -0,0 +1,29 @@
import { Injectable } from '@nestjs/common';
import { DramaRecord, EpisodeRecord } from '../../dramas/interfaces/drama-records.interface';
@Injectable()
export class TikTokDataProvider {
getDramaMetrics(drama: DramaRecord) {
const base = drama.id * 1000 + drama.totalEpisodes * 100;
return {
plays: base + 500,
likes: base + 80,
shares: drama.id * 13 + 20,
comments: drama.id * 7 + 12,
completionRate: 0.68,
averageWatchSeconds: 96,
};
}
getEpisodeMetrics(episode: EpisodeRecord) {
const base = episode.id * 500 + episode.episodeNo * 50;
return {
plays: base + 300,
likes: base + 40,
shares: episode.id * 5 + 8,
comments: episode.id * 3 + 6,
completionRate: 0.72,
averageWatchSeconds: Math.min(episode.durationSeconds || 180, 120),
};
}
}

View File

@@ -0,0 +1,53 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AdminUser } from '../admin/entities/admin-user.entity';
import { Permission } from '../admin/entities/permission.entity';
import { Role } from '../admin/entities/role.entity';
import { DataSyncJob } from '../data/entities/data-sync-job.entity';
import { DramaMetric } from '../data/entities/drama-metric.entity';
import { EpisodeMetric } from '../data/entities/episode-metric.entity';
import { Drama } from '../dramas/entities/drama.entity';
import { Episode } from '../dramas/entities/episode.entity';
import { PlaybackErrorLog } from '../logs/entities/playback-error-log.entity';
import { RequestLog } from '../logs/entities/request-log.entity';
import { Cover } from '../media/entities/cover.entity';
import { MediaUploadJob } from '../media/entities/media-upload-job.entity';
import { Order } from '../orders/entities/order.entity';
import { UserEpisodeUnlock } from '../orders/entities/user-episode-unlock.entity';
import { User } from '../users/entities/user.entity';
const databaseImports = process.env.DB_HOST
? [
TypeOrmModule.forRoot({
type: 'mysql',
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT) || 3306,
username: process.env.DB_USERNAME ?? 'root',
password: process.env.DB_PASSWORD ?? '',
database: process.env.DB_DATABASE ?? 'cth_tk',
entities: [
AdminUser,
Permission,
Role,
DataSyncJob,
DramaMetric,
EpisodeMetric,
Drama,
Episode,
PlaybackErrorLog,
RequestLog,
Cover,
MediaUploadJob,
Order,
UserEpisodeUnlock,
User,
],
synchronize: process.env.DB_SYNCHRONIZE === 'true',
}),
]
: [];
@Module({
imports: databaseImports,
})
export class DatabaseModule {}

View File

@@ -1,87 +1,134 @@
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
import { PermissionsGuard } from '../admin/guards/permissions.guard';
import { CreateDramaDto } from './dto/create-drama.dto';
import { CreateEpisodeDto } from './dto/create-episode.dto';
import { DramasService } from './dramas.service';
import { PublishStatus } from './drama-status.enum';
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { RequirePermissions } from "../admin/decorators/require-permissions.decorator";
import { AdminJwtAuthGuard } from "../admin/guards/admin-jwt-auth.guard";
import { PermissionsGuard } from "../admin/guards/permissions.guard";
import { ConfigureEpisodesDto } from "./dto/configure-episodes.dto";
import { CreateDramaDto } from "./dto/create-drama.dto";
import { CreateEpisodeDto } from "./dto/create-episode.dto";
import { UpdateDramaDto } from "./dto/update-drama.dto";
import { UpdateEpisodeDto } from "./dto/update-episode.dto";
import { DramasService } from "./dramas.service";
import { PublishStatus } from "./drama-status.enum";
@ApiTags('Dramas')
@ApiTags("Dramas")
@Controller()
export class DramasController {
constructor(private readonly dramasService: DramasService) {}
constructor(private readonly dramasService: DramasService) {}
@Post('/api/admin/v1/dramas')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions('drama:create')
createDrama(@Body() dto: CreateDramaDto) {
return this.dramasService.createDrama(dto);
}
@Post("/api/admin/v1/dramas")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("drama:create")
createDrama(@Body() dto: CreateDramaDto) {
return this.dramasService.createDrama(dto);
}
@Get('/api/admin/v1/dramas')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions('drama:read')
listAdminDramas(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
return this.dramasService.listAdminDramas({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get("/api/admin/v1/dramas")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("drama:read")
listAdminDramas(@Query("page") page?: string, @Query("pageSize") pageSize?: string) {
return this.dramasService.listAdminDramas({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Post('/api/admin/v1/episodes')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions('episode:create')
createEpisode(@Body() dto: CreateEpisodeDto) {
return this.dramasService.createEpisode(dto);
}
@Get("/api/admin/v1/dramas/:id")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("drama:read")
getDrama(@Param("id") id: string) {
return this.dramasService.getDramaOrThrow(Number(id));
}
@Post('/api/admin/v1/dramas/:id/submit-review')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions('drama:update')
submitReview(@Param('id') id: string) {
return this.dramasService.submitReview(Number(id));
}
@Patch("/api/admin/v1/dramas/:id")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("drama:update")
updateDrama(@Param("id") id: string, @Body() dto: UpdateDramaDto) {
return this.dramasService.updateDrama(Number(id), dto);
}
@Patch('/api/admin/v1/episodes/:id/publish-status')
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions('episode:update')
updatePublishStatus(
@Param('id') id: string,
@Body() dto: { publishStatus: PublishStatus },
) {
return this.dramasService.updateEpisodePublishStatus(
Number(id),
dto.publishStatus,
);
}
@Post("/api/admin/v1/dramas/:id/episodes/batch")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:create")
configureEpisodes(@Param("id") id: string, @Body() dto: ConfigureEpisodesDto) {
return this.dramasService.configureEpisodes(Number(id), dto);
}
@Get('/api/app/v1/dramas')
listPublishedDramas(
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.dramasService.listPublishedDramas({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get("/api/admin/v1/dramas/:id/episodes")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:update")
listAdminEpisodes(@Param("id") id: string, @Query("page") page?: string, @Query("pageSize") pageSize?: string) {
return this.dramasService.listAdminEpisodes(Number(id), {
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get('/api/app/v1/dramas/:id/episodes')
listPublishedEpisodes(
@Param('id') id: string,
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.dramasService.listPublishedEpisodes(Number(id), {
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Post("/api/admin/v1/episodes")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:create")
createEpisode(@Body() dto: CreateEpisodeDto) {
return this.dramasService.createEpisode(dto);
}
@Patch("/api/admin/v1/episodes/:id")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:update")
updateEpisode(@Param("id") id: string, @Body() dto: UpdateEpisodeDto) {
return this.dramasService.updateEpisode(Number(id), dto);
}
@Patch("/api/admin/v1/dramas/:dramaId/episodes/:episodeId")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:update")
updateDramaEpisode(@Param("dramaId") dramaId: string, @Param("episodeId") episodeId: string, @Body() dto: UpdateEpisodeDto) {
return this.dramasService.updateDramaEpisode(Number(dramaId), Number(episodeId), dto);
}
@Post("/api/admin/v1/dramas/:id/submit-review")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("drama:update")
submitReview(@Param("id") id: string) {
return this.dramasService.submitReview(Number(id));
}
@Patch("/api/admin/v1/episodes/:id/publish-status")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
@RequirePermissions("episode:update")
updatePublishStatus(@Param("id") id: string, @Body() dto: { publishStatus: PublishStatus }) {
return this.dramasService.updateEpisodePublishStatus(Number(id), dto.publishStatus);
}
@Get("/api/app/v1/dramas")
listPublishedDramas(@Query("page") page?: string, @Query("pageSize") pageSize?: string, @Query("title") title?: string) {
return this.dramasService.listPublishedDramas({
page: Number(page) || 1,
pageSize: Number(pageSize) || 10,
title,
});
}
@Get("/api/app/v1/dramas/:id/episodes")
listPublishedEpisodes(@Param("id") id: string, @Query("page") page?: string, @Query("pageSize") pageSize?: string) {
return this.dramasService.listPublishedEpisodes(Number(id), {
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Get("/api/app/v1/dramas/:id")
getPublishedDrama(@Param("id") id: string) {
return this.dramasService.getPublishedDramaOrThrow(Number(id));
}
}

View File

@@ -2,10 +2,19 @@ import {
ConflictException,
Injectable,
NotFoundException,
Optional,
UnprocessableEntityException,
} from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource, Like } from 'typeorm';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { ConfigureEpisodesDto } from './dto/configure-episodes.dto';
import { CreateDramaDto } from './dto/create-drama.dto';
import { CreateEpisodeDto } from './dto/create-episode.dto';
import { UpdateDramaDto } from './dto/update-drama.dto';
import { UpdateEpisodeDto } from './dto/update-episode.dto';
import { Drama } from './entities/drama.entity';
import { Episode } from './entities/episode.entity';
import { PublishStatus } from './drama-status.enum';
import {
DramaRecord,
@@ -17,6 +26,10 @@ interface PaginationInput {
pageSize: number;
}
interface PublishedDramaListInput extends PaginationInput {
title?: string;
}
@Injectable()
export class DramasService {
private dramaSequence = 1;
@@ -24,7 +37,44 @@ export class DramasService {
private readonly dramas: DramaRecord[] = [];
private readonly episodes: EpisodeRecord[] = [];
createDrama(dto: CreateDramaDto): DramaRecord {
constructor(
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {}
async createDrama(dto: CreateDramaDto): Promise<DramaRecord> {
const { totalEpisodes } = dto;
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Drama);
const entity = repository.create({
tiktokAlbumId: dto.tiktokAlbumId,
title: dto.title,
description: dto.description,
coverId: dto.coverId,
coverUrl: dto.coverUrl,
portraitCoverUrl: dto.portraitCoverUrl,
landscapeCoverUrl: dto.landscapeCoverUrl,
type: dto.type,
tags: dto.tags ?? [],
region: dto.region,
language: dto.language,
year: dto.year,
status: dto.status ?? PublishStatus.Draft,
sortOrder: dto.sortOrder ?? 0,
isRecommended: dto.isRecommended ?? false,
onlineVersion: dto.onlineVersion ?? 1,
});
const saved = await repository.save(entity);
if (totalEpisodes) {
await this.configureEpisodes(Number(saved.id), {
episodeCount: totalEpisodes,
});
return this.getDramaOrThrow(Number(saved.id));
}
return this.toDramaRecord(saved, 0, 0);
}
const now = new Date().toISOString();
const drama: DramaRecord = {
id: this.dramaSequence++,
@@ -44,41 +94,172 @@ export class DramasService {
sortOrder: dto.sortOrder ?? 0,
isRecommended: dto.isRecommended ?? false,
onlineVersion: dto.onlineVersion ?? 1,
totalEpisodes: 0,
publishedEpisodes: 0,
createdAt: now,
updatedAt: now,
};
this.dramas.push(drama);
if (totalEpisodes) {
await this.configureEpisodes(drama.id, { episodeCount: totalEpisodes });
return this.getDramaOrThrow(drama.id);
}
return drama;
}
listAdminDramas(pagination: PaginationInput): PaginatedResponse<DramaRecord> {
return this.paginate(this.sortDramas(this.dramas), pagination);
async listAdminDramas(
pagination: PaginationInput,
): Promise<PaginatedResponse<DramaRecord>> {
if (this.hasDatabase()) {
const { page, pageSize, skip, take } = this.resolvePagination(pagination);
const [records, total] = await this.dataSource
.getRepository(Drama)
.findAndCount({
order: { sortOrder: 'DESC', id: 'DESC' },
skip,
take,
});
const list = await Promise.all(
records.map((drama) => this.toDramaRecordWithCounts(drama)),
);
return { list, pagination: { page, pageSize, total } };
}
return this.paginate(
this.sortDramas(this.dramas.map((drama) => this.withEpisodeCounts(drama))),
pagination,
);
}
createEpisode(dto: CreateEpisodeDto): EpisodeRecord {
async getDramaOrThrow(id: number): Promise<DramaRecord> {
if (this.hasDatabase()) {
const drama = await this.dataSource
.getRepository(Drama)
.findOne({ where: { id } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
return this.toDramaRecordWithCounts(drama);
}
const drama = this.dramas.find((item) => item.id === id);
if (!drama) {
throw new NotFoundException('Drama not found');
}
return this.withEpisodeCounts(drama);
}
async updateDrama(id: number, dto: UpdateDramaDto): Promise<DramaRecord> {
const { totalEpisodes, ...dramaUpdates } = dto;
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Drama);
const drama = await repository.findOne({ where: { id } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
repository.merge(drama, {
...dramaUpdates,
tags: dramaUpdates.tags ?? drama.tags,
});
const saved = await repository.save(drama);
if (totalEpisodes) {
await this.configureEpisodes(Number(saved.id), {
episodeCount: totalEpisodes,
});
}
return this.toDramaRecordWithCounts(saved);
}
const drama = this.dramas.find((item) => item.id === id);
if (!drama) {
throw new NotFoundException('Drama not found');
}
Object.assign(drama, {
...dramaUpdates,
tags: dramaUpdates.tags ?? drama.tags,
updatedAt: new Date().toISOString(),
});
if (totalEpisodes) {
await this.configureEpisodes(drama.id, { episodeCount: totalEpisodes });
}
return this.withEpisodeCounts(drama);
}
async createEpisode(dto: CreateEpisodeDto): Promise<EpisodeRecord> {
const dramaId = dto.dramaId ?? dto.albumId;
const episodeNo = dto.episodeNo ?? dto.seq;
if (!dramaId || !episodeNo) {
throw new NotFoundException('Drama not found');
}
const freeType = dto.freeType ?? (dto.isPaid ? 'paid' : 'free');
const price = dto.price ?? dto.unlockPrice ?? 0;
const publishStatus = dto.publishStatus ?? dto.status ?? PublishStatus.Draft;
const reviewStatus =
dto.reviewStatus ??
(publishStatus === PublishStatus.Published ? 'approved' : 'not_submitted');
if (this.hasDatabase()) {
const dramaRepository = this.dataSource.getRepository(Drama);
const drama = await dramaRepository.findOne({ where: { id: dramaId } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
const episodeRepository = this.dataSource.getRepository(Episode);
const duplicate = await episodeRepository.findOne({
where: { dramaId, episodeNo },
});
if (duplicate) {
throw new ConflictException(
'Episode number already exists in this drama',
);
}
const entity = episodeRepository.create({
dramaId,
tiktokEpisodeId: dto.tiktokEpisodeId,
episodeNo,
title: dto.title,
description: dto.description,
byteplusVid: dto.byteplusVid,
coverId: dto.coverId,
coverUrl: dto.coverUrl ?? '',
videoUrl: dto.videoUrl,
trialDurationSeconds: dto.trialDurationSeconds,
durationSeconds: dto.durationSeconds ?? 0,
width: dto.width,
height: dto.height,
isPaid: freeType === 'paid',
freeType,
unlockPrice: price,
price,
publishAt: dto.publishAt ? new Date(dto.publishAt) : undefined,
nextReleaseAt: dto.nextReleaseAt ? new Date(dto.nextReleaseAt) : undefined,
status: publishStatus,
reviewStatus,
publishStatus,
});
const saved = await episodeRepository.save(entity);
return this.toEpisodeRecord(saved);
}
const drama = this.dramas.find((item) => item.id === dramaId);
if (!drama) {
throw new NotFoundException('Drama not found');
}
const duplicate = this.episodes.some(
(item) =>
item.dramaId === dramaId && item.episodeNo === episodeNo,
(item) => item.dramaId === dramaId && item.episodeNo === episodeNo,
);
if (duplicate) {
throw new ConflictException('Episode number already exists in this drama');
}
const now = new Date().toISOString();
const freeType = dto.freeType ?? (dto.isPaid ? 'paid' : 'free');
const price = dto.price ?? dto.unlockPrice ?? 0;
const episode: EpisodeRecord = {
id: this.episodeSequence++,
dramaId,
@@ -90,19 +271,21 @@ export class DramasService {
description: dto.description,
byteplusVid: dto.byteplusVid,
coverId: dto.coverId,
coverUrl: dto.coverUrl,
coverUrl: dto.coverUrl ?? '',
videoUrl: dto.videoUrl,
trialDurationSeconds: dto.trialDurationSeconds,
durationSeconds: dto.durationSeconds,
durationSeconds: dto.durationSeconds ?? 0,
width: dto.width,
height: dto.height,
isPaid: freeType === 'paid',
freeType,
unlockPrice: price,
price,
publishAt: dto.publishAt,
nextReleaseAt: dto.nextReleaseAt,
status: dto.status ?? dto.publishStatus ?? PublishStatus.Draft,
reviewStatus: dto.reviewStatus ?? 'pending',
publishStatus: dto.publishStatus ?? dto.status ?? PublishStatus.Draft,
status: publishStatus,
reviewStatus,
publishStatus,
createdAt: now,
updatedAt: now,
};
@@ -111,21 +294,392 @@ export class DramasService {
return episode;
}
listPublishedDramas(
async configureEpisodes(
dramaId: number,
dto: ConfigureEpisodesDto,
): Promise<PaginatedResponse<EpisodeRecord>> {
if (this.hasDatabase()) {
const dramaRepository = this.dataSource.getRepository(Drama);
const drama = await dramaRepository.findOne({ where: { id: dramaId } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
const episodeRepository = this.dataSource.getRepository(Episode);
const existing = await episodeRepository.find({
where: { dramaId },
order: { episodeNo: 'ASC' },
});
if (dto.episodeCount < existing.length) {
const removable = existing.slice(dto.episodeCount);
const hasLockedEpisode = removable.some(
(episode) =>
episode.byteplusVid ||
episode.publishStatus !== PublishStatus.Draft ||
episode.reviewStatus !== 'not_submitted',
);
if (hasLockedEpisode) {
throw new UnprocessableEntityException(
'Only empty draft tail episodes can be removed',
);
}
await episodeRepository.remove(removable);
}
for (
let episodeNo = existing.length + 1;
episodeNo <= dto.episodeCount;
episodeNo++
) {
await this.createEpisode({
dramaId,
episodeNo,
title: `${episodeNo}`,
coverUrl: drama.coverUrl,
durationSeconds: 0,
freeType: 'free',
price: 0,
reviewStatus: 'not_submitted',
publishStatus: PublishStatus.Draft,
status: PublishStatus.Draft,
});
}
const list = await episodeRepository.find({
where: { dramaId },
order: { episodeNo: 'ASC' },
});
const records = list.map((episode) => this.toEpisodeRecord(episode));
return {
list: records,
pagination: { page: 1, pageSize: records.length, total: records.length },
};
}
const drama = this.dramas.find((item) => item.id === dramaId);
if (!drama) {
throw new NotFoundException('Drama not found');
}
const existing = this.episodes
.filter((episode) => episode.dramaId === dramaId)
.sort((left, right) => left.episodeNo - right.episodeNo);
if (dto.episodeCount < existing.length) {
const removable = existing.slice(dto.episodeCount);
const hasLockedEpisode = removable.some(
(episode) =>
episode.byteplusVid ||
episode.publishStatus !== PublishStatus.Draft ||
episode.reviewStatus !== 'not_submitted',
);
if (hasLockedEpisode) {
throw new UnprocessableEntityException(
'Only empty draft tail episodes can be removed',
);
}
for (const episode of removable) {
const index = this.episodes.findIndex((item) => item.id === episode.id);
if (index >= 0) {
this.episodes.splice(index, 1);
}
}
}
for (
let episodeNo = existing.length + 1;
episodeNo <= dto.episodeCount;
episodeNo++
) {
await this.createEpisode({
dramaId,
episodeNo,
title: `${episodeNo}`,
coverUrl: drama.coverUrl,
durationSeconds: 0,
freeType: 'free',
price: 0,
reviewStatus: 'not_submitted',
publishStatus: PublishStatus.Draft,
status: PublishStatus.Draft,
});
}
const list = this.episodes
.filter((episode) => episode.dramaId === dramaId)
.sort((left, right) => left.episodeNo - right.episodeNo);
return {
list,
pagination: { page: 1, pageSize: list.length, total: list.length },
};
}
async listAdminEpisodes(
dramaId: number,
pagination: PaginationInput,
): PaginatedResponse<DramaRecord> {
): Promise<PaginatedResponse<EpisodeRecord>> {
await this.getDramaOrThrow(dramaId);
if (this.hasDatabase()) {
const { page, pageSize, skip, take } = this.resolvePagination(pagination);
const [records, total] = await this.dataSource
.getRepository(Episode)
.findAndCount({
where: { dramaId },
order: { episodeNo: 'ASC' },
skip,
take,
});
return {
list: records.map((episode) => this.toEpisodeRecord(episode)),
pagination: { page, pageSize, total },
};
}
const records = this.episodes
.filter((episode) => episode.dramaId === dramaId)
.sort((left, right) => left.episodeNo - right.episodeNo);
return this.paginate(records, pagination);
}
async updateEpisode(id: number, dto: UpdateEpisodeDto): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Episode);
const episode = await repository.findOne({ where: { id } });
if (!episode) {
throw new NotFoundException('Episode not found');
}
const freeType =
dto.freeType ??
(dto.isPaid === undefined
? episode.freeType
: dto.isPaid
? 'paid'
: 'free');
repository.merge(episode, {
...dto,
dramaId: dto.dramaId ?? dto.albumId ?? episode.dramaId,
episodeNo: dto.episodeNo ?? dto.seq ?? episode.episodeNo,
freeType,
isPaid: freeType === 'paid',
price: dto.price ?? dto.unlockPrice ?? episode.price,
unlockPrice: dto.unlockPrice ?? dto.price ?? episode.unlockPrice,
status: dto.status ?? dto.publishStatus ?? episode.status,
publishStatus: dto.publishStatus ?? dto.status ?? episode.publishStatus,
publishAt: dto.publishAt ? new Date(dto.publishAt) : episode.publishAt,
nextReleaseAt: dto.nextReleaseAt
? new Date(dto.nextReleaseAt)
: episode.nextReleaseAt,
});
const saved = await repository.save(episode);
return this.toEpisodeRecord(saved);
}
const episode = await this.getMemEpisodeOrThrow(id);
const freeType =
dto.freeType ??
(dto.isPaid === undefined
? episode.freeType
: dto.isPaid
? 'paid'
: 'free');
Object.assign(episode, {
...dto,
dramaId: dto.dramaId ?? dto.albumId ?? episode.dramaId,
albumId: dto.albumId ?? dto.dramaId ?? episode.albumId,
episodeNo: dto.episodeNo ?? dto.seq ?? episode.episodeNo,
seq: dto.seq ?? dto.episodeNo ?? episode.seq,
freeType,
isPaid: freeType === 'paid',
price: dto.price ?? dto.unlockPrice ?? episode.price,
unlockPrice: dto.unlockPrice ?? dto.price ?? episode.unlockPrice,
status: dto.status ?? dto.publishStatus ?? episode.status,
publishStatus: dto.publishStatus ?? dto.status ?? episode.publishStatus,
updatedAt: new Date().toISOString(),
});
return episode;
}
async updateDramaEpisode(
dramaId: number,
episodeId: number,
dto: UpdateEpisodeDto,
): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const episode = await this.dataSource.getRepository(Episode).findOne({
where: { id: episodeId, dramaId },
});
if (!episode) {
throw new NotFoundException('Episode not found');
}
} else {
const episode = await this.getMemEpisodeOrThrow(episodeId);
if (episode.dramaId !== dramaId) {
throw new NotFoundException('Episode not found');
}
}
return this.updateEpisode(episodeId, { ...dto, dramaId });
}
async attachEpisodeMedia(input: {
episodeId: number;
byteplusVid: string;
videoUrl: string;
storageBucket: string;
objectKey: string;
durationSeconds: number;
width: number;
height: number;
reviewStatus: EpisodeRecord['reviewStatus'];
reviewMessage?: string;
}): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Episode);
const episode = await repository.findOne({
where: { id: input.episodeId },
});
if (!episode) {
throw new NotFoundException('Episode not found');
}
episode.byteplusVid = input.byteplusVid;
episode.videoUrl = input.videoUrl;
episode.storageBucket = input.storageBucket;
episode.objectKey = input.objectKey;
episode.durationSeconds = input.durationSeconds;
episode.width = input.width;
episode.height = input.height;
episode.reviewStatus = input.reviewStatus;
episode.reviewMessage = input.reviewMessage;
const saved = await repository.save(episode);
return this.toEpisodeRecord(saved);
}
const episode = await this.getMemEpisodeOrThrow(input.episodeId);
episode.byteplusVid = input.byteplusVid;
episode.videoUrl = input.videoUrl;
episode.storageBucket = input.storageBucket;
episode.objectKey = input.objectKey;
episode.durationSeconds = input.durationSeconds;
episode.width = input.width;
episode.height = input.height;
episode.reviewStatus = input.reviewStatus;
episode.reviewMessage = input.reviewMessage;
episode.updatedAt = new Date().toISOString();
return episode;
}
async updateEpisodeReviewStatus(
episodeId: number,
reviewStatus: EpisodeRecord['reviewStatus'],
reviewMessage?: string,
): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Episode);
const episode = await repository.findOne({ where: { id: episodeId } });
if (!episode) {
throw new NotFoundException('Episode not found');
}
episode.reviewStatus = reviewStatus;
episode.reviewMessage = reviewMessage;
const saved = await repository.save(episode);
return this.toEpisodeRecord(saved);
}
const episode = await this.getMemEpisodeOrThrow(episodeId);
episode.reviewStatus = reviewStatus;
episode.reviewMessage = reviewMessage;
episode.updatedAt = new Date().toISOString();
return episode;
}
async listPublishedDramas(
input: PublishedDramaListInput,
): Promise<PaginatedResponse<DramaRecord>> {
const title = input.title?.trim();
if (this.hasDatabase()) {
const { page, pageSize, skip, take } = this.resolvePagination(input);
const [records, total] = await this.dataSource
.getRepository(Drama)
.findAndCount({
where: {
status: PublishStatus.Published,
...(title ? { title: Like(`%${title}%`) } : {}),
},
order: { sortOrder: 'DESC', id: 'DESC' },
skip,
take,
});
const list = await Promise.all(
records.map((drama) => this.toDramaRecordWithCounts(drama)),
);
return { list, pagination: { page, pageSize, total } };
}
return this.paginate(
this.sortDramas(
this.dramas.filter((item) => item.status === PublishStatus.Published),
this.dramas
.filter((item) => item.status === PublishStatus.Published)
.filter((item) => !title || item.title.includes(title))
.map((drama) => this.withEpisodeCounts(drama)),
),
pagination,
input,
);
}
listPublishedEpisodes(
async getPublishedDramaOrThrow(id: number): Promise<DramaRecord> {
if (this.hasDatabase()) {
const drama = await this.dataSource
.getRepository(Drama)
.findOne({ where: { id, status: PublishStatus.Published } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
return this.toDramaRecordWithCounts(drama);
}
const drama = this.dramas.find(
(item) => item.id === id && item.status === PublishStatus.Published,
);
if (!drama) {
throw new NotFoundException('Drama not found');
}
return this.withEpisodeCounts(drama);
}
async listPublishedEpisodes(
dramaId: number,
pagination: PaginationInput,
): PaginatedResponse<EpisodeRecord> {
): Promise<PaginatedResponse<EpisodeRecord>> {
if (this.hasDatabase()) {
const drama = await this.dataSource
.getRepository(Drama)
.findOne({ where: { id: dramaId, status: PublishStatus.Published } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
const { page, pageSize, skip, take } = this.resolvePagination(pagination);
const [records, total] = await this.dataSource
.getRepository(Episode)
.findAndCount({
where: {
dramaId,
status: PublishStatus.Published,
publishStatus: PublishStatus.Published,
reviewStatus: 'approved',
},
order: { episodeNo: 'ASC' },
skip,
take,
});
return {
list: records.map((episode) => this.toEpisodeRecord(episode)),
pagination: { page, pageSize, total },
};
}
const drama = this.dramas.find((item) => item.id === dramaId);
if (!drama || drama.status !== PublishStatus.Published) {
throw new NotFoundException('Drama not found');
@@ -136,14 +690,47 @@ export class DramasService {
(item) =>
item.dramaId === dramaId && item.status === PublishStatus.Published,
)
.filter(
(item) =>
item.publishStatus === PublishStatus.Published &&
item.reviewStatus === 'approved',
)
.sort((left, right) => left.episodeNo - right.episodeNo);
return this.paginate(episodes, pagination);
}
getPublishedEpisodeOrThrow(episodeId: number): EpisodeRecord {
async getPublishedEpisodeOrThrow(episodeId: number): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const episode = await this.dataSource.getRepository(Episode).findOne({
where: {
id: episodeId,
status: PublishStatus.Published,
publishStatus: PublishStatus.Published,
reviewStatus: 'approved',
},
});
if (!episode) {
throw new NotFoundException('Episode not found');
}
const drama = await this.dataSource
.getRepository(Drama)
.findOne({
where: { id: episode.dramaId, status: PublishStatus.Published },
});
if (!drama) {
throw new NotFoundException('Episode not found');
}
return this.toEpisodeRecord(episode);
}
const episode = this.episodes.find((item) => item.id === episodeId);
if (!episode || episode.status !== PublishStatus.Published) {
if (
!episode ||
episode.status !== PublishStatus.Published ||
episode.publishStatus !== PublishStatus.Published ||
episode.reviewStatus !== 'approved'
) {
throw new NotFoundException('Episode not found');
}
@@ -155,16 +742,39 @@ export class DramasService {
return episode;
}
getEpisodeOrThrow(episodeId: number): EpisodeRecord {
const episode = this.episodes.find((item) => item.id === episodeId);
if (!episode) {
throw new NotFoundException('Episode not found');
async getEpisodeOrThrow(episodeId: number): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const episode = await this.dataSource
.getRepository(Episode)
.findOne({ where: { id: episodeId } });
if (!episode) {
throw new NotFoundException('Episode not found');
}
return this.toEpisodeRecord(episode);
}
return episode;
return this.getMemEpisodeOrThrow(episodeId);
}
submitReview(albumId: number) {
async submitReview(albumId: number) {
if (this.hasDatabase()) {
const dramaRepository = this.dataSource.getRepository(Drama);
const drama = await dramaRepository.findOne({ where: { id: albumId } });
if (!drama) {
throw new NotFoundException('Drama not found');
}
const episodeRepository = this.dataSource.getRepository(Episode);
const episodes = await episodeRepository.find({
where: { dramaId: albumId },
});
for (const episode of episodes) {
episode.reviewStatus = 'approved';
episode.reviewMessage = 'Mock review approved';
}
await episodeRepository.save(episodes);
return { albumId, reviewStatus: 'approved' };
}
const album = this.dramas.find((item) => item.id === albumId);
if (!album) {
throw new NotFoundException('Drama not found');
@@ -173,24 +783,172 @@ export class DramasService {
this.episodes
.filter((episode) => episode.albumId === albumId)
.forEach((episode) => {
episode.reviewStatus = 'pending';
episode.reviewStatus = 'approved';
episode.reviewMessage = 'Mock review approved';
episode.updatedAt = new Date().toISOString();
});
return {
albumId,
reviewStatus: 'pending',
};
return { albumId, reviewStatus: 'approved' };
}
updateEpisodePublishStatus(episodeId: number, publishStatus: PublishStatus) {
const episode = this.getEpisodeOrThrow(episodeId);
async listAllDramas(): Promise<DramaRecord[]> {
if (this.hasDatabase()) {
const records = await this.dataSource
.getRepository(Drama)
.find({ order: { sortOrder: 'DESC', id: 'DESC' } });
return Promise.all(records.map((drama) => this.toDramaRecordWithCounts(drama)));
}
return this.sortDramas(this.dramas.map((drama) => this.withEpisodeCounts(drama)));
}
async listAllEpisodes(): Promise<EpisodeRecord[]> {
if (this.hasDatabase()) {
const records = await this.dataSource
.getRepository(Episode)
.find({ order: { id: 'ASC' } });
return records.map((episode) => this.toEpisodeRecord(episode));
}
return [...this.episodes].sort((left, right) => left.id - right.id);
}
async updateEpisodePublishStatus(
episodeId: number,
publishStatus: PublishStatus,
): Promise<EpisodeRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Episode);
const episode = await repository.findOne({ where: { id: episodeId } });
if (!episode) {
throw new NotFoundException('Episode not found');
}
episode.publishStatus = publishStatus;
episode.status = publishStatus;
const saved = await repository.save(episode);
return this.toEpisodeRecord(saved);
}
const episode = await this.getMemEpisodeOrThrow(episodeId);
episode.publishStatus = publishStatus;
episode.status = publishStatus;
episode.updatedAt = new Date().toISOString();
return episode;
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private getMemEpisodeOrThrow(episodeId: number): EpisodeRecord {
const episode = this.episodes.find((item) => item.id === episodeId);
if (!episode) {
throw new NotFoundException('Episode not found');
}
return episode;
}
private async toDramaRecordWithCounts(entity: Drama): Promise<DramaRecord> {
const episodeRepository = this.dataSource!.getRepository(Episode);
const dramaId = Number(entity.id);
const totalEpisodes = await episodeRepository.count({ where: { dramaId } });
const publishedEpisodes = await episodeRepository.count({
where: {
dramaId,
publishStatus: PublishStatus.Published,
reviewStatus: 'approved',
},
});
return this.toDramaRecord(entity, totalEpisodes, publishedEpisodes);
}
private toDramaRecord(
entity: Drama,
totalEpisodes: number,
publishedEpisodes: number,
): DramaRecord {
return {
id: Number(entity.id),
tiktokAlbumId: entity.tiktokAlbumId,
title: entity.title,
description: entity.description,
coverId: entity.coverId,
coverUrl: entity.coverUrl,
portraitCoverUrl: entity.portraitCoverUrl,
landscapeCoverUrl: entity.landscapeCoverUrl,
type: entity.type,
tags: entity.tags ?? [],
region: entity.region,
language: entity.language,
year: entity.year,
status: entity.status,
sortOrder: entity.sortOrder,
isRecommended: entity.isRecommended,
onlineVersion: entity.onlineVersion,
totalEpisodes,
publishedEpisodes,
createdAt: this.toIso(entity.createdAt),
updatedAt: this.toIso(entity.updatedAt),
};
}
private toEpisodeRecord(entity: Episode): EpisodeRecord {
const dramaId = Number(entity.dramaId);
return {
id: Number(entity.id),
dramaId,
albumId: dramaId,
tiktokEpisodeId: entity.tiktokEpisodeId,
episodeNo: entity.episodeNo,
seq: entity.episodeNo,
title: entity.title,
description: entity.description,
byteplusVid: entity.byteplusVid,
coverId: entity.coverId,
coverUrl: entity.coverUrl,
videoUrl: entity.videoUrl,
storageBucket: entity.storageBucket,
objectKey: entity.objectKey,
trialDurationSeconds: entity.trialDurationSeconds,
durationSeconds: entity.durationSeconds,
width: entity.width,
height: entity.height,
isPaid: entity.isPaid,
freeType: entity.freeType,
unlockPrice: entity.unlockPrice,
price: entity.price,
publishAt: this.toIsoOrUndefined(entity.publishAt),
nextReleaseAt: this.toIsoOrUndefined(entity.nextReleaseAt),
status: entity.status,
reviewStatus: entity.reviewStatus,
reviewMessage: entity.reviewMessage,
publishStatus: entity.publishStatus,
createdAt: this.toIso(entity.createdAt),
updatedAt: this.toIso(entity.updatedAt),
};
}
private toIso(value?: Date | string): string {
if (!value) {
return new Date().toISOString();
}
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
private toIsoOrUndefined(value?: Date | string): string | undefined {
if (!value) {
return undefined;
}
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
private resolvePagination(input: PaginationInput) {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
return { page, pageSize, skip: (page - 1) * pageSize, take: pageSize };
}
private sortDramas(records: DramaRecord[]) {
return [...records].sort((left, right) => {
if (right.sortOrder !== left.sortOrder) {
@@ -201,6 +959,19 @@ export class DramasService {
});
}
private withEpisodeCounts(drama: DramaRecord): DramaRecord {
const episodes = this.episodes.filter((episode) => episode.dramaId === drama.id);
return {
...drama,
totalEpisodes: episodes.length,
publishedEpisodes: episodes.filter(
(episode) =>
episode.publishStatus === PublishStatus.Published &&
episode.reviewStatus === 'approved',
).length,
};
}
private paginate<T>(
records: T[],
input: PaginationInput,

View File

@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsInt, Max, Min } from 'class-validator';
export class ConfigureEpisodesDto {
@ApiProperty()
@IsInt()
@Min(1)
@Max(500)
episodeCount: number;
}

View File

@@ -7,6 +7,7 @@ import {
IsOptional,
IsString,
IsUrl,
Max,
Min,
} from 'class-validator';
import { PublishStatus } from '../drama-status.enum';
@@ -88,6 +89,13 @@ export class CreateDramaDto {
@IsBoolean()
isRecommended?: boolean;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
@Max(500)
totalEpisodes?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()

View File

@@ -82,6 +82,18 @@ export class CreateEpisodeDto {
@Min(1)
durationSeconds: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
width?: number;
@ApiPropertyOptional()
@IsOptional()
@IsInt()
@Min(1)
height?: number;
@ApiPropertyOptional()
@IsOptional()
@IsBoolean()
@@ -119,10 +131,12 @@ export class CreateEpisodeDto {
@IsEnum(PublishStatus)
status?: PublishStatus;
@ApiPropertyOptional({ enum: ['pending', 'approved', 'rejected'] })
@ApiPropertyOptional({
enum: ['not_submitted', 'pending', 'reviewing', 'approved', 'rejected'],
})
@IsOptional()
@IsString()
reviewStatus?: 'pending' | 'approved' | 'rejected';
reviewStatus?: 'not_submitted' | 'pending' | 'reviewing' | 'approved' | 'rejected';
@ApiPropertyOptional({ enum: PublishStatus })
@IsOptional()

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateDramaDto } from './create-drama.dto';
export class UpdateDramaDto extends PartialType(CreateDramaDto) {}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateEpisodeDto } from './create-episode.dto';
export class UpdateEpisodeDto extends PartialType(CreateEpisodeDto) {}

View File

@@ -12,12 +12,18 @@ export class Drama {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'varchar', length: 128, nullable: true })
tiktokAlbumId?: string;
@Column({ type: 'varchar', length: 255 })
title: string;
@Column({ type: 'text', nullable: true })
description?: string;
@Column({ type: 'int', nullable: true })
coverId?: number;
@Column({ type: 'varchar', length: 1024 })
coverUrl: string;
@@ -51,6 +57,9 @@ export class Drama {
@Column({ type: 'boolean', default: false })
isRecommended: boolean;
@Column({ type: 'int', default: 1 })
onlineVersion: number;
@CreateDateColumn()
createdAt: Date;

View File

@@ -17,6 +17,9 @@ export class Episode {
@Column({ type: 'bigint' })
dramaId: number;
@Column({ type: 'varchar', length: 128, nullable: true })
tiktokEpisodeId?: string;
@Column({ type: 'int' })
episodeNo: number;
@@ -26,24 +29,48 @@ export class Episode {
@Column({ type: 'text', nullable: true })
description?: string;
@Column({ type: 'int', nullable: true })
coverId?: number;
@Column({ type: 'varchar', length: 1024 })
coverUrl: string;
@Column({ type: 'varchar', length: 1024 })
videoUrl: string;
@Column({ type: 'varchar', length: 1024, nullable: true })
videoUrl?: string;
@Column({ type: 'varchar', length: 128, nullable: true })
byteplusVid?: string;
@Column({ type: 'varchar', length: 255, nullable: true })
storageBucket?: string;
@Column({ type: 'varchar', length: 512, nullable: true })
objectKey?: string;
@Column({ type: 'int', nullable: true })
trialDurationSeconds?: number;
@Column({ type: 'int' })
@Column({ type: 'int', default: 0 })
durationSeconds: number;
@Column({ type: 'int', nullable: true })
width?: number;
@Column({ type: 'int', nullable: true })
height?: number;
@Column({ type: 'boolean', default: false })
isPaid: boolean;
@Column({ type: 'varchar', length: 16, default: 'free' })
freeType: 'free' | 'paid';
@Column({ type: 'int', nullable: true })
unlockPrice?: number;
@Column({ type: 'int', default: 0 })
price: number;
@Column({ type: 'datetime', nullable: true })
publishAt?: Date;
@@ -53,6 +80,15 @@ export class Episode {
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
status: PublishStatus;
@Column({ type: 'varchar', length: 32, default: 'not_submitted' })
reviewStatus: 'not_submitted' | 'pending' | 'reviewing' | 'approved' | 'rejected';
@Column({ type: 'varchar', length: 512, nullable: true })
reviewMessage?: string;
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
publishStatus: PublishStatus;
@CreateDateColumn()
createdAt: Date;

View File

@@ -18,6 +18,8 @@ export interface DramaRecord {
sortOrder: number;
isRecommended: boolean;
onlineVersion: number;
totalEpisodes: number;
publishedEpisodes: number;
createdAt: string;
updatedAt: string;
}
@@ -35,8 +37,12 @@ export interface EpisodeRecord {
coverId?: number;
coverUrl: string;
videoUrl?: string;
storageBucket?: string;
objectKey?: string;
trialDurationSeconds?: number;
durationSeconds: number;
width?: number;
height?: number;
isPaid: boolean;
freeType: 'free' | 'paid';
unlockPrice?: number;
@@ -44,7 +50,8 @@ export interface EpisodeRecord {
publishAt?: string;
nextReleaseAt?: string;
status: PublishStatus;
reviewStatus: 'pending' | 'approved' | 'rejected';
reviewStatus: 'not_submitted' | 'pending' | 'reviewing' | 'approved' | 'rejected';
reviewMessage?: string;
publishStatus: PublishStatus;
createdAt: string;
updatedAt: string;

View File

@@ -0,0 +1,9 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';
export class CompleteDirectUploadTaskDto {
@ApiPropertyOptional()
@IsOptional()
@IsString()
providerUploadId?: string;
}

View File

@@ -0,0 +1,22 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsInt, IsString, Min } from 'class-validator';
export class CreateDirectUploadTaskDto {
@ApiProperty()
@IsInt()
@Min(1)
episodeId: number;
@ApiProperty()
@IsString()
fileName: string;
@ApiProperty()
@IsString()
contentType: string;
@ApiProperty()
@IsInt()
@Min(1)
fileSize: number;
}

View File

@@ -0,0 +1,21 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('covers')
export class Cover {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'varchar', length: 255 })
fileName: string;
@Column({ type: 'varchar', length: 1024 })
url: string;
@CreateDateColumn()
createdAt: Date;
}

View File

@@ -16,6 +16,9 @@ export class MediaUploadJob {
@Column({ type: 'varchar', length: 128 })
jobId: string;
@Column({ type: 'int', nullable: true })
episodeId?: number;
@Index()
@Column({ type: 'varchar', length: 128, nullable: true })
byteplusVid?: string;
@@ -23,6 +26,42 @@ export class MediaUploadJob {
@Column({ type: 'varchar', length: 64 })
status: string;
@Column({ type: 'varchar', length: 255, nullable: true })
fileName?: string;
@Column({ type: 'varchar', length: 128, nullable: true })
contentType?: string;
@Column({ type: 'int', nullable: true })
fileSize?: number;
@Column({ type: 'varchar', length: 255, nullable: true })
bucket?: string;
@Column({ type: 'varchar', length: 512, nullable: true })
objectKey?: string;
@Column({ type: 'varchar', length: 1024, nullable: true })
uploadUrl?: string;
@Column({ type: 'varchar', length: 1024, nullable: true })
videoUrl?: string;
@Column({ type: 'int', nullable: true })
width?: number;
@Column({ type: 'int', nullable: true })
height?: number;
@Column({ type: 'int', nullable: true })
durationSeconds?: number;
@Column({ type: 'varchar', length: 32, nullable: true })
reviewStatus?: 'not_submitted' | 'pending' | 'reviewing' | 'approved' | 'rejected';
@Column({ type: 'varchar', length: 512, nullable: true })
reviewMessage?: string;
@Column({ type: 'json', nullable: true })
rawResponse?: Record<string, unknown>;

View File

@@ -8,8 +8,21 @@ export interface CoverRecord {
export interface MediaUploadJobRecord {
id: number;
jobId: string;
episodeId?: number;
byteplusVid?: string;
status: string;
fileName?: string;
contentType?: string;
fileSize?: number;
bucket?: string;
objectKey?: string;
uploadUrl?: string;
videoUrl?: string;
width?: number;
height?: number;
durationSeconds?: number;
reviewStatus?: 'not_submitted' | 'pending' | 'reviewing' | 'approved' | 'rejected';
reviewMessage?: string;
rawResponse?: Record<string, unknown>;
createdAt: string;
updatedAt: string;

View File

@@ -1,40 +1,68 @@
import { Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
import { PermissionsGuard } from '../admin/guards/permissions.guard';
import { CreateCoverDto } from './dto/create-cover.dto';
import { CreateUploadJobDto } from './dto/create-upload-job.dto';
import { MediaService } from './media.service';
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
import { ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { RequirePermissions } from "../admin/decorators/require-permissions.decorator";
import { AdminJwtAuthGuard } from "../admin/guards/admin-jwt-auth.guard";
import { PermissionsGuard } from "../admin/guards/permissions.guard";
import { CreateCoverDto } from "./dto/create-cover.dto";
import { CreateDirectUploadTaskDto } from "./dto/create-direct-upload-task.dto";
import { CreateUploadJobDto } from "./dto/create-upload-job.dto";
import { MediaService } from "./media.service";
@ApiTags('Media')
@Controller('/api/admin/v1/media')
@ApiTags("Media")
@Controller("/api/admin/v1/media")
@ApiBearerAuth()
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
export class MediaController {
constructor(private readonly mediaService: MediaService) {}
constructor(private readonly mediaService: MediaService) {}
@Post('/covers')
@RequirePermissions('media:create')
createCover(@Body() dto: CreateCoverDto) {
return this.mediaService.createCover(dto);
}
@Post("/covers")
@RequirePermissions("media:create")
createCover(@Body() dto: CreateCoverDto) {
return this.mediaService.createCover(dto);
}
@Post('/upload-jobs')
@RequirePermissions('media:create')
createUploadJob(@Body() dto: CreateUploadJobDto) {
return this.mediaService.createUploadJob(dto);
}
@Post("/upload-jobs")
@RequirePermissions("media:create")
createUploadJob(@Body() dto: CreateUploadJobDto) {
return this.mediaService.createUploadJob(dto);
}
@Get('/upload-jobs')
@RequirePermissions('media:read')
listUploadJobs(
@Query('page') page?: string,
@Query('pageSize') pageSize?: string,
) {
return this.mediaService.listUploadJobs({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
@Post("/upload-tasks")
@RequirePermissions("media:create")
createDirectUploadTask(@Body() dto: CreateDirectUploadTaskDto) {
return this.mediaService.createDirectUploadTask(dto);
}
@Get("/upload-tasks/:jobId")
@RequirePermissions("media:read")
getUploadTask(@Param("jobId") jobId: string) {
return this.mediaService.getUploadTask(jobId);
}
@Patch("/upload-tasks/:jobId/complete")
@RequirePermissions("media:create")
completeDirectUploadTask(@Param("jobId") jobId: string) {
return this.mediaService.completeDirectUploadTask(jobId);
}
@Post("/upload-tasks/:jobId/review/retry")
@RequirePermissions("media:create")
retryReview(@Param("jobId") jobId: string) {
return this.mediaService.retryReview(jobId);
}
@Post("/review-status/sync")
@RequirePermissions("media:create")
syncReviewStatuses() {
return this.mediaService.syncReviewStatuses();
}
@Get("/upload-jobs")
@RequirePermissions("media:read")
listUploadJobs(@Query("page") page?: string, @Query("pageSize") pageSize?: string) {
return this.mediaService.listUploadJobs({
page: Number(page) || 1,
pageSize: Number(pageSize) || 20,
});
}
}

View File

@@ -1,12 +1,14 @@
import { Module } from '@nestjs/common';
import { AdminModule } from '../admin/admin.module';
import { DramasModule } from '../dramas/dramas.module';
import { MediaController } from './media.controller';
import { MediaService } from './media.service';
import { BytePlusMediaProvider } from './providers/byteplus-media.provider';
@Module({
imports: [AdminModule],
imports: [AdminModule, DramasModule],
controllers: [MediaController],
providers: [MediaService],
providers: [MediaService, BytePlusMediaProvider],
exports: [MediaService],
})
export class MediaModule {}

View File

@@ -1,11 +1,19 @@
import { Injectable } from '@nestjs/common';
import { Injectable, NotFoundException, Optional } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { randomUUID } from 'crypto';
import { DataSource } from 'typeorm';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { DramasService } from '../dramas/dramas.service';
import { CreateCoverDto } from './dto/create-cover.dto';
import { CreateDirectUploadTaskDto } from './dto/create-direct-upload-task.dto';
import { CreateUploadJobDto } from './dto/create-upload-job.dto';
import { Cover } from './entities/cover.entity';
import { MediaUploadJob } from './entities/media-upload-job.entity';
import {
CoverRecord,
MediaUploadJobRecord,
} from './interfaces/media-records.interface';
import { BytePlusMediaProvider } from './providers/byteplus-media.provider';
interface PaginationInput {
page: number;
@@ -19,7 +27,23 @@ export class MediaService {
private readonly covers: CoverRecord[] = [];
private readonly uploadJobs: MediaUploadJobRecord[] = [];
createCover(dto: CreateCoverDto): CoverRecord {
constructor(
private readonly dramasService: DramasService,
private readonly bytePlusMediaProvider: BytePlusMediaProvider,
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {}
async createCover(dto: CreateCoverDto): Promise<CoverRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Cover);
const saved = await repository.save(
repository.create({ fileName: dto.fileName, url: dto.url }),
);
return this.toCoverRecord(saved);
}
const cover: CoverRecord = {
id: this.coverSequence++,
fileName: dto.fileName,
@@ -30,7 +54,20 @@ export class MediaService {
return cover;
}
createUploadJob(dto: CreateUploadJobDto): MediaUploadJobRecord {
async createUploadJob(dto: CreateUploadJobDto): Promise<MediaUploadJobRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(MediaUploadJob);
const saved = await repository.save(
repository.create({
jobId: dto.jobId,
byteplusVid: dto.byteplusVid,
status: dto.status,
rawResponse: dto.rawResponse,
}),
);
return this.toJobRecord(saved);
}
const now = new Date().toISOString();
const job: MediaUploadJobRecord = {
id: this.uploadJobSequence++,
@@ -45,21 +82,331 @@ export class MediaService {
return job;
}
listUploadJobs(
input: PaginationInput,
): PaginatedResponse<MediaUploadJobRecord> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const start = (page - 1) * pageSize;
const records = [...this.uploadJobs].reverse();
return {
list: records.slice(start, start + pageSize),
pagination: {
page,
pageSize,
total: records.length,
async createDirectUploadTask(
dto: CreateDirectUploadTaskDto,
): Promise<MediaUploadJobRecord> {
await this.dramasService.getEpisodeOrThrow(dto.episodeId);
const jobId = randomUUID();
const upload = this.bytePlusMediaProvider.createDirectUpload({
jobId,
fileName: dto.fileName,
contentType: dto.contentType,
});
const base = {
jobId,
episodeId: dto.episodeId,
status: 'pending',
fileName: dto.fileName,
contentType: dto.contentType,
fileSize: dto.fileSize,
bucket: upload.bucket,
objectKey: upload.objectKey,
uploadUrl: upload.uploadUrl,
reviewStatus: 'not_submitted' as const,
rawResponse: {
headers: upload.headers,
expiresAt: upload.expiresAt,
},
};
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(MediaUploadJob);
return this.toJobRecord(await repository.save(repository.create(base)));
}
const now = new Date().toISOString();
const job: MediaUploadJobRecord = {
id: this.uploadJobSequence++,
...base,
createdAt: now,
updatedAt: now,
};
this.uploadJobs.push(job);
return job;
}
async completeDirectUploadTask(jobId: string): Promise<MediaUploadJobRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(MediaUploadJob);
const job = await repository.findOne({ where: { jobId } });
if (!job || !job.objectKey || !job.episodeId) {
throw new NotFoundException('Upload task not found');
}
const completed = this.bytePlusMediaProvider.completeUpload({
jobId: job.jobId,
objectKey: job.objectKey,
});
const review = this.bytePlusMediaProvider.submitReview(
completed.byteplusVid,
);
job.byteplusVid = completed.byteplusVid;
job.videoUrl = completed.videoUrl;
job.width = completed.width;
job.height = completed.height;
job.durationSeconds = completed.durationSeconds;
job.status = review.reviewStatus;
job.reviewStatus = review.reviewStatus;
job.reviewMessage = review.reviewMessage;
job.rawResponse = {
...(job.rawResponse ?? {}),
upload: completed.rawResponse,
review,
};
await repository.save(job);
await this.dramasService.attachEpisodeMedia({
episodeId: Number(job.episodeId),
byteplusVid: completed.byteplusVid,
videoUrl: completed.videoUrl,
storageBucket: job.bucket ?? '',
objectKey: job.objectKey,
durationSeconds: completed.durationSeconds,
width: completed.width,
height: completed.height,
reviewStatus: review.reviewStatus,
reviewMessage: review.reviewMessage,
});
return this.toJobRecord(job);
}
const job = this.getMemJobOrThrow(jobId);
if (!job.objectKey || !job.episodeId) {
throw new NotFoundException('Upload task not found');
}
const completed = this.bytePlusMediaProvider.completeUpload({
jobId: job.jobId,
objectKey: job.objectKey,
});
const review = this.bytePlusMediaProvider.submitReview(completed.byteplusVid);
Object.assign(job, {
byteplusVid: completed.byteplusVid,
videoUrl: completed.videoUrl,
width: completed.width,
height: completed.height,
durationSeconds: completed.durationSeconds,
status: review.reviewStatus,
reviewStatus: review.reviewStatus,
reviewMessage: review.reviewMessage,
rawResponse: {
...job.rawResponse,
upload: completed.rawResponse,
review,
},
updatedAt: new Date().toISOString(),
});
await this.dramasService.attachEpisodeMedia({
episodeId: job.episodeId,
byteplusVid: completed.byteplusVid,
videoUrl: completed.videoUrl,
storageBucket: job.bucket ?? '',
objectKey: job.objectKey,
durationSeconds: completed.durationSeconds,
width: completed.width,
height: completed.height,
reviewStatus: review.reviewStatus,
reviewMessage: review.reviewMessage,
});
return job;
}
async retryReview(jobId: string): Promise<MediaUploadJobRecord> {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(MediaUploadJob);
const job = await repository.findOne({ where: { jobId } });
if (!job || !job.byteplusVid || !job.episodeId) {
throw new NotFoundException('Upload task not found');
}
const review = this.bytePlusMediaProvider.submitReview(job.byteplusVid);
job.status = review.reviewStatus;
job.reviewStatus = review.reviewStatus;
job.reviewMessage = review.reviewMessage;
await repository.save(job);
await this.dramasService.updateEpisodeReviewStatus(
Number(job.episodeId),
review.reviewStatus,
review.reviewMessage,
);
return this.toJobRecord(job);
}
const job = this.getMemJobOrThrow(jobId);
if (!job.byteplusVid || !job.episodeId) {
throw new NotFoundException('Upload task not found');
}
const review = this.bytePlusMediaProvider.submitReview(job.byteplusVid);
job.status = review.reviewStatus;
job.reviewStatus = review.reviewStatus;
job.reviewMessage = review.reviewMessage;
job.updatedAt = new Date().toISOString();
await this.dramasService.updateEpisodeReviewStatus(
job.episodeId,
review.reviewStatus,
review.reviewMessage,
);
return job;
}
async syncReviewStatuses() {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(MediaUploadJob);
const candidates = await repository.find({
where: [{ reviewStatus: 'reviewing' }, { reviewStatus: 'pending' }],
});
const reviewingJobs = candidates.filter(
(job) => job.byteplusVid && job.episodeId,
);
for (const job of reviewingJobs) {
const review = this.bytePlusMediaProvider.queryReviewStatus(
job.byteplusVid as string,
);
job.status = review.reviewStatus;
job.reviewStatus = review.reviewStatus;
job.reviewMessage = review.reviewMessage;
await repository.save(job);
await this.dramasService.updateEpisodeReviewStatus(
Number(job.episodeId),
review.reviewStatus,
review.reviewMessage,
);
}
return { status: 'completed', synced: reviewingJobs.length };
}
const reviewingJobs = this.uploadJobs.filter(
(job) =>
job.byteplusVid &&
job.episodeId &&
(job.reviewStatus === 'reviewing' || job.reviewStatus === 'pending'),
);
for (const job of reviewingJobs) {
const review = this.bytePlusMediaProvider.queryReviewStatus(
job.byteplusVid as string,
);
job.status = review.reviewStatus;
job.reviewStatus = review.reviewStatus;
job.reviewMessage = review.reviewMessage;
job.updatedAt = new Date().toISOString();
await this.dramasService.updateEpisodeReviewStatus(
job.episodeId as number,
review.reviewStatus,
review.reviewMessage,
);
}
return { status: 'completed', synced: reviewingJobs.length };
}
async getUploadTask(jobId: string): Promise<MediaUploadJobRecord> {
return this.getUploadJobOrThrow(jobId);
}
async listUploadJobs(
input: PaginationInput,
): Promise<PaginatedResponse<MediaUploadJobRecord>> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
if (this.hasDatabase()) {
const [records, total] = await this.dataSource
.getRepository(MediaUploadJob)
.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return {
list: records.map((job) => this.toJobRecord(job)),
pagination: { page, pageSize, total },
};
}
const records = [...this.uploadJobs].reverse();
return {
list: records.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize),
pagination: { page, pageSize, total: this.uploadJobs.length },
};
}
private async getUploadJobOrThrow(jobId: string): Promise<MediaUploadJobRecord> {
if (this.hasDatabase()) {
const job = await this.dataSource
.getRepository(MediaUploadJob)
.findOne({ where: { jobId } });
if (!job) {
throw new NotFoundException('Upload task not found');
}
return this.toJobRecord(job);
}
return this.getMemJobOrThrow(jobId);
}
private getMemJobOrThrow(jobId: string): MediaUploadJobRecord {
const job = this.uploadJobs.find((item) => item.jobId === jobId);
if (!job) {
throw new NotFoundException('Upload task not found');
}
return job;
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private toCoverRecord(cover: Cover): CoverRecord {
return {
id: Number(cover.id),
fileName: cover.fileName,
url: cover.url,
createdAt: this.toIso(cover.createdAt),
};
}
private toJobRecord(job: MediaUploadJob): MediaUploadJobRecord {
return {
id: Number(job.id),
jobId: job.jobId,
episodeId:
job.episodeId === null || job.episodeId === undefined
? undefined
: Number(job.episodeId),
byteplusVid: job.byteplusVid,
status: job.status,
fileName: job.fileName,
contentType: job.contentType,
fileSize: job.fileSize,
bucket: job.bucket,
objectKey: job.objectKey,
uploadUrl: job.uploadUrl,
videoUrl: job.videoUrl,
width: job.width,
height: job.height,
durationSeconds: job.durationSeconds,
reviewStatus: job.reviewStatus,
reviewMessage: job.reviewMessage,
rawResponse: job.rawResponse,
createdAt: this.toIso(job.createdAt),
updatedAt: this.toIso(job.updatedAt),
};
}
private toIso(value?: Date | string): string {
if (!value) {
return new Date().toISOString();
}
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
}

View File

@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
interface CreateUploadInput {
jobId: string;
fileName: string;
contentType: string;
}
interface CompleteUploadInput {
jobId: string;
objectKey: string;
}
@Injectable()
export class BytePlusMediaProvider {
createDirectUpload(input: CreateUploadInput) {
const bucket = process.env.BYTEPLUS_BUCKET ?? 'mock-short-drama';
const objectKey = `videos/${input.jobId}/${input.fileName}`;
return {
bucket,
objectKey,
uploadUrl: `https://mock-byteplus-upload.local/${bucket}/${objectKey}`,
headers: {
'content-type': input.contentType,
},
expiresAt: Date.now() + 15 * 60 * 1000,
};
}
completeUpload(input: CompleteUploadInput) {
return {
byteplusVid: `mock_vid_${input.jobId.replace(/-/g, '_')}`,
videoUrl: `https://mock-byteplus-cdn.local/${input.objectKey}`,
width: 1080,
height: 1920,
durationSeconds: 180,
rawResponse: {
provider: 'byteplus-mock',
objectKey: input.objectKey,
},
};
}
submitReview(byteplusVid: string) {
return {
reviewStatus: 'reviewing' as const,
reviewMessage: `Mock review submitted for ${byteplusVid}`,
};
}
queryReviewStatus(byteplusVid: string) {
return {
reviewStatus: 'approved' as const,
reviewMessage: `Mock review approved for ${byteplusVid}`,
};
}
}

View File

@@ -1,15 +1,21 @@
import {
Injectable,
NotFoundException,
Optional,
UnprocessableEntityException,
} from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { DramasService } from '../dramas/dramas.service';
import { UserRecord } from '../users/interfaces/user-record.interface';
import { CreateOrderDto } from './dto/create-order.dto';
import { TikTokPaymentWebhookDto } from './dto/tiktok-payment-webhook.dto';
import { Order } from './entities/order.entity';
import { UserEpisodeUnlock } from './entities/user-episode-unlock.entity';
import {
OrderRecord,
OrderStatus,
UserEpisodeUnlockRecord,
} from './interfaces/order-records.interface';
@@ -20,23 +26,49 @@ export class OrdersService {
private readonly orders: OrderRecord[] = [];
private readonly unlocks: UserEpisodeUnlockRecord[] = [];
constructor(private readonly dramasService: DramasService) {}
constructor(
private readonly dramasService: DramasService,
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {}
createOrder(user: UserRecord, dto: CreateOrderDto): OrderRecord {
const episode = this.dramasService.getPublishedEpisodeOrThrow(dto.episodeId);
async createOrder(user: UserRecord, dto: CreateOrderDto): Promise<OrderRecord> {
const episode = await this.dramasService.getPublishedEpisodeOrThrow(
dto.episodeId,
);
if (!episode.isPaid) {
throw new UnprocessableEntityException('Episode is free');
}
const amount = episode.price ?? episode.unlockPrice ?? 0;
const orderNo = this.createOrderNo();
const tradeOrderId = this.createTradeOrderId();
this.orderSequence++;
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(Order);
const entity = repository.create({
orderNo,
tradeOrderId,
userId: user.id,
albumId: episode.albumId,
episodeId: episode.id,
amount,
status: 'pending',
});
return this.toOrderRecord(await repository.save(entity));
}
const now = new Date().toISOString();
const order: OrderRecord = {
id: this.orderSequence++,
orderNo: this.createOrderNo(),
tradeOrderId: this.createTradeOrderId(),
id: this.orders.length + 1,
orderNo,
tradeOrderId,
userId: user.id,
albumId: episode.albumId,
episodeId: episode.id,
amount: episode.price ?? episode.unlockPrice ?? 0,
amount,
status: 'pending',
createdAt: now,
updatedAt: now,
@@ -46,13 +78,10 @@ export class OrdersService {
return order;
}
getPlayback(user: UserRecord, episodeId: number) {
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
async getPlayback(user: UserRecord, episodeId: number) {
const episode = await this.dramasService.getPublishedEpisodeOrThrow(episodeId);
const isUnlocked =
!episode.isPaid ||
this.unlocks.some(
(unlock) => unlock.userId === user.id && unlock.episodeId === episodeId,
);
!episode.isPaid || (await this.isUnlocked(user.id, episodeId));
return {
episodeId: episode.id,
@@ -66,7 +95,68 @@ export class OrdersService {
};
}
handlePaymentWebhook(dto: TikTokPaymentWebhookDto) {
async handlePaymentWebhook(dto: TikTokPaymentWebhookDto) {
if (this.hasDatabase()) {
const orderRepository = this.dataSource.getRepository(Order);
const where: Record<string, string>[] = [];
if (dto.orderNo) {
where.push({ orderNo: dto.orderNo });
}
if (dto.tradeOrderId) {
where.push({ tradeOrderId: dto.tradeOrderId });
}
const order = where.length
? await orderRepository.findOne({ where })
: null;
if (!order) {
throw new NotFoundException('Order not found');
}
if (order.status === 'paid') {
return {
orderNo: order.orderNo,
status: order.status,
unlocked: await this.isUnlocked(
Number(order.userId),
Number(order.episodeId),
),
};
}
order.providerTransactionId = dto.providerTransactionId;
order.tiktokOrderId = dto.tiktokOrderId ?? order.tiktokOrderId;
order.status = dto.status;
await orderRepository.save(order);
if (
dto.status === 'paid' &&
!(await this.isUnlocked(
Number(order.userId),
Number(order.episodeId),
))
) {
const unlockRepository = this.dataSource.getRepository(UserEpisodeUnlock);
await unlockRepository.save(
unlockRepository.create({
userId: Number(order.userId),
episodeId: Number(order.episodeId),
source: 'payment',
orderNo: order.orderNo,
}),
);
}
return {
orderNo: order.orderNo,
tradeOrderId: order.tradeOrderId,
status: order.status,
unlocked: await this.isUnlocked(
Number(order.userId),
Number(order.episodeId),
),
};
}
const order = this.orders.find(
(item) =>
item.orderNo === dto.orderNo || item.tradeOrderId === dto.tradeOrderId,
@@ -79,7 +169,7 @@ export class OrdersService {
return {
orderNo: order.orderNo,
status: order.status,
unlocked: this.isUnlocked(order.userId, order.episodeId),
unlocked: await this.isUnlocked(order.userId, order.episodeId),
};
}
@@ -88,7 +178,10 @@ export class OrdersService {
order.status = dto.status;
order.updatedAt = new Date().toISOString();
if (dto.status === 'paid' && !this.isUnlocked(order.userId, order.episodeId)) {
if (
dto.status === 'paid' &&
!(await this.isUnlocked(order.userId, order.episodeId))
) {
this.unlocks.push({
id: this.unlockSequence++,
userId: order.userId,
@@ -103,40 +196,95 @@ export class OrdersService {
orderNo: order.orderNo,
tradeOrderId: order.tradeOrderId,
status: order.status,
unlocked: this.isUnlocked(order.userId, order.episodeId),
unlocked: await this.isUnlocked(order.userId, order.episodeId),
};
}
hasEpisodePermission(userId: number, episodeId: number) {
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
return !episode.isPaid || this.isUnlocked(userId, episodeId);
async hasEpisodePermission(userId: number, episodeId: number) {
const episode = await this.dramasService.getPublishedEpisodeOrThrow(episodeId);
return !episode.isPaid || (await this.isUnlocked(userId, episodeId));
}
listUnlockRecords(input: {
async listUnlockRecords(input: {
page: number;
pageSize: number;
}): PaginatedResponse<UserEpisodeUnlockRecord> {
}): Promise<PaginatedResponse<UserEpisodeUnlockRecord>> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const start = (page - 1) * pageSize;
const records = [...this.unlocks].reverse();
if (this.hasDatabase()) {
const [records, total] = await this.dataSource
.getRepository(UserEpisodeUnlock)
.findAndCount({
order: { id: 'DESC' },
skip: (page - 1) * pageSize,
take: pageSize,
});
return {
list: records.map((record) => this.toUnlockRecord(record)),
pagination: { page, pageSize, total },
};
}
const records = [...this.unlocks].reverse();
return {
list: records.slice(start, start + pageSize),
pagination: {
page,
pageSize,
total: records.length,
},
list: records.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize),
pagination: { page, pageSize, total: this.unlocks.length },
};
}
private isUnlocked(userId: number, episodeId: number) {
private async isUnlocked(userId: number, episodeId: number): Promise<boolean> {
if (this.hasDatabase()) {
const count = await this.dataSource
.getRepository(UserEpisodeUnlock)
.count({ where: { userId, episodeId } });
return count > 0;
}
return this.unlocks.some(
(unlock) => unlock.userId === userId && unlock.episodeId === episodeId,
);
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private toOrderRecord(order: Order): OrderRecord {
return {
id: Number(order.id),
orderNo: order.orderNo,
tradeOrderId: order.tradeOrderId,
userId: Number(order.userId),
albumId: Number(order.albumId),
episodeId: Number(order.episodeId),
tiktokOrderId: order.tiktokOrderId,
amount: order.amount,
status: order.status as OrderStatus,
providerTransactionId: order.providerTransactionId,
createdAt: this.toIso(order.createdAt),
updatedAt: this.toIso(order.updatedAt),
};
}
private toUnlockRecord(unlock: UserEpisodeUnlock): UserEpisodeUnlockRecord {
return {
id: Number(unlock.id),
userId: Number(unlock.userId),
episodeId: Number(unlock.episodeId),
source: unlock.source as 'payment' | 'admin' | 'free',
orderNo: unlock.orderNo,
createdAt: this.toIso(unlock.createdAt),
};
}
private toIso(value?: Date | string): string {
if (!value) {
return new Date().toISOString();
}
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
private createOrderNo() {
return `ORD${Date.now()}${String(this.orderSequence).padStart(6, '0')}`;
}

View File

@@ -17,3 +17,16 @@ export class PlayerController {
return this.playerService.getEpisodePlayer(user, Number(id));
}
}
@ApiTags('Player')
@Controller('/api/app/v1/episodes')
export class EpisodePlayerController {
constructor(private readonly playerService: PlayerService) {}
@Get('/:id/player')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
getEpisodePlayer(@CurrentUser() user: UserRecord, @Param('id') id: string) {
return this.playerService.getEpisodePlayer(user, Number(id));
}
}

View File

@@ -3,12 +3,12 @@ import { AuthModule } from '../auth/auth.module';
import { DramasModule } from '../dramas/dramas.module';
import { OrdersModule } from '../orders/orders.module';
import { UsersModule } from '../users/users.module';
import { PlayerController } from './player.controller';
import { EpisodePlayerController, PlayerController } from './player.controller';
import { PlayerService } from './player.service';
@Module({
imports: [AuthModule, DramasModule, OrdersModule, UsersModule],
controllers: [PlayerController],
controllers: [PlayerController, EpisodePlayerController],
providers: [PlayerService],
})
export class PlayerModule {}

View File

@@ -10,9 +10,9 @@ export class PlayerService {
private readonly ordersService: OrdersService,
) {}
getEpisodePlayer(user: UserRecord, episodeId: number) {
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
const hasPermission = this.ordersService.hasEpisodePermission(
async getEpisodePlayer(user: UserRecord, episodeId: number) {
const episode = await this.dramasService.getPublishedEpisodeOrThrow(episodeId);
const hasPermission = await this.ordersService.hasEpisodePermission(
user.id,
episode.id,
);

View File

@@ -1,92 +1,172 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
import { UserRecord } from './interfaces/user-record.interface';
import { Injectable, NotFoundException, Optional } from "@nestjs/common";
import { InjectDataSource } from "@nestjs/typeorm";
import { DataSource } from "typeorm";
import { PaginatedResponse } from "../../common/dto/paginated-response.dto";
import { User } from "./entities/user.entity";
import { UserRecord } from "./interfaces/user-record.interface";
interface UpsertTikTokUserInput {
tiktokOpenId: string;
tiktokUnionId?: string;
nickname?: string;
avatarUrl?: string;
tiktokOpenId: string;
tiktokUnionId?: string;
nickname?: string;
avatarUrl?: string;
}
interface PaginationInput {
page: number;
pageSize: number;
page: number;
pageSize: number;
}
@Injectable()
export class UsersService {
private userSequence = 1;
private readonly users: UserRecord[] = [];
private userSequence = 1;
private readonly users: UserRecord[] = [];
upsertTikTokUser(input: UpsertTikTokUserInput) {
const existing = this.users.find(
(user) => user.tiktokOpenId === input.tiktokOpenId,
);
const now = new Date().toISOString();
constructor(
@Optional()
@InjectDataSource()
readonly dataSource?: DataSource,
) {}
if (existing) {
existing.tiktokUnionId = input.tiktokUnionId ?? existing.tiktokUnionId;
existing.nickname = input.nickname ?? existing.nickname;
existing.avatarUrl = input.avatarUrl ?? existing.avatarUrl;
existing.updatedAt = now;
return { user: existing, isNewUser: false };
async upsertTikTokUser(input: UpsertTikTokUserInput) {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(User);
const existing = await repository.findOne({
where: { tiktokOpenId: input.tiktokOpenId },
});
if (existing) {
existing.tiktokUnionId = input.tiktokUnionId ?? existing.tiktokUnionId;
existing.nickname = input.nickname ?? existing.nickname;
existing.avatarUrl = input.avatarUrl ?? existing.avatarUrl;
const saved = await repository.save(existing);
return { user: this.toRecord(saved), isNewUser: false };
}
const user = repository.create({
tiktokOpenId: input.tiktokOpenId,
tiktokUnionId: input.tiktokUnionId,
nickname: input.nickname,
avatarUrl: input.avatarUrl,
status: "active",
});
const saved = await repository.save(user);
return { user: this.toRecord(saved), isNewUser: true };
}
const existing = this.users.find((user) => user.tiktokOpenId === input.tiktokOpenId);
const now = new Date().toISOString();
if (existing) {
existing.tiktokUnionId = input.tiktokUnionId ?? existing.tiktokUnionId;
existing.nickname = input.nickname ?? existing.nickname;
existing.avatarUrl = input.avatarUrl ?? existing.avatarUrl;
existing.updatedAt = now;
return { user: existing, isNewUser: false };
}
const user: UserRecord = {
id: this.userSequence++,
tiktokOpenId: input.tiktokOpenId,
tiktokUnionId: input.tiktokUnionId,
nickname: input.nickname,
avatarUrl: input.avatarUrl,
status: "active",
createdAt: now,
updatedAt: now,
};
this.users.push(user);
return { user, isNewUser: true };
}
const user: UserRecord = {
id: this.userSequence++,
tiktokOpenId: input.tiktokOpenId,
tiktokUnionId: input.tiktokUnionId,
nickname: input.nickname,
avatarUrl: input.avatarUrl,
status: 'active',
createdAt: now,
updatedAt: now,
};
async findById(id: number) {
if (this.hasDatabase()) {
const user = await this.dataSource.getRepository(User).findOne({
where: { id },
});
return user ? this.toRecord(user) : undefined;
}
this.users.push(user);
return { user, isNewUser: true };
}
findById(id: number) {
return this.users.find((user) => user.id === id);
}
listUsers(pagination: PaginationInput): PaginatedResponse<UserRecord> {
return this.paginate([...this.users].reverse(), pagination);
}
getUserOrThrow(id: number) {
const user = this.findById(id);
if (!user) {
throw new NotFoundException('User not found');
return this.users.find((user) => user.id === id);
}
return user;
}
async listUsers(pagination: PaginationInput): Promise<PaginatedResponse<UserRecord>> {
if (this.hasDatabase()) {
const page = Math.max(pagination.page, 1);
const pageSize = Math.min(Math.max(pagination.pageSize, 1), 100);
const repository = this.dataSource.getRepository(User);
const [records, total] = await repository.findAndCount({
order: { id: "DESC" },
skip: (page - 1) * pageSize,
take: pageSize,
});
updateStatus(id: number, status: 'active' | 'disabled') {
const user = this.getUserOrThrow(id);
user.status = status;
user.updatedAt = new Date().toISOString();
return user;
}
return {
list: records.map((user) => this.toRecord(user)),
pagination: { page, pageSize, total },
};
}
private paginate<T>(
records: T[],
input: PaginationInput,
): PaginatedResponse<T> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const start = (page - 1) * pageSize;
return this.paginate([...this.users].reverse(), pagination);
}
return {
list: records.slice(start, start + pageSize),
pagination: {
page,
pageSize,
total: records.length,
},
};
}
async getUserOrThrow(id: number) {
const user = await this.findById(id);
if (!user) {
throw new NotFoundException("User not found");
}
return user;
}
async updateStatus(id: number, status: "active" | "disabled") {
if (this.hasDatabase()) {
const repository = this.dataSource.getRepository(User);
const user = await repository.findOne({ where: { id } });
if (!user) {
throw new NotFoundException("User not found");
}
user.status = status;
return this.toRecord(await repository.save(user));
}
const user = await this.getUserOrThrow(id);
user.status = status;
user.updatedAt = new Date().toISOString();
return user;
}
private hasDatabase(): this is this & { dataSource: DataSource } {
return Boolean(this.dataSource?.isInitialized);
}
private toRecord(user: User): UserRecord {
return {
id: Number(user.id),
tiktokOpenId: user.tiktokOpenId,
tiktokUnionId: user.tiktokUnionId,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
status: user.status as "active" | "disabled",
createdAt: user.createdAt?.toISOString?.() ?? new Date().toISOString(),
updatedAt: user.updatedAt?.toISOString?.() ?? new Date().toISOString(),
};
}
private paginate<T>(records: T[], input: PaginationInput): PaginatedResponse<T> {
const page = Math.max(input.page, 1);
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
const start = (page - 1) * pageSize;
return {
list: records.slice(start, start + pageSize),
pagination: {
page,
pageSize,
total: records.length,
},
};
}
}

View File

@@ -0,0 +1,231 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
import { bootstrapApp } from '../src/bootstrap';
import { loginAdmin } from './test-helpers';
describe('Data management and media upload flow', () => {
let app: INestApplication;
let adminToken: string;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleRef.createNestApplication();
bootstrapApp(app);
await app.init();
adminToken = await loginAdmin(app);
});
afterAll(async () => {
await app.close();
});
it('creates a drama, configures episode slots, completes a direct upload, and exposes approved published content to app APIs', async () => {
const drama = await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Upload Flow Drama',
description: 'Drama created by admin before uploading episodes.',
coverUrl: 'https://cdn.example.com/upload-flow-cover.jpg',
type: 'romance',
region: 'TH',
language: 'th',
status: 'draft',
})
.expect(201);
const dramaId = drama.body.data.id as number;
const slots = await request(app.getHttpServer())
.post(`/api/admin/v1/dramas/${dramaId}/episodes/batch`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ episodeCount: 3 })
.expect(201);
expect(slots.body.data.list).toHaveLength(3);
expect(slots.body.data.list[0]).toMatchObject({
dramaId,
episodeNo: 1,
title: '第1集',
publishStatus: 'draft',
reviewStatus: 'not_submitted',
});
const episodeId = slots.body.data.list[0].id as number;
const uploadTask = await request(app.getHttpServer())
.post('/api/admin/v1/media/upload-tasks')
.set('Authorization', `Bearer ${adminToken}`)
.send({
episodeId,
fileName: 'episode-1.mp4',
contentType: 'video/mp4',
fileSize: 1024,
})
.expect(201);
expect(uploadTask.body.data).toMatchObject({
jobId: expect.any(String),
uploadUrl: expect.stringContaining('mock-byteplus-upload'),
bucket: expect.any(String),
objectKey: expect.stringContaining('episode-1.mp4'),
status: 'pending',
});
const completed = await request(app.getHttpServer())
.patch(`/api/admin/v1/media/upload-tasks/${uploadTask.body.data.jobId}/complete`)
.set('Authorization', `Bearer ${adminToken}`)
.send({})
.expect(200);
expect(completed.body.data).toMatchObject({
jobId: uploadTask.body.data.jobId,
episodeId,
status: 'reviewing',
byteplusVid: expect.stringMatching(/^mock_vid_/),
width: 1080,
height: 1920,
durationSeconds: 180,
});
await request(app.getHttpServer())
.post(`/api/admin/v1/media/upload-tasks/${uploadTask.body.data.jobId}/review/retry`)
.set('Authorization', `Bearer ${adminToken}`)
.expect(201);
await request(app.getHttpServer())
.post('/api/admin/v1/media/review-status/sync')
.set('Authorization', `Bearer ${adminToken}`)
.expect(201);
await request(app.getHttpServer())
.patch(`/api/admin/v1/episodes/${episodeId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: '正式第1集',
coverUrl: 'https://cdn.example.com/episode-1-cover.jpg',
freeType: 'free',
publishStatus: 'published',
})
.expect(200);
await request(app.getHttpServer())
.patch(`/api/admin/v1/dramas/${dramaId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ status: 'published' })
.expect(200);
const appDetail = await request(app.getHttpServer())
.get(`/api/app/v1/dramas/${dramaId}`)
.expect(200);
expect(appDetail.body.data).toMatchObject({
id: dramaId,
title: 'Upload Flow Drama',
totalEpisodes: 3,
publishedEpisodes: 1,
});
const appEpisodes = await request(app.getHttpServer())
.get(`/api/app/v1/dramas/${dramaId}/episodes`)
.expect(200);
expect(appEpisodes.body.data.list).toEqual([
expect.objectContaining({
id: episodeId,
title: '正式第1集',
reviewStatus: 'approved',
publishStatus: 'published',
byteplusVid: completed.body.data.byteplusVid,
}),
]);
});
it('syncs TikTok mock analytics and returns overview plus drama and episode metrics', async () => {
const drama = await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Analytics Drama',
coverUrl: 'https://cdn.example.com/analytics-cover.jpg',
type: 'action',
status: 'published',
})
.expect(201);
const episode = await request(app.getHttpServer())
.post('/api/admin/v1/episodes')
.set('Authorization', `Bearer ${adminToken}`)
.send({
dramaId: drama.body.data.id,
episodeNo: 1,
title: 'Analytics Episode',
coverUrl: 'https://cdn.example.com/analytics-episode.jpg',
videoUrl: 'https://cdn.example.com/analytics-episode.mp4',
byteplusVid: 'mock_vid_analytics',
durationSeconds: 180,
reviewStatus: 'approved',
publishStatus: 'published',
status: 'published',
})
.expect(201);
const sync = await request(app.getHttpServer())
.post('/api/admin/v1/data/sync')
.set('Authorization', `Bearer ${adminToken}`)
.send({ dramaId: drama.body.data.id })
.expect(201);
expect(sync.body.data).toMatchObject({
status: 'completed',
dramaCount: expect.any(Number),
episodeCount: expect.any(Number),
});
const overview = await request(app.getHttpServer())
.get('/api/admin/v1/data/overview')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(overview.body.data).toMatchObject({
totalPlays: expect.any(Number),
totalLikes: expect.any(Number),
totalShares: expect.any(Number),
totalComments: expect.any(Number),
});
const dramaMetrics = await request(app.getHttpServer())
.get('/api/admin/v1/data/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(dramaMetrics.body.data.list).toEqual(
expect.arrayContaining([
expect.objectContaining({
dramaId: drama.body.data.id,
title: 'Analytics Drama',
plays: expect.any(Number),
}),
]),
);
const episodeMetrics = await request(app.getHttpServer())
.get(`/api/admin/v1/data/episodes?dramaId=${drama.body.data.id}`)
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(episodeMetrics.body.data.list).toEqual([
expect.objectContaining({
dramaId: drama.body.data.id,
episodeId: episode.body.data.id,
title: 'Analytics Episode',
plays: expect.any(Number),
}),
]);
});
});

View File

@@ -0,0 +1,185 @@
import { AdminService } from '../src/modules/admin/admin.service';
import { DataService } from '../src/modules/data/data.service';
import { TikTokDataProvider } from '../src/modules/data/providers/tiktok-data.provider';
import { PublishStatus } from '../src/modules/dramas/drama-status.enum';
import { DramasService } from '../src/modules/dramas/dramas.service';
import { LogsService } from '../src/modules/logs/logs.service';
import { UsersService } from '../src/modules/users/users.service';
function createRepository<T extends { id?: number }>() {
const records: T[] = [];
return {
records,
create: jest.fn((input: Partial<T>) => input as T),
save: jest.fn(async (input: T) => {
if (!input.id) {
input.id = records.length + 1;
}
const index = records.findIndex((item) => item.id === input.id);
if (index >= 0) {
records[index] = input;
} else {
records.push(input);
}
return input;
}),
findOne: jest.fn(async ({ where }: { where: Partial<T> }) =>
records.find((item) =>
Object.entries(where).every(
([key, value]) => item[key as keyof T] === value,
),
) ?? null,
),
find: jest.fn(async () => [...records]),
count: jest.fn(async () => records.length),
};
}
function createDataSource(repositories: Record<string, unknown>) {
return {
isInitialized: true,
getRepository: jest.fn((entity: { name: string }) => {
const repository = repositories[entity.name];
if (!repository) {
throw new Error(`Missing repository for ${entity.name}`);
}
return repository;
}),
};
}
describe('database-backed persistence', () => {
it('persists permissions and admin profile changes through TypeORM repositories', async () => {
const permissionRepository = createRepository();
const roleRepository = createRepository();
const adminUserRepository = createRepository();
const dataSource = createDataSource({
Permission: permissionRepository,
Role: roleRepository,
AdminUser: adminUserRepository,
});
const service = new AdminService(
{ signAsync: jest.fn() } as never,
dataSource as never,
);
await service.onModuleInit();
const permissions = await service.listPermissions({ page: 1, pageSize: 50 });
expect(permissions.list).toEqual(
expect.arrayContaining([
expect.objectContaining({ code: 'permission:read', name: '查看权限' }),
expect.objectContaining({ code: 'data:read', name: '查看数据' }),
]),
);
const updated = await service.updateProfile(1, {
nickname: '数据库管理员',
email: 'db-admin@example.com',
});
expect(updated).toMatchObject({
id: 1,
nickname: '数据库管理员',
email: 'db-admin@example.com',
});
expect(adminUserRepository.save).toHaveBeenCalledWith(
expect.objectContaining({
nickname: '数据库管理员',
email: 'db-admin@example.com',
}),
);
});
it('persists app users through TypeORM repositories when a DataSource is configured', async () => {
const userRepository = createRepository();
const dataSource = createDataSource({ User: userRepository });
const service = new UsersService(dataSource as never);
const result = await service.upsertTikTokUser({
tiktokOpenId: 'open-db-1',
nickname: 'DB User',
});
expect(result.isNewUser).toBe(true);
expect(userRepository.save).toHaveBeenCalledWith(
expect.objectContaining({
tiktokOpenId: 'open-db-1',
nickname: 'DB User',
status: 'active',
}),
);
});
it('persists request logs and playback error logs through TypeORM repositories', async () => {
const requestLogRepository = createRepository();
const playbackErrorLogRepository = createRepository();
const dataSource = createDataSource({
RequestLog: requestLogRepository,
PlaybackErrorLog: playbackErrorLogRepository,
});
const service = new LogsService(dataSource as never);
await service.recordRequest({
requestId: '00000000-0000-4000-8000-000000000001',
method: 'GET',
path: '/api/admin/v1/logs',
statusCode: 200,
responseCode: 0,
message: 'success',
costMs: 3,
});
await service.createPlaybackError({
requestId: '00000000-0000-4000-8000-000000000002',
dramaId: 1,
episodeId: 2,
playUrl: 'https://cdn.example.com/video.mp4',
playerErrorCode: 'NETWORK',
message: 'network error',
occurredAt: '2026-07-01T00:00:00.000Z',
});
expect(requestLogRepository.save).toHaveBeenCalled();
expect(playbackErrorLogRepository.save).toHaveBeenCalled();
});
it('persists synced drama and episode metrics through TypeORM repositories', async () => {
const dramaMetricRepository = createRepository();
const episodeMetricRepository = createRepository();
const syncJobRepository = createRepository();
const dataSource = createDataSource({
DramaMetric: dramaMetricRepository,
EpisodeMetric: episodeMetricRepository,
DataSyncJob: syncJobRepository,
});
const dramasService = new DramasService();
const tiktokDataProvider = new TikTokDataProvider();
const service = new DataService(
dramasService,
tiktokDataProvider,
dataSource as never,
);
const drama = await dramasService.createDrama({
title: 'DB Metrics',
coverUrl: 'https://cdn.example.com/cover.jpg',
type: 'action',
status: PublishStatus.Published,
});
await dramasService.createEpisode({
dramaId: drama.id,
episodeNo: 1,
title: 'DB Metrics Episode',
coverUrl: drama.coverUrl,
videoUrl: 'https://cdn.example.com/video.mp4',
durationSeconds: 180,
status: PublishStatus.Published,
});
await service.sync({ dramaId: drama.id });
expect(dramaMetricRepository.save).toHaveBeenCalled();
expect(episodeMetricRepository.save).toHaveBeenCalled();
expect(syncJobRepository.save).toHaveBeenCalled();
});
});

View File

@@ -122,6 +122,89 @@ describe('Dramas and episodes', () => {
});
});
it('creates episode slots when a new drama declares total episodes', async () => {
const drama = await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Preconfigured Slots Drama',
coverUrl: 'https://cdn.example.com/preconfigured-slots.jpg',
type: 'romance',
status: 'draft',
totalEpisodes: 2,
})
.expect(201);
expect(drama.body.data).toMatchObject({
title: 'Preconfigured Slots Drama',
totalEpisodes: 2,
publishedEpisodes: 0,
});
const episodes = await request(app.getHttpServer())
.get(`/api/admin/v1/dramas/${drama.body.data.id}/episodes`)
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
expect(episodes.body.data.list).toEqual([
expect.objectContaining({
dramaId: drama.body.data.id,
episodeNo: 1,
title: '第1集',
publishStatus: 'draft',
}),
expect.objectContaining({
dramaId: drama.body.data.id,
episodeNo: 2,
title: '第2集',
publishStatus: 'draft',
}),
]);
});
it('updates an episode from the drama detail episodes endpoint', async () => {
const drama = await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Nested Episode Update Drama',
coverUrl: 'https://cdn.example.com/nested-update.jpg',
type: 'action',
status: 'draft',
totalEpisodes: 1,
})
.expect(201);
const episodes = await request(app.getHttpServer())
.get(`/api/admin/v1/dramas/${drama.body.data.id}/episodes`)
.set('Authorization', `Bearer ${adminToken}`)
.expect(200);
const episodeId = episodes.body.data.list[0].id;
const updated = await request(app.getHttpServer())
.patch(`/api/admin/v1/dramas/${drama.body.data.id}/episodes/${episodeId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Updated Nested Episode',
description: 'Updated from drama detail.',
durationSeconds: 240,
freeType: 'paid',
price: 199,
})
.expect(200);
expect(updated.body.data).toMatchObject({
id: episodeId,
dramaId: drama.body.data.id,
title: 'Updated Nested Episode',
description: 'Updated from drama detail.',
durationSeconds: 240,
freeType: 'paid',
isPaid: true,
price: 199,
});
});
it('returns only published dramas and published episodes to app APIs', async () => {
const published = await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
@@ -197,4 +280,45 @@ describe('Dramas and episodes', () => {
}),
]);
});
it('filters published dramas by title and defaults app page size to 10', async () => {
await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Searchable Moon Drama',
coverUrl: 'https://cdn.example.com/searchable-moon.jpg',
type: 'romance',
status: 'published',
})
.expect(201);
await request(app.getHttpServer())
.post('/api/admin/v1/dramas')
.set('Authorization', `Bearer ${adminToken}`)
.send({
title: 'Hidden Sun Drama',
coverUrl: 'https://cdn.example.com/hidden-sun.jpg',
type: 'romance',
status: 'published',
})
.expect(201);
const response = await request(app.getHttpServer())
.get('/api/app/v1/dramas')
.query({ title: 'Moon' })
.expect(200);
expect(response.body.data.pagination.pageSize).toBe(10);
expect(response.body.data.list).toEqual(
expect.arrayContaining([
expect.objectContaining({ title: 'Searchable Moon Drama' }),
]),
);
expect(response.body.data.list).not.toEqual(
expect.arrayContaining([
expect.objectContaining({ title: 'Hidden Sun Drama' }),
]),
);
});
});

View File

@@ -1,19 +1,19 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"strict": true,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"noImplicitAny": false
}
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"strict": true,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"noImplicitAny": false
}
}