chore: 初始化TikTok短剧后端项目基础架构
创建了完整的NestJS项目结构,包含配置文件、核心模块、工具类、拦截器、过滤器等基础代码,实现了健康检查、用户认证、管理员RBAC、剧集管理、订单支付、媒体管理等核心功能的基础框架,配置了ESLint、TypeScript、Jest等开发工具链。
This commit is contained in:
146
src/modules/admin/admin.controller.ts
Normal file
146
src/modules/admin/admin.controller.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentAdmin } from './decorators/current-admin.decorator';
|
||||
import { RequirePermissions } from './decorators/require-permissions.decorator';
|
||||
import { AdminLoginDto } from './dto/admin-login.dto';
|
||||
import { ChangeAdminPasswordDto } from './dto/change-admin-password.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 { UpdateAdminRolesDto } from './dto/update-admin-roles.dto';
|
||||
import { UpdateAdminStatusDto } from './dto/update-admin-status.dto';
|
||||
import { UpdateRolePermissionsDto } from './dto/update-role-permissions.dto';
|
||||
import { AdminJwtAuthGuard } from './guards/admin-jwt-auth.guard';
|
||||
import { PermissionsGuard } from './guards/permissions.guard';
|
||||
import { AdminUserRecord } from './interfaces/admin-records.interface';
|
||||
import { AdminService } from './admin.service';
|
||||
|
||||
@ApiTags('Admin')
|
||||
@Controller('/api/admin/v1')
|
||||
export class AdminController {
|
||||
constructor(private readonly adminService: AdminService) {}
|
||||
|
||||
@Post('/auth/login')
|
||||
login(@Body() dto: AdminLoginDto) {
|
||||
return this.adminService.login(dto);
|
||||
}
|
||||
|
||||
@Get('/auth/profile')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard)
|
||||
getProfile(@CurrentAdmin() admin: AdminUserRecord) {
|
||||
return this.adminService.toAdminView(admin);
|
||||
}
|
||||
|
||||
@Patch('/auth/profile')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard)
|
||||
updateProfile(
|
||||
@CurrentAdmin() admin: AdminUserRecord,
|
||||
@Body() dto: UpdateAdminProfileDto,
|
||||
) {
|
||||
return this.adminService.updateProfile(admin.id, dto);
|
||||
}
|
||||
|
||||
@Patch('/auth/password')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard)
|
||||
changePassword(
|
||||
@CurrentAdmin() admin: AdminUserRecord,
|
||||
@Body() dto: ChangeAdminPasswordDto,
|
||||
) {
|
||||
return this.adminService.changePassword(
|
||||
admin.id,
|
||||
dto.oldPassword,
|
||||
dto.newPassword,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/permissions')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('permission:read')
|
||||
listPermissions(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||
return this.adminService.listPermissions({
|
||||
page: Number(page) || 1,
|
||||
pageSize: Number(pageSize) || 20,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('/permissions')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('permission:create')
|
||||
createPermission(@Body() dto: CreatePermissionDto) {
|
||||
return this.adminService.createPermission(dto);
|
||||
}
|
||||
|
||||
@Get('/roles')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('role:read')
|
||||
listRoles(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||
return this.adminService.listRoles({
|
||||
page: Number(page) || 1,
|
||||
pageSize: Number(pageSize) || 20,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('/roles')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('role:create')
|
||||
createRole(@Body() dto: CreateRoleDto) {
|
||||
return this.adminService.createRole(dto);
|
||||
}
|
||||
|
||||
@Patch('/roles/:id/permissions')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('role:update')
|
||||
updateRolePermissions(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateRolePermissionsDto,
|
||||
) {
|
||||
return this.adminService.updateRolePermissions(
|
||||
Number(id),
|
||||
dto.permissionIds,
|
||||
);
|
||||
}
|
||||
|
||||
@Get('/admin-users')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('admin-user:read')
|
||||
listAdminUsers(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||
return this.adminService.listAdminUsers({
|
||||
page: Number(page) || 1,
|
||||
pageSize: Number(pageSize) || 20,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('/admin-users')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('admin-user:create')
|
||||
createAdminUser(@Body() dto: CreateAdminUserDto) {
|
||||
return this.adminService.createAdminUser(dto);
|
||||
}
|
||||
|
||||
@Patch('/admin-users/:id/roles')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('admin-user:update')
|
||||
updateAdminRoles(@Param('id') id: string, @Body() dto: UpdateAdminRolesDto) {
|
||||
return this.adminService.updateAdminRoles(Number(id), dto.roleIds);
|
||||
}
|
||||
|
||||
@Patch('/admin-users/:id/status')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('admin-user:update')
|
||||
updateAdminStatus(@Param('id') id: string, @Body() dto: UpdateAdminStatusDto) {
|
||||
return this.adminService.updateAdminStatus(Number(id), dto.status);
|
||||
}
|
||||
}
|
||||
20
src/modules/admin/admin.module.ts
Normal file
20
src/modules/admin/admin.module.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { AdminController } from './admin.controller';
|
||||
import { AdminService } from './admin.service';
|
||||
import { AdminJwtAuthGuard } from './guards/admin-jwt-auth.guard';
|
||||
import { PermissionsGuard } from './guards/permissions.guard';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [
|
||||
JwtModule.register({
|
||||
secret: process.env.ADMIN_JWT_SECRET ?? process.env.JWT_SECRET ?? 'development-secret',
|
||||
signOptions: { expiresIn: '12h' },
|
||||
}),
|
||||
],
|
||||
controllers: [AdminController],
|
||||
providers: [AdminService, AdminJwtAuthGuard, PermissionsGuard],
|
||||
exports: [JwtModule, AdminService, AdminJwtAuthGuard, PermissionsGuard],
|
||||
})
|
||||
export class AdminModule {}
|
||||
318
src/modules/admin/admin.service.ts
Normal file
318
src/modules/admin/admin.service.ts
Normal file
@@ -0,0 +1,318 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
UnprocessableEntityException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
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 {
|
||||
AdminUserRecord,
|
||||
AdminUserView,
|
||||
PermissionRecord,
|
||||
RoleRecord,
|
||||
} from './interfaces/admin-records.interface';
|
||||
|
||||
interface PaginationInput {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
private permissionSequence = 1;
|
||||
private roleSequence = 1;
|
||||
private adminSequence = 1;
|
||||
private readonly permissions: PermissionRecord[] = [];
|
||||
private readonly roles: RoleRecord[] = [];
|
||||
private readonly admins: AdminUserRecord[] = [];
|
||||
|
||||
constructor(private readonly jwtService: JwtService) {
|
||||
this.seed();
|
||||
}
|
||||
|
||||
async login(dto: AdminLoginDto) {
|
||||
const admin = this.admins.find((item) => item.username === dto.username);
|
||||
if (
|
||||
!admin ||
|
||||
admin.status !== 'active' ||
|
||||
!bcrypt.compareSync(dto.password, admin.passwordHash)
|
||||
) {
|
||||
throw new UnauthorizedException('Invalid username or password');
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken: await this.jwtService.signAsync({
|
||||
sub: admin.id,
|
||||
username: admin.username,
|
||||
type: 'admin',
|
||||
}),
|
||||
admin: this.toAdminView(admin),
|
||||
};
|
||||
}
|
||||
|
||||
createPermission(dto: CreatePermissionDto): PermissionRecord {
|
||||
if (this.permissions.some((item) => item.code === dto.code)) {
|
||||
throw new ConflictException('Permission code already exists');
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const permission: PermissionRecord = {
|
||||
id: this.permissionSequence++,
|
||||
code: dto.code,
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.permissions.push(permission);
|
||||
return permission;
|
||||
}
|
||||
|
||||
listPermissions(
|
||||
pagination: PaginationInput,
|
||||
): PaginatedResponse<PermissionRecord> {
|
||||
return this.paginate([...this.permissions], pagination);
|
||||
}
|
||||
|
||||
createRole(dto: CreateRoleDto): RoleRecord {
|
||||
if (this.roles.some((item) => item.code === dto.code)) {
|
||||
throw new ConflictException('Role code already exists');
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const permissionIds = dto.permissionIds ?? [];
|
||||
const role: RoleRecord = {
|
||||
id: this.roleSequence++,
|
||||
code: dto.code,
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
permissionIds,
|
||||
permissions: this.permissions.filter((permission) =>
|
||||
permissionIds.includes(permission.id),
|
||||
),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.roles.push(role);
|
||||
return role;
|
||||
}
|
||||
|
||||
listRoles(pagination: PaginationInput): PaginatedResponse<RoleRecord> {
|
||||
return this.paginate([...this.roles], pagination);
|
||||
}
|
||||
|
||||
updateRolePermissions(id: number, permissionIds: number[]): RoleRecord {
|
||||
const role = this.roles.find((item) => item.id === id);
|
||||
if (!role) {
|
||||
throw new NotFoundException('Role not found');
|
||||
}
|
||||
|
||||
const uniquePermissionIds = [...new Set(permissionIds)];
|
||||
role.permissionIds = uniquePermissionIds;
|
||||
role.permissions = this.permissions.filter((permission) =>
|
||||
uniquePermissionIds.includes(permission.id),
|
||||
);
|
||||
role.updatedAt = new Date().toISOString();
|
||||
return role;
|
||||
}
|
||||
|
||||
createAdminUser(dto: CreateAdminUserDto): AdminUserView {
|
||||
if (this.admins.some((item) => item.username === dto.username)) {
|
||||
throw new ConflictException('Admin username already exists');
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const admin: AdminUserRecord = {
|
||||
id: this.adminSequence++,
|
||||
username: dto.username,
|
||||
passwordHash: bcrypt.hashSync(dto.password, 10),
|
||||
nickname: dto.nickname,
|
||||
email: dto.email,
|
||||
status: 'active',
|
||||
isSuperAdmin: false,
|
||||
roleIds: dto.roleIds ?? [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.admins.push(admin);
|
||||
return this.toAdminView(admin);
|
||||
}
|
||||
|
||||
listAdminUsers(
|
||||
pagination: PaginationInput,
|
||||
): PaginatedResponse<AdminUserView> {
|
||||
return this.paginate(
|
||||
this.admins.map((admin) => this.toAdminView(admin)),
|
||||
pagination,
|
||||
);
|
||||
}
|
||||
|
||||
updateAdminStatus(
|
||||
id: number,
|
||||
status: 'active' | 'disabled',
|
||||
): AdminUserView {
|
||||
const admin = this.findAdminById(id);
|
||||
if (!admin) {
|
||||
throw new NotFoundException('Admin user not found');
|
||||
}
|
||||
|
||||
admin.status = status;
|
||||
admin.updatedAt = new Date().toISOString();
|
||||
return this.toAdminView(admin);
|
||||
}
|
||||
|
||||
updateAdminRoles(id: number, roleIds: number[]): AdminUserView {
|
||||
const admin = this.findAdminById(id);
|
||||
if (!admin) {
|
||||
throw new NotFoundException('Admin user not found');
|
||||
}
|
||||
|
||||
admin.roleIds = [...new Set(roleIds)];
|
||||
admin.updatedAt = new Date().toISOString();
|
||||
return this.toAdminView(admin);
|
||||
}
|
||||
|
||||
updateProfile(
|
||||
adminId: number,
|
||||
dto: UpdateAdminProfileDto,
|
||||
): AdminUserView {
|
||||
const admin = this.findAdminById(adminId);
|
||||
if (!admin) {
|
||||
throw new NotFoundException('Admin user not found');
|
||||
}
|
||||
|
||||
admin.nickname = dto.nickname;
|
||||
admin.email = dto.email;
|
||||
admin.updatedAt = new Date().toISOString();
|
||||
return this.toAdminView(admin);
|
||||
}
|
||||
|
||||
changePassword(
|
||||
adminId: number,
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
): Record<string, never> {
|
||||
const admin = this.findAdminById(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);
|
||||
admin.updatedAt = new Date().toISOString();
|
||||
return {};
|
||||
}
|
||||
|
||||
findAdminById(id: number) {
|
||||
return this.admins.find((admin) => admin.id === id);
|
||||
}
|
||||
|
||||
getPermissionCodesForAdmin(adminId: number) {
|
||||
const admin = this.findAdminById(adminId);
|
||||
if (!admin) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (admin.isSuperAdmin) {
|
||||
return ['*'];
|
||||
}
|
||||
|
||||
return this.roles
|
||||
.filter((role) => admin.roleIds.includes(role.id))
|
||||
.flatMap((role) => role.permissions.map((permission) => permission.code));
|
||||
}
|
||||
|
||||
toAdminView(admin: AdminUserRecord): AdminUserView {
|
||||
const roles = this.roles.filter((role) => admin.roleIds.includes(role.id));
|
||||
const permissions: PermissionRecord[] | ['*'] = admin.isSuperAdmin
|
||||
? ['*']
|
||||
: roles.flatMap((role) => role.permissions);
|
||||
|
||||
return {
|
||||
id: admin.id,
|
||||
username: admin.username,
|
||||
nickname: admin.nickname,
|
||||
email: admin.email,
|
||||
status: admin.status,
|
||||
isSuperAdmin: admin.isSuperAdmin,
|
||||
roles,
|
||||
permissions,
|
||||
createdAt: admin.createdAt,
|
||||
updatedAt: admin.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
private seed() {
|
||||
const codes = [
|
||||
['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', '创建媒体'],
|
||||
['payment:read', '查看支付记录'],
|
||||
['log:read', '查看日志'],
|
||||
];
|
||||
|
||||
for (const [code, name] of codes) {
|
||||
this.createPermission({ code, name });
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
this.admins.push({
|
||||
id: this.adminSequence++,
|
||||
username: process.env.ADMIN_USERNAME ?? 'admin',
|
||||
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: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
12
src/modules/admin/decorators/current-admin.decorator.ts
Normal file
12
src/modules/admin/decorators/current-admin.decorator.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||
|
||||
export const CurrentAdmin = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): AdminUserRecord | undefined => {
|
||||
const request = ctx
|
||||
.switchToHttp()
|
||||
.getRequest<Request & { adminUser?: AdminUserRecord }>();
|
||||
return request.adminUser;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const REQUIRED_PERMISSIONS_METADATA = 'admin:required-permissions';
|
||||
|
||||
export const RequirePermissions = (...permissions: string[]) =>
|
||||
SetMetadata(REQUIRED_PERMISSIONS_METADATA, permissions);
|
||||
13
src/modules/admin/dto/admin-login.dto.ts
Normal file
13
src/modules/admin/dto/admin-login.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class AdminLoginDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(6)
|
||||
password: string;
|
||||
}
|
||||
13
src/modules/admin/dto/change-admin-password.dto.ts
Normal file
13
src/modules/admin/dto/change-admin-password.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class ChangeAdminPasswordDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
oldPassword: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(6)
|
||||
newPassword: string;
|
||||
}
|
||||
38
src/modules/admin/dto/create-admin-user.dto.ts
Normal file
38
src/modules/admin/dto/create-admin-user.dto.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsArray,
|
||||
IsEmail,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateAdminUserDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
username: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@MinLength(6)
|
||||
password: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
nickname?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
email?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [Number] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
roleIds?: number[];
|
||||
}
|
||||
17
src/modules/admin/dto/create-permission.dto.ts
Normal file
17
src/modules/admin/dto/create-permission.dto.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreatePermissionDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
code: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
}
|
||||
30
src/modules/admin/dto/create-role.dto.ts
Normal file
30
src/modules/admin/dto/create-role.dto.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsArray,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateRoleDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
code: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [Number] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
permissionIds?: number[];
|
||||
}
|
||||
14
src/modules/admin/dto/update-admin-profile.dto.ts
Normal file
14
src/modules/admin/dto/update-admin-profile.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsEmail, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class UpdateAdminProfileDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
nickname?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsEmail()
|
||||
email?: string;
|
||||
}
|
||||
10
src/modules/admin/dto/update-admin-roles.dto.ts
Normal file
10
src/modules/admin/dto/update-admin-roles.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsArray, IsInt, Min } from 'class-validator';
|
||||
|
||||
export class UpdateAdminRolesDto {
|
||||
@ApiProperty({ type: [Number] })
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
roleIds: number[];
|
||||
}
|
||||
8
src/modules/admin/dto/update-admin-status.dto.ts
Normal file
8
src/modules/admin/dto/update-admin-status.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsIn } from 'class-validator';
|
||||
|
||||
export class UpdateAdminStatusDto {
|
||||
@ApiProperty({ enum: ['active', 'disabled'] })
|
||||
@IsIn(['active', 'disabled'])
|
||||
status: 'active' | 'disabled';
|
||||
}
|
||||
10
src/modules/admin/dto/update-role-permissions.dto.ts
Normal file
10
src/modules/admin/dto/update-role-permissions.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsArray, IsInt, Min } from 'class-validator';
|
||||
|
||||
export class UpdateRolePermissionsDto {
|
||||
@ApiProperty({ type: [Number] })
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
@Min(1, { each: true })
|
||||
permissionIds: number[];
|
||||
}
|
||||
39
src/modules/admin/entities/admin-user.entity.ts
Normal file
39
src/modules/admin/entities/admin-user.entity.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('admin_users')
|
||||
export class AdminUser {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
username: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
passwordHash: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
nickname?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, default: 'active' })
|
||||
status: string;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
isSuperAdmin: boolean;
|
||||
|
||||
@Column({ type: 'json', nullable: true })
|
||||
roleIds?: number[];
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
30
src/modules/admin/entities/permission.entity.ts
Normal file
30
src/modules/admin/entities/permission.entity.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('permissions')
|
||||
export class Permission {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
code: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 512, nullable: true })
|
||||
description?: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
33
src/modules/admin/entities/role.entity.ts
Normal file
33
src/modules/admin/entities/role.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('roles')
|
||||
export class Role {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
code: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
name: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 512, nullable: true })
|
||||
description?: string;
|
||||
|
||||
@Column({ type: 'json', nullable: true })
|
||||
permissionIds?: number[];
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
53
src/modules/admin/guards/admin-jwt-auth.guard.ts
Normal file
53
src/modules/admin/guards/admin-jwt-auth.guard.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||
import { AdminService } from '../admin.service';
|
||||
|
||||
@Injectable()
|
||||
export class AdminJwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly adminService: AdminService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<Request & { adminUser?: AdminUserRecord; adminId?: number }>();
|
||||
const authHeader = request.get('authorization');
|
||||
const token = authHeader?.startsWith('Bearer ')
|
||||
? authHeader.slice('Bearer '.length)
|
||||
: undefined;
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Admin not authenticated');
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync<{
|
||||
sub: number;
|
||||
type: string;
|
||||
}>(token);
|
||||
if (payload.type !== 'admin') {
|
||||
throw new UnauthorizedException('Admin not authenticated');
|
||||
}
|
||||
|
||||
const adminUser = this.adminService.findAdminById(payload.sub);
|
||||
if (!adminUser || adminUser.status !== 'active') {
|
||||
throw new UnauthorizedException('Admin not authenticated');
|
||||
}
|
||||
|
||||
request.adminUser = adminUser;
|
||||
request.adminId = adminUser.id;
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Admin not authenticated');
|
||||
}
|
||||
}
|
||||
}
|
||||
52
src/modules/admin/guards/permissions.guard.ts
Normal file
52
src/modules/admin/guards/permissions.guard.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request } from 'express';
|
||||
import {
|
||||
REQUIRED_PERMISSIONS_METADATA,
|
||||
} from '../decorators/require-permissions.decorator';
|
||||
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||
import { AdminService } from '../admin.service';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly adminService: AdminService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const required =
|
||||
this.reflector.getAllAndOverride<string[]>(
|
||||
REQUIRED_PERMISSIONS_METADATA,
|
||||
[context.getHandler(), context.getClass()],
|
||||
) ?? [];
|
||||
|
||||
if (required.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context
|
||||
.switchToHttp()
|
||||
.getRequest<Request & { adminUser?: AdminUserRecord }>();
|
||||
const adminUser = request.adminUser;
|
||||
|
||||
if (!adminUser) {
|
||||
throw new ForbiddenException('No permission');
|
||||
}
|
||||
|
||||
if (adminUser.isSuperAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const permissions = this.adminService.getPermissionCodesForAdmin(adminUser.id);
|
||||
const allowed = required.every((permission) =>
|
||||
permissions.includes(permission),
|
||||
);
|
||||
|
||||
if (!allowed) {
|
||||
throw new ForbiddenException('No permission');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
45
src/modules/admin/interfaces/admin-records.interface.ts
Normal file
45
src/modules/admin/interfaces/admin-records.interface.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
export interface PermissionRecord {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface RoleRecord {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
permissionIds: number[];
|
||||
permissions: PermissionRecord[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface AdminUserRecord {
|
||||
id: number;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
nickname?: string;
|
||||
email?: string;
|
||||
status: 'active' | 'disabled';
|
||||
isSuperAdmin: boolean;
|
||||
roleIds: number[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface AdminUserView {
|
||||
id: number;
|
||||
username: string;
|
||||
nickname?: string;
|
||||
email?: string;
|
||||
status: 'active' | 'disabled';
|
||||
isSuperAdmin: boolean;
|
||||
roles: RoleRecord[];
|
||||
permissions: PermissionRecord[] | ['*'];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
15
src/modules/auth/auth.controller.ts
Normal file
15
src/modules/auth/auth.controller.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthService } from './auth.service';
|
||||
import { TikTokLoginDto } from './dto/tiktok-login.dto';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@Controller('/api/app/v1/auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('/tiktok-login')
|
||||
loginWithTikTok(@Body() dto: TikTokLoginDto) {
|
||||
return this.authService.loginWithTikTok(dto);
|
||||
}
|
||||
}
|
||||
20
src/modules/auth/auth.module.ts
Normal file
20
src/modules/auth/auth.module.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
JwtModule.register({
|
||||
secret: process.env.JWT_SECRET ?? 'development-secret',
|
||||
signOptions: { expiresIn: '30d' },
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard],
|
||||
exports: [JwtModule, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
39
src/modules/auth/auth.service.ts
Normal file
39
src/modules/auth/auth.service.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { TikTokLoginDto } from './dto/tiktok-login.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly usersService: UsersService,
|
||||
) {}
|
||||
|
||||
async loginWithTikTok(dto: TikTokLoginDto) {
|
||||
const tiktokOpenId = dto.mockOpenId ?? this.resolveOpenIdFromCode(dto.code);
|
||||
const result = this.usersService.upsertTikTokUser({
|
||||
tiktokOpenId,
|
||||
tiktokUnionId: dto.tiktokUnionId,
|
||||
nickname: dto.nickname,
|
||||
avatarUrl: dto.avatarUrl,
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken: await this.jwtService.signAsync({
|
||||
sub: result.user.id,
|
||||
tiktokOpenId: result.user.tiktokOpenId,
|
||||
}),
|
||||
user: result.user,
|
||||
isNewUser: result.isNewUser,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveOpenIdFromCode(code: string) {
|
||||
if (!code) {
|
||||
throw new UnprocessableEntityException('TikTok login code is required');
|
||||
}
|
||||
|
||||
return `mock-${code}`;
|
||||
}
|
||||
}
|
||||
10
src/modules/auth/decorators/current-user.decorator.ts
Normal file
10
src/modules/auth/decorators/current-user.decorator.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { UserRecord } from '../../users/interfaces/user-record.interface';
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(_data: unknown, ctx: ExecutionContext): UserRecord | undefined => {
|
||||
const request = ctx.switchToHttp().getRequest<Request & { user?: UserRecord }>();
|
||||
return request.user;
|
||||
},
|
||||
);
|
||||
30
src/modules/auth/dto/tiktok-login.dto.ts
Normal file
30
src/modules/auth/dto/tiktok-login.dto.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class TikTokLoginDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
code: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'Development-only mock open id until TikTok app credentials are configured.',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mockOpenId?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tiktokUnionId?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
nickname?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
avatarUrl?: string;
|
||||
}
|
||||
42
src/modules/auth/guards/jwt-auth.guard.ts
Normal file
42
src/modules/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
import { UsersService } from '../../users/users.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly usersService: UsersService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request & { user?: unknown }>();
|
||||
const authHeader = request.get('authorization');
|
||||
const token = authHeader?.startsWith('Bearer ')
|
||||
? authHeader.slice('Bearer '.length)
|
||||
: undefined;
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Not authenticated');
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync<{ sub: number }>(token);
|
||||
const user = this.usersService.findById(payload.sub);
|
||||
if (!user || user.status !== 'active') {
|
||||
throw new UnauthorizedException('Not authenticated');
|
||||
}
|
||||
|
||||
request.user = user;
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Not authenticated');
|
||||
}
|
||||
}
|
||||
}
|
||||
6
src/modules/dramas/drama-status.enum.ts
Normal file
6
src/modules/dramas/drama-status.enum.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export enum PublishStatus {
|
||||
Draft = 'draft',
|
||||
Scheduled = 'scheduled',
|
||||
Published = 'published',
|
||||
Offline = 'offline',
|
||||
}
|
||||
87
src/modules/dramas/dramas.controller.ts
Normal file
87
src/modules/dramas/dramas.controller.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
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';
|
||||
|
||||
@ApiTags('Dramas')
|
||||
@Controller()
|
||||
export class DramasController {
|
||||
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);
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@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,
|
||||
) {
|
||||
return this.dramasService.listPublishedDramas({
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
12
src/modules/dramas/dramas.module.ts
Normal file
12
src/modules/dramas/dramas.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { DramasController } from './dramas.controller';
|
||||
import { DramasService } from './dramas.service';
|
||||
|
||||
@Module({
|
||||
imports: [AdminModule],
|
||||
controllers: [DramasController],
|
||||
providers: [DramasService],
|
||||
exports: [DramasService],
|
||||
})
|
||||
export class DramasModule {}
|
||||
221
src/modules/dramas/dramas.service.ts
Normal file
221
src/modules/dramas/dramas.service.ts
Normal file
@@ -0,0 +1,221 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||
import { CreateDramaDto } from './dto/create-drama.dto';
|
||||
import { CreateEpisodeDto } from './dto/create-episode.dto';
|
||||
import { PublishStatus } from './drama-status.enum';
|
||||
import {
|
||||
DramaRecord,
|
||||
EpisodeRecord,
|
||||
} from './interfaces/drama-records.interface';
|
||||
|
||||
interface PaginationInput {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class DramasService {
|
||||
private dramaSequence = 1;
|
||||
private episodeSequence = 1;
|
||||
private readonly dramas: DramaRecord[] = [];
|
||||
private readonly episodes: EpisodeRecord[] = [];
|
||||
|
||||
createDrama(dto: CreateDramaDto): DramaRecord {
|
||||
const now = new Date().toISOString();
|
||||
const drama: DramaRecord = {
|
||||
id: this.dramaSequence++,
|
||||
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,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.dramas.push(drama);
|
||||
return drama;
|
||||
}
|
||||
|
||||
listAdminDramas(pagination: PaginationInput): PaginatedResponse<DramaRecord> {
|
||||
return this.paginate(this.sortDramas(this.dramas), pagination);
|
||||
}
|
||||
|
||||
createEpisode(dto: CreateEpisodeDto): EpisodeRecord {
|
||||
const dramaId = dto.dramaId ?? dto.albumId;
|
||||
const episodeNo = dto.episodeNo ?? dto.seq;
|
||||
if (!dramaId || !episodeNo) {
|
||||
throw new NotFoundException('Drama not found');
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
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,
|
||||
albumId: dramaId,
|
||||
tiktokEpisodeId: dto.tiktokEpisodeId,
|
||||
episodeNo,
|
||||
seq: 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,
|
||||
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,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.episodes.push(episode);
|
||||
return episode;
|
||||
}
|
||||
|
||||
listPublishedDramas(
|
||||
pagination: PaginationInput,
|
||||
): PaginatedResponse<DramaRecord> {
|
||||
return this.paginate(
|
||||
this.sortDramas(
|
||||
this.dramas.filter((item) => item.status === PublishStatus.Published),
|
||||
),
|
||||
pagination,
|
||||
);
|
||||
}
|
||||
|
||||
listPublishedEpisodes(
|
||||
dramaId: number,
|
||||
pagination: PaginationInput,
|
||||
): PaginatedResponse<EpisodeRecord> {
|
||||
const drama = this.dramas.find((item) => item.id === dramaId);
|
||||
if (!drama || drama.status !== PublishStatus.Published) {
|
||||
throw new NotFoundException('Drama not found');
|
||||
}
|
||||
|
||||
const episodes = this.episodes
|
||||
.filter(
|
||||
(item) =>
|
||||
item.dramaId === dramaId && item.status === PublishStatus.Published,
|
||||
)
|
||||
.sort((left, right) => left.episodeNo - right.episodeNo);
|
||||
|
||||
return this.paginate(episodes, pagination);
|
||||
}
|
||||
|
||||
getPublishedEpisodeOrThrow(episodeId: number): EpisodeRecord {
|
||||
const episode = this.episodes.find((item) => item.id === episodeId);
|
||||
if (!episode || episode.status !== PublishStatus.Published) {
|
||||
throw new NotFoundException('Episode not found');
|
||||
}
|
||||
|
||||
const drama = this.dramas.find((item) => item.id === episode.dramaId);
|
||||
if (!drama || drama.status !== PublishStatus.Published) {
|
||||
throw new NotFoundException('Episode not found');
|
||||
}
|
||||
|
||||
return episode;
|
||||
}
|
||||
|
||||
getEpisodeOrThrow(episodeId: number): EpisodeRecord {
|
||||
const episode = this.episodes.find((item) => item.id === episodeId);
|
||||
if (!episode) {
|
||||
throw new NotFoundException('Episode not found');
|
||||
}
|
||||
|
||||
return episode;
|
||||
}
|
||||
|
||||
submitReview(albumId: number) {
|
||||
const album = this.dramas.find((item) => item.id === albumId);
|
||||
if (!album) {
|
||||
throw new NotFoundException('Drama not found');
|
||||
}
|
||||
|
||||
this.episodes
|
||||
.filter((episode) => episode.albumId === albumId)
|
||||
.forEach((episode) => {
|
||||
episode.reviewStatus = 'pending';
|
||||
episode.updatedAt = new Date().toISOString();
|
||||
});
|
||||
|
||||
return {
|
||||
albumId,
|
||||
reviewStatus: 'pending',
|
||||
};
|
||||
}
|
||||
|
||||
updateEpisodePublishStatus(episodeId: number, publishStatus: PublishStatus) {
|
||||
const episode = this.getEpisodeOrThrow(episodeId);
|
||||
episode.publishStatus = publishStatus;
|
||||
episode.status = publishStatus;
|
||||
episode.updatedAt = new Date().toISOString();
|
||||
return episode;
|
||||
}
|
||||
|
||||
private sortDramas(records: DramaRecord[]) {
|
||||
return [...records].sort((left, right) => {
|
||||
if (right.sortOrder !== left.sortOrder) {
|
||||
return right.sortOrder - left.sortOrder;
|
||||
}
|
||||
|
||||
return right.id - left.id;
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
96
src/modules/dramas/dto/create-drama.dto.ts
Normal file
96
src/modules/dramas/dto/create-drama.dto.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUrl,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { PublishStatus } from '../drama-status.enum';
|
||||
|
||||
export class CreateDramaDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tiktokAlbumId?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
coverUrl: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
coverId?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
portraitCoverUrl?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
landscapeCoverUrl?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
type: string;
|
||||
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
tags?: string[];
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
region?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
language?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1900)
|
||||
year?: number;
|
||||
|
||||
@ApiPropertyOptional({ enum: PublishStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(PublishStatus)
|
||||
status?: PublishStatus;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
sortOrder?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isRecommended?: boolean;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
onlineVersion?: number;
|
||||
}
|
||||
131
src/modules/dramas/dto/create-episode.dto.ts
Normal file
131
src/modules/dramas/dto/create-episode.dto.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import {
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUrl,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { PublishStatus } from '../drama-status.enum';
|
||||
|
||||
export class CreateEpisodeDto {
|
||||
@ApiProperty()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
dramaId?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
albumId?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tiktokEpisodeId?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
episodeNo?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
seq?: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
title: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
coverUrl: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
coverId?: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsOptional()
|
||||
@IsUrl({ require_tld: false })
|
||||
videoUrl?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
byteplusVid?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
trialDurationSeconds?: number;
|
||||
|
||||
@ApiProperty()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
durationSeconds: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
isPaid?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['free', 'paid'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
freeType?: 'free' | 'paid';
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
unlockPrice?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
price?: number;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
publishAt?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
nextReleaseAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ enum: PublishStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(PublishStatus)
|
||||
status?: PublishStatus;
|
||||
|
||||
@ApiPropertyOptional({ enum: ['pending', 'approved', 'rejected'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
reviewStatus?: 'pending' | 'approved' | 'rejected';
|
||||
|
||||
@ApiPropertyOptional({ enum: PublishStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(PublishStatus)
|
||||
publishStatus?: PublishStatus;
|
||||
}
|
||||
59
src/modules/dramas/entities/drama.entity.ts
Normal file
59
src/modules/dramas/entities/drama.entity.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { PublishStatus } from '../drama-status.enum';
|
||||
|
||||
@Entity('dramas')
|
||||
export class Drama {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
title: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024 })
|
||||
coverUrl: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||
portraitCoverUrl?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||
landscapeCoverUrl?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
type: string;
|
||||
|
||||
@Column({ type: 'json', nullable: true })
|
||||
tags?: string[];
|
||||
|
||||
@Column({ type: 'varchar', length: 64, nullable: true })
|
||||
region?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, nullable: true })
|
||||
language?: string;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
year?: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
|
||||
status: PublishStatus;
|
||||
|
||||
@Column({ type: 'int', default: 0 })
|
||||
sortOrder: number;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
isRecommended: boolean;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
61
src/modules/dramas/entities/episode.entity.ts
Normal file
61
src/modules/dramas/entities/episode.entity.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import { PublishStatus } from '../drama-status.enum';
|
||||
|
||||
@Entity('episodes')
|
||||
@Index(['dramaId', 'episodeNo'], { unique: true })
|
||||
export class Episode {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
dramaId: number;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
episodeNo: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
title: string;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
description?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024 })
|
||||
coverUrl: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024 })
|
||||
videoUrl: string;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
trialDurationSeconds?: number;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
durationSeconds: number;
|
||||
|
||||
@Column({ type: 'boolean', default: false })
|
||||
isPaid: boolean;
|
||||
|
||||
@Column({ type: 'int', nullable: true })
|
||||
unlockPrice?: number;
|
||||
|
||||
@Column({ type: 'datetime', nullable: true })
|
||||
publishAt?: Date;
|
||||
|
||||
@Column({ type: 'datetime', nullable: true })
|
||||
nextReleaseAt?: Date;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
|
||||
status: PublishStatus;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
51
src/modules/dramas/interfaces/drama-records.interface.ts
Normal file
51
src/modules/dramas/interfaces/drama-records.interface.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { PublishStatus } from '../drama-status.enum';
|
||||
|
||||
export interface DramaRecord {
|
||||
id: number;
|
||||
tiktokAlbumId?: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
coverId?: number;
|
||||
coverUrl: string;
|
||||
portraitCoverUrl?: string;
|
||||
landscapeCoverUrl?: string;
|
||||
type: string;
|
||||
tags: string[];
|
||||
region?: string;
|
||||
language?: string;
|
||||
year?: number;
|
||||
status: PublishStatus;
|
||||
sortOrder: number;
|
||||
isRecommended: boolean;
|
||||
onlineVersion: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface EpisodeRecord {
|
||||
id: number;
|
||||
dramaId: number;
|
||||
albumId: number;
|
||||
tiktokEpisodeId?: string;
|
||||
episodeNo: number;
|
||||
seq: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
byteplusVid?: string;
|
||||
coverId?: number;
|
||||
coverUrl: string;
|
||||
videoUrl?: string;
|
||||
trialDurationSeconds?: number;
|
||||
durationSeconds: number;
|
||||
isPaid: boolean;
|
||||
freeType: 'free' | 'paid';
|
||||
unlockPrice?: number;
|
||||
price: number;
|
||||
publishAt?: string;
|
||||
nextReleaseAt?: string;
|
||||
status: PublishStatus;
|
||||
reviewStatus: 'pending' | 'approved' | 'rejected';
|
||||
publishStatus: PublishStatus;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
11
src/modules/health/health.controller.ts
Normal file
11
src/modules/health/health.controller.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Health')
|
||||
@Controller('/api/app/v1/health')
|
||||
export class HealthController {
|
||||
@Get()
|
||||
getHealth() {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
7
src/modules/health/health.module.ts
Normal file
7
src/modules/health/health.module.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
12
src/modules/media/dto/create-cover.dto.ts
Normal file
12
src/modules/media/dto/create-cover.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, IsUrl } from 'class-validator';
|
||||
|
||||
export class CreateCoverDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
fileName: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsUrl({ require_tld: false })
|
||||
url: string;
|
||||
}
|
||||
22
src/modules/media/dto/create-upload-job.dto.ts
Normal file
22
src/modules/media/dto/create-upload-job.dto.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsObject, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateUploadJobDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
jobId: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
byteplusVid?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
status: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
rawResponse?: Record<string, unknown>;
|
||||
}
|
||||
34
src/modules/media/entities/media-upload-job.entity.ts
Normal file
34
src/modules/media/entities/media-upload-job.entity.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('media_upload_jobs')
|
||||
export class MediaUploadJob {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
jobId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
byteplusVid?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
status: string;
|
||||
|
||||
@Column({ type: 'json', nullable: true })
|
||||
rawResponse?: Record<string, unknown>;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
16
src/modules/media/interfaces/media-records.interface.ts
Normal file
16
src/modules/media/interfaces/media-records.interface.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export interface CoverRecord {
|
||||
id: number;
|
||||
fileName: string;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface MediaUploadJobRecord {
|
||||
id: number;
|
||||
jobId: string;
|
||||
byteplusVid?: string;
|
||||
status: string;
|
||||
rawResponse?: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
40
src/modules/media/media.controller.ts
Normal file
40
src/modules/media/media.controller.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
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';
|
||||
|
||||
@ApiTags('Media')
|
||||
@Controller('/api/admin/v1/media')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
export class MediaController {
|
||||
constructor(private readonly mediaService: MediaService) {}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@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,
|
||||
});
|
||||
}
|
||||
}
|
||||
12
src/modules/media/media.module.ts
Normal file
12
src/modules/media/media.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { MediaController } from './media.controller';
|
||||
import { MediaService } from './media.service';
|
||||
|
||||
@Module({
|
||||
imports: [AdminModule],
|
||||
controllers: [MediaController],
|
||||
providers: [MediaService],
|
||||
exports: [MediaService],
|
||||
})
|
||||
export class MediaModule {}
|
||||
65
src/modules/media/media.service.ts
Normal file
65
src/modules/media/media.service.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||
import { CreateCoverDto } from './dto/create-cover.dto';
|
||||
import { CreateUploadJobDto } from './dto/create-upload-job.dto';
|
||||
import {
|
||||
CoverRecord,
|
||||
MediaUploadJobRecord,
|
||||
} from './interfaces/media-records.interface';
|
||||
|
||||
interface PaginationInput {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MediaService {
|
||||
private coverSequence = 1;
|
||||
private uploadJobSequence = 1;
|
||||
private readonly covers: CoverRecord[] = [];
|
||||
private readonly uploadJobs: MediaUploadJobRecord[] = [];
|
||||
|
||||
createCover(dto: CreateCoverDto): CoverRecord {
|
||||
const cover: CoverRecord = {
|
||||
id: this.coverSequence++,
|
||||
fileName: dto.fileName,
|
||||
url: dto.url,
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
this.covers.push(cover);
|
||||
return cover;
|
||||
}
|
||||
|
||||
createUploadJob(dto: CreateUploadJobDto): MediaUploadJobRecord {
|
||||
const now = new Date().toISOString();
|
||||
const job: MediaUploadJobRecord = {
|
||||
id: this.uploadJobSequence++,
|
||||
jobId: dto.jobId,
|
||||
byteplusVid: dto.byteplusVid,
|
||||
status: dto.status,
|
||||
rawResponse: dto.rawResponse,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
this.uploadJobs.push(job);
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
9
src/modules/orders/dto/create-order.dto.ts
Normal file
9
src/modules/orders/dto/create-order.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsInt, Min } from 'class-validator';
|
||||
|
||||
export class CreateOrderDto {
|
||||
@ApiProperty()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
episodeId: number;
|
||||
}
|
||||
32
src/modules/orders/dto/tiktok-payment-webhook.dto.ts
Normal file
32
src/modules/orders/dto/tiktok-payment-webhook.dto.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsIn, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class TikTokPaymentWebhookDto {
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
orderNo?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tradeOrderId?: string;
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
tiktokOrderId?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
providerTransactionId: string;
|
||||
|
||||
@ApiProperty({ enum: ['paid', 'failed'] })
|
||||
@IsIn(['paid', 'failed'])
|
||||
status: 'paid' | 'failed';
|
||||
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
signature?: string;
|
||||
}
|
||||
49
src/modules/orders/entities/order.entity.ts
Normal file
49
src/modules/orders/entities/order.entity.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('orders')
|
||||
export class Order {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
orderNo: string;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
tradeOrderId: string;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
userId: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
albumId: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
episodeId: number;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
amount: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 32 })
|
||||
status: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
providerTransactionId?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
tiktokOrderId?: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
29
src/modules/orders/entities/user-episode-unlock.entity.ts
Normal file
29
src/modules/orders/entities/user-episode-unlock.entity.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('user_episode_unlocks')
|
||||
@Index(['userId', 'episodeId'], { unique: true })
|
||||
export class UserEpisodeUnlock {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
userId: number;
|
||||
|
||||
@Column({ type: 'bigint' })
|
||||
episodeId: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
orderNo: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32 })
|
||||
source: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
}
|
||||
25
src/modules/orders/interfaces/order-records.interface.ts
Normal file
25
src/modules/orders/interfaces/order-records.interface.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export type OrderStatus = 'pending' | 'paid' | 'failed';
|
||||
|
||||
export interface OrderRecord {
|
||||
id: number;
|
||||
orderNo: string;
|
||||
tradeOrderId: string;
|
||||
userId: number;
|
||||
albumId: number;
|
||||
episodeId: number;
|
||||
tiktokOrderId?: string;
|
||||
amount: number;
|
||||
status: OrderStatus;
|
||||
providerTransactionId?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UserEpisodeUnlockRecord {
|
||||
id: number;
|
||||
userId: number;
|
||||
episodeId: number;
|
||||
source: 'payment' | 'admin' | 'free';
|
||||
orderNo: string;
|
||||
createdAt: string;
|
||||
}
|
||||
50
src/modules/orders/orders.controller.ts
Normal file
50
src/modules/orders/orders.controller.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Body, Controller, Get, Param, 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 { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||
import { CreateOrderDto } from './dto/create-order.dto';
|
||||
import { TikTokPaymentWebhookDto } from './dto/tiktok-payment-webhook.dto';
|
||||
import { OrdersService } from './orders.service';
|
||||
|
||||
@ApiTags('Orders')
|
||||
@Controller()
|
||||
export class OrdersController {
|
||||
constructor(private readonly ordersService: OrdersService) {}
|
||||
|
||||
@Post('/api/app/v1/orders')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
createOrder(@CurrentUser() user: UserRecord, @Body() dto: CreateOrderDto) {
|
||||
return this.ordersService.createOrder(user, dto);
|
||||
}
|
||||
|
||||
@Get('/api/app/v1/episodes/:id/play')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
getPlayback(@CurrentUser() user: UserRecord, @Param('id') id: string) {
|
||||
return this.ordersService.getPlayback(user, Number(id));
|
||||
}
|
||||
|
||||
@Post('/api/webhooks/tiktok/payments')
|
||||
handlePaymentWebhook(@Body() dto: TikTokPaymentWebhookDto) {
|
||||
return this.ordersService.handlePaymentWebhook(dto);
|
||||
}
|
||||
|
||||
@Get('/api/admin/v1/unlock-records')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
@RequirePermissions('payment:read')
|
||||
listUnlockRecords(
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.ordersService.listUnlockRecords({
|
||||
page: Number(page) || 1,
|
||||
pageSize: Number(pageSize) || 20,
|
||||
});
|
||||
}
|
||||
}
|
||||
15
src/modules/orders/orders.module.ts
Normal file
15
src/modules/orders/orders.module.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { DramasModule } from '../dramas/dramas.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { OrdersController } from './orders.controller';
|
||||
import { OrdersService } from './orders.service';
|
||||
|
||||
@Module({
|
||||
imports: [AdminModule, AuthModule, DramasModule, UsersModule],
|
||||
controllers: [OrdersController],
|
||||
providers: [OrdersService],
|
||||
exports: [OrdersService],
|
||||
})
|
||||
export class OrdersModule {}
|
||||
147
src/modules/orders/orders.service.ts
Normal file
147
src/modules/orders/orders.service.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnprocessableEntityException,
|
||||
} from '@nestjs/common';
|
||||
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 {
|
||||
OrderRecord,
|
||||
UserEpisodeUnlockRecord,
|
||||
} from './interfaces/order-records.interface';
|
||||
|
||||
@Injectable()
|
||||
export class OrdersService {
|
||||
private orderSequence = 1;
|
||||
private unlockSequence = 1;
|
||||
private readonly orders: OrderRecord[] = [];
|
||||
private readonly unlocks: UserEpisodeUnlockRecord[] = [];
|
||||
|
||||
constructor(private readonly dramasService: DramasService) {}
|
||||
|
||||
createOrder(user: UserRecord, dto: CreateOrderDto): OrderRecord {
|
||||
const episode = this.dramasService.getPublishedEpisodeOrThrow(dto.episodeId);
|
||||
if (!episode.isPaid) {
|
||||
throw new UnprocessableEntityException('Episode is free');
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const order: OrderRecord = {
|
||||
id: this.orderSequence++,
|
||||
orderNo: this.createOrderNo(),
|
||||
tradeOrderId: this.createTradeOrderId(),
|
||||
userId: user.id,
|
||||
albumId: episode.albumId,
|
||||
episodeId: episode.id,
|
||||
amount: episode.price ?? episode.unlockPrice ?? 0,
|
||||
status: 'pending',
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
this.orders.push(order);
|
||||
return order;
|
||||
}
|
||||
|
||||
getPlayback(user: UserRecord, episodeId: number) {
|
||||
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||
const isUnlocked =
|
||||
!episode.isPaid ||
|
||||
this.unlocks.some(
|
||||
(unlock) => unlock.userId === user.id && unlock.episodeId === episodeId,
|
||||
);
|
||||
|
||||
return {
|
||||
episodeId: episode.id,
|
||||
dramaId: episode.dramaId,
|
||||
albumId: episode.albumId,
|
||||
isLocked: !isUnlocked,
|
||||
isPaid: episode.isPaid,
|
||||
trialDurationSeconds: episode.trialDurationSeconds,
|
||||
durationSeconds: episode.durationSeconds,
|
||||
videoUrl: isUnlocked ? episode.videoUrl : null,
|
||||
};
|
||||
}
|
||||
|
||||
handlePaymentWebhook(dto: TikTokPaymentWebhookDto) {
|
||||
const order = this.orders.find(
|
||||
(item) =>
|
||||
item.orderNo === dto.orderNo || item.tradeOrderId === dto.tradeOrderId,
|
||||
);
|
||||
if (!order) {
|
||||
throw new NotFoundException('Order not found');
|
||||
}
|
||||
|
||||
if (order.status === 'paid') {
|
||||
return {
|
||||
orderNo: order.orderNo,
|
||||
status: order.status,
|
||||
unlocked: this.isUnlocked(order.userId, order.episodeId),
|
||||
};
|
||||
}
|
||||
|
||||
order.providerTransactionId = dto.providerTransactionId;
|
||||
order.tiktokOrderId = dto.tiktokOrderId ?? order.tiktokOrderId;
|
||||
order.status = dto.status;
|
||||
order.updatedAt = new Date().toISOString();
|
||||
|
||||
if (dto.status === 'paid' && !this.isUnlocked(order.userId, order.episodeId)) {
|
||||
this.unlocks.push({
|
||||
id: this.unlockSequence++,
|
||||
userId: order.userId,
|
||||
episodeId: order.episodeId,
|
||||
source: 'payment',
|
||||
orderNo: order.orderNo,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
orderNo: order.orderNo,
|
||||
tradeOrderId: order.tradeOrderId,
|
||||
status: order.status,
|
||||
unlocked: this.isUnlocked(order.userId, order.episodeId),
|
||||
};
|
||||
}
|
||||
|
||||
hasEpisodePermission(userId: number, episodeId: number) {
|
||||
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||
return !episode.isPaid || this.isUnlocked(userId, episodeId);
|
||||
}
|
||||
|
||||
listUnlockRecords(input: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}): 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();
|
||||
|
||||
return {
|
||||
list: records.slice(start, start + pageSize),
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: records.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private isUnlocked(userId: number, episodeId: number) {
|
||||
return this.unlocks.some(
|
||||
(unlock) => unlock.userId === userId && unlock.episodeId === episodeId,
|
||||
);
|
||||
}
|
||||
|
||||
private createOrderNo() {
|
||||
return `ORD${Date.now()}${String(this.orderSequence).padStart(6, '0')}`;
|
||||
}
|
||||
|
||||
private createTradeOrderId() {
|
||||
return `TRADE${Date.now()}${String(this.orderSequence).padStart(6, '0')}`;
|
||||
}
|
||||
}
|
||||
19
src/modules/player/player.controller.ts
Normal file
19
src/modules/player/player.controller.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||
import { PlayerService } from './player.service';
|
||||
|
||||
@ApiTags('Player')
|
||||
@Controller('/api/app/v1/player')
|
||||
export class PlayerController {
|
||||
constructor(private readonly playerService: PlayerService) {}
|
||||
|
||||
@Get('/episodes/:id')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
getEpisodePlayer(@CurrentUser() user: UserRecord, @Param('id') id: string) {
|
||||
return this.playerService.getEpisodePlayer(user, Number(id));
|
||||
}
|
||||
}
|
||||
14
src/modules/player/player.module.ts
Normal file
14
src/modules/player/player.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
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 { PlayerService } from './player.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, DramasModule, OrdersModule, UsersModule],
|
||||
controllers: [PlayerController],
|
||||
providers: [PlayerService],
|
||||
})
|
||||
export class PlayerModule {}
|
||||
30
src/modules/player/player.service.ts
Normal file
30
src/modules/player/player.service.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DramasService } from '../dramas/dramas.service';
|
||||
import { OrdersService } from '../orders/orders.service';
|
||||
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||
|
||||
@Injectable()
|
||||
export class PlayerService {
|
||||
constructor(
|
||||
private readonly dramasService: DramasService,
|
||||
private readonly ordersService: OrdersService,
|
||||
) {}
|
||||
|
||||
getEpisodePlayer(user: UserRecord, episodeId: number) {
|
||||
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||
const hasPermission = this.ordersService.hasEpisodePermission(
|
||||
user.id,
|
||||
episode.id,
|
||||
);
|
||||
|
||||
return {
|
||||
albumId: episode.albumId,
|
||||
episodeId: episode.id,
|
||||
vid: episode.byteplusVid,
|
||||
hasPermission,
|
||||
playAuthToken: hasPermission
|
||||
? `play_auth_${episode.byteplusVid ?? episode.id}_${user.id}`
|
||||
: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
8
src/modules/users/dto/update-user-status.dto.ts
Normal file
8
src/modules/users/dto/update-user-status.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsIn } from 'class-validator';
|
||||
|
||||
export class UpdateUserStatusDto {
|
||||
@ApiProperty({ enum: ['active', 'disabled'] })
|
||||
@IsIn(['active', 'disabled'])
|
||||
status: 'active' | 'disabled';
|
||||
}
|
||||
37
src/modules/users/entities/user.entity.ts
Normal file
37
src/modules/users/entities/user.entity.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('users')
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Index({ unique: true })
|
||||
@Column({ type: 'varchar', length: 128 })
|
||||
tiktokOpenId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
tiktokUnionId?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||
nickname?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||
avatarUrl?: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 32, default: 'active' })
|
||||
status: string;
|
||||
|
||||
@CreateDateColumn()
|
||||
createdAt: Date;
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
}
|
||||
10
src/modules/users/interfaces/user-record.interface.ts
Normal file
10
src/modules/users/interfaces/user-record.interface.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export interface UserRecord {
|
||||
id: number;
|
||||
tiktokOpenId: string;
|
||||
tiktokUnionId?: string;
|
||||
nickname?: string;
|
||||
avatarUrl?: string;
|
||||
status: 'active' | 'disabled';
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
36
src/modules/users/users.controller.ts
Normal file
36
src/modules/users/users.controller.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Body, Controller, Get, Param, Patch, 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 { UpdateUserStatusDto } from './dto/update-user-status.dto';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@ApiTags('Users')
|
||||
@Controller('/api/admin/v1/users')
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||
export class UsersController {
|
||||
constructor(private readonly usersService: UsersService) {}
|
||||
|
||||
@Get()
|
||||
@RequirePermissions('user:read')
|
||||
listUsers(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||
return this.usersService.listUsers({
|
||||
page: Number(page) || 1,
|
||||
pageSize: Number(pageSize) || 20,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('/:id')
|
||||
@RequirePermissions('user:read')
|
||||
getUser(@Param('id') id: string) {
|
||||
return this.usersService.getUserOrThrow(Number(id));
|
||||
}
|
||||
|
||||
@Patch('/:id/status')
|
||||
@RequirePermissions('user:update')
|
||||
updateStatus(@Param('id') id: string, @Body() dto: UpdateUserStatusDto) {
|
||||
return this.usersService.updateStatus(Number(id), dto.status);
|
||||
}
|
||||
}
|
||||
12
src/modules/users/users.module.ts
Normal file
12
src/modules/users/users.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
@Module({
|
||||
imports: [AdminModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
92
src/modules/users/users.service.ts
Normal file
92
src/modules/users/users.service.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||
import { UserRecord } from './interfaces/user-record.interface';
|
||||
|
||||
interface UpsertTikTokUserInput {
|
||||
tiktokOpenId: string;
|
||||
tiktokUnionId?: string;
|
||||
nickname?: string;
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
interface PaginationInput {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
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();
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
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 user;
|
||||
}
|
||||
|
||||
updateStatus(id: number, status: 'active' | 'disabled') {
|
||||
const user = this.getUserOrThrow(id);
|
||||
user.status = status;
|
||||
user.updatedAt = new Date().toISOString();
|
||||
return user;
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user