Spaces:
Running
Running
Download server/admin.ts from kishankrish19/nexus-tts-engine: direct link, hf CLI and curl.
- Browser
- Download file 40 kB
-
https://huggingface.co/spaces/kishankrish19/nexus-tts-engine/resolve/main/server/admin.ts
- Command line
-
hf download hf://spaces/kishankrish19/nexus-tts-engine/server/admin.ts
-
curl -L -o admin.ts https://huggingface.co/spaces/kishankrish19/nexus-tts-engine/resolve/main/server/admin.ts
40 kB
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Req,
Res,
UseGuards,
BadRequestException,
ConflictException,
NotFoundException,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import type { Response } from 'express';
import { createReadStream } from 'node:fs';
import { spawn } from 'node:child_process';
import type { Writable } from 'node:stream';
import { FileInterceptor } from '@nestjs/platform-express';
import { z } from 'zod';
import { unlink, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { db, parse, seal, unseal, token, hash, audit, origin, dataDir, decrypt, type MediaManifest, type AuthRequest } from './core';
import { AdminGuard } from './auth';
import { hf } from './storage';
import { addToTrash, removeFromTrash, getTrash, getTrashItem, clearTrash } from './recycle-bin';
import { getBrandingInfo, updateBranding } from './branding';
import { clearSourceBackup } from './upload-integrity';
import { ciphertext } from './playback';
const artwork = z
.string()
.max(2000)
.refine(
(v) => v.startsWith('/art/') || v.startsWith('/api/artwork/') || /^https:\/\//.test(v),
'Use an uploaded image or HTTPS image URL',
);
const titleSchema = z.object({
name: z.string().trim().min(1).max(150),
synopsis: z.string().max(4000),
format: z.enum(['MOVIE', 'SERIES']),
category: z.enum(['ANIME', 'CARTOON', 'LIVE_ACTION']),
genres: z.array(z.string().max(40)).max(12),
languages: z.array(z.string().max(40)).max(12),
year: z.number().int().min(1900).max(2100),
ageRating: z.string().max(12),
poster: artwork,
backdrop: artwork,
featured: z.boolean(),
rightsNote: z.string().max(2000).default(''),
availableUntil: z.string().datetime().nullable().optional(),
});
@Controller('admin')
@UseGuards(AdminGuard)
export class AdminController {
@Get('overview') async overview() {
const [members, titles, orders, uploads, audits] = await Promise.all([
db.user.count(),
db.title.count(),
db.order.aggregate({ where: { status: 'PAID' }, _sum: { amount: true }, _count: true }),
db.upload.findMany({
take: 12,
orderBy: { createdAt: 'desc' },
include: { episode: { include: { title: { select: { name: true } } } } },
}),
db.audit.findMany({ take: 20, orderBy: { createdAt: 'desc' } }),
]);
return {
members,
titles,
revenue: orders._sum.amount || 0,
purchases: orders._count,
uploads,
audits,
};
}
@Get('titles') titles() {
return db.title.findMany({
where: { NOT: { status: { startsWith: 'TRASHED' } } },
include: {
products: { where: { active: true } },
episodes: {
where: { NOT: { name: { startsWith: '[TRASHED]' } } },
orderBy: [{ season: 'asc' }, { number: 'asc' }],
include: {
asset: { select: { id: true, bytes: true, storageId: true } },
uploads: { orderBy: { createdAt: 'desc' }, take: 1 },
},
},
},
orderBy: { createdAt: 'desc' },
});
}
@Post('titles') async create(@Body() body: unknown, @Req() req: AuthRequest) {
const input = parse(titleSchema, body);
const slug =
input.name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '') +
'-' +
token().slice(0, 6);
const title = await db.title.create({
data: {
...input,
slug,
products: { create: { mode: 'FREE' } },
...(input.format === 'MOVIE' ? { episodes: { create: { name: input.name } } } : {}),
},
});
await audit(req.user.id, 'TITLE_CREATED', title.id);
return title;
}
@Post('titles/:id') async edit(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(titleSchema, body);
const result = await db.$transaction(async (tx) => {
// Serialize format changes with episode creation; uploaded media keeps its episode ID.
const current = await tx.title.update({ where: { id }, data: { updatedAt: new Date() } });
if (input.format !== current.format) {
if (current.status === 'PUBLISHED')
throw new ConflictException('Unpublish this title before changing its format.');
const episodes = await tx.episode.findMany({ where: { titleId: id } });
if (input.format === 'MOVIE') {
if (episodes.length > 1)
throw new BadRequestException(
'A movie can contain only one video entry. This series has multiple episodes; they cannot be combined or removed automatically.',
);
if (episodes.length === 1)
await tx.episode.update({
where: { id: episodes[0].id },
data: { season: 1, number: 1 },
});
else await tx.episode.create({ data: { titleId: id, name: input.name } });
}
}
return tx.title.update({ where: { id }, data: input });
});
await audit(req.user.id, 'TITLE_UPDATED', id);
return result;
}
@Post('titles/:id/publish') async publish(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const { published } = parse(z.object({ published: z.boolean() }), body);
const title = await db.title.findUniqueOrThrow({
where: { id },
include: {
episodes: {
include: {
asset: true,
uploads: { where: { state: { notIn: ['READY', 'FAILED', 'CANCELLED'] } } },
},
},
},
});
if (published) {
if (!title.episodes.length)
throw new BadRequestException(
'Add a video entry and finish uploading before publishing. If this is a movie, select Movie in Edit details.',
);
const unfinished = title.episodes.filter(
(episode) => !episode.asset || episode.uploads.length > 0,
);
if (unfinished.length)
throw new BadRequestException(
`Finish processing before publishing: ${unfinished
.slice(0, 5)
.map((episode) => episode.name)
.join(
', ',
)}${unfinished.length > 5 ? '…' : ''}. You can correct Movie / Series in Edit details.`,
);
}
await db.title.update({
where: { id },
data: { status: published ? 'PUBLISHED' : 'DRAFT', showcase: false },
});
await audit(req.user.id, published ? 'TITLE_PUBLISHED' : 'TITLE_UNPUBLISHED', id);
if (published) {
// Free staging and temp backup disk space after successful publication
for (const episode of title.episodes) {
const uploads = await db.upload.findMany({ where: { episodeId: episode.id } });
for (const u of uploads) {
await clearSourceBackup(u.id).catch(() => {});
await unlink(join(dataDir, 'uploads', u.id)).catch(() => {});
}
}
}
return { ok: true };
}
@Post('titles/:id/pricing') async pricing(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(
z.object({
mode: z.enum(['FREE', 'PURCHASE', 'RENTAL']),
pricePaise: z.number().int().min(0).max(10000000),
rentalHours: z.number().int().min(1).max(8760),
}),
body,
);
if (input.mode !== 'FREE' && input.pricePaise < 100)
throw new BadRequestException('Paid access must cost at least ₹1.');
const product = await db.$transaction(async (tx) => {
await tx.title.update({ where: { id }, data: { updatedAt: new Date() } });
await tx.product.updateMany({
where: { titleId: id, active: true },
data: { active: false },
});
return tx.product.create({
data: { titleId: id, ...input, pricePaise: input.mode === 'FREE' ? 0 : input.pricePaise },
});
});
await audit(req.user.id, 'PRICING_UPDATED', id);
return product;
}
@Post('titles/:id/episodes') async episode(@Param('id') titleId: string, @Body() body: unknown) {
const input = parse(
z.object({
name: z.string().min(1).max(200),
season: z.number().int().min(1).max(1000),
number: z.number().int().min(1).max(10000),
introStart: z.number().min(0).default(0),
introEnd: z.number().min(0).default(0),
outroStart: z.number().min(0).default(0),
outroEnd: z.number().min(0).default(0),
}),
body,
);
if ((input.introEnd ?? 0) < (input.introStart ?? 0))
throw new BadRequestException('Intro end must be after its start.');
if ((input.outroEnd ?? 0) < (input.outroStart ?? 0))
throw new BadRequestException('Outro end must be after its start.');
return db.$transaction(async (tx) => {
const title = await tx.title.update({
where: { id: titleId },
data: { updatedAt: new Date() },
});
if (title.format === 'MOVIE')
throw new BadRequestException('Movies already have one video entry.');
if (title.status === 'PUBLISHED')
throw new ConflictException(
'Unpublish before adding episodes, then publish when media is ready.',
);
return tx.episode.create({ data: { titleId, ...input } });
});
}
@Get('storage') storage() {
return db.storage.findMany({
where: { health: { not: 'TRASHED' } },
select: {
id: true,
name: true,
bucket: true,
enabled: true,
health: true,
_count: { select: { assets: true } },
},
orderBy: { createdAt: 'asc' },
});
}
@Post('titles/:id/sequence') async sequence(@Param('id') id: string, @Body() body: unknown) {
const input = parse(
z.object({
reorder: z.boolean().default(false),
season: z.number().int().min(1),
episodes: z
.array(z.object({ id: z.string(), name: z.string().trim().min(1).max(200) }))
.min(1)
.max(10000),
}),
body,
);
if (new Set(input.episodes.map((e) => e.id)).size !== input.episodes.length)
throw new BadRequestException('Each episode must appear once.');
return db.$transaction(
async (tx) => {
const title = await tx.title.update({ where: { id }, data: { updatedAt: new Date() } });
if (title.format !== 'SERIES')
throw new BadRequestException('Sequence editing is for series.');
const rows = await tx.episode.findMany({ where: { titleId: id, season: input.season } });
if (
rows.length !== input.episodes.length ||
rows.some((e) => !input.episodes.some((selected) => selected.id === e.id))
)
throw new BadRequestException('The season changed. Reopen the sequence editor.');
// Move outside the existing number range before assigning final positions,
// so swaps cannot violate the unique season/episode constraint.
const offset = Math.max(0, ...rows.map((e) => e.number)) + rows.length + 1;
for (let i = 0; input.reorder && i < input.episodes.length; i++)
await tx.episode.update({
where: { id: input.episodes[i].id },
data: { number: offset + i },
});
for (let i = 0; i < input.episodes.length; i++)
await tx.episode.update({
where: { id: input.episodes[i].id },
data: { ...(input.reorder ? { number: i + 1 } : {}), name: input.episodes[i].name },
});
return { ok: true };
},
{ timeout: 60000 },
);
}
@Post('episodes/:id') async editEpisode(@Param('id') id: string, @Body() body: unknown) {
const input = parse(
z.object({
name: z.string().min(1).max(200),
season: z.number().int().min(1),
number: z.number().int().min(1),
introStart: z.number().min(0),
introEnd: z.number().min(0),
outroStart: z.number().min(0).default(0),
outroEnd: z.number().min(0).default(0),
}),
body,
);
if (input.introEnd < input.introStart)
throw new BadRequestException('Intro end must be after its start.');
if ((input.outroEnd ?? 0) < (input.outroStart ?? 0))
throw new BadRequestException('Outro end must be after its start.');
const episode = await db.episode.findUniqueOrThrow({ where: { id }, include: { title: true } });
if (episode.title.format === 'MOVIE' && (input.season !== 1 || input.number !== 1))
throw new BadRequestException('Movie file must remain entry 1.');
if (episode.duration > 0 && input.introEnd > episode.duration)
throw new BadRequestException('Intro cannot extend beyond the video.');
if (episode.duration > 0 && (input.outroEnd ?? 0) > episode.duration)
throw new BadRequestException('Outro cannot extend beyond the video.');
return db.episode.update({ where: { id }, data: input });
}
@Post('storage') async addStorage(@Body() body: unknown, @Req() req: AuthRequest) {
const input = parse(
z.object({
name: z.string().min(1).max(100),
bucket: z.string().regex(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/),
token: z.string().min(10).max(500),
createBucket: z.boolean().default(false),
private: z.boolean().default(false),
}),
body,
);
if (await db.storage.findFirst({ where: { bucket: input.bucket } }))
throw new ConflictException('This bucket is already connected.');
if (input.createBucket)
await hf({ op: 'create', bucket: input.bucket, token: input.token, private: input.private });
await hf({ op: 'check', bucket: input.bucket, token: input.token });
const result = await db.storage.create({
data: {
name: input.name,
bucket: input.bucket,
tokenEncrypted: seal(input.token),
health: 'CONNECTED',
},
});
await audit(req.user.id, 'STORAGE_ADDED', result.id);
return { id: result.id };
}
@Post('storage/discover') async discover(@Body() body: unknown) {
const input = parse(
z.object({
token: z.string().min(10).max(500),
namespace: z
.string()
.regex(/^[a-zA-Z0-9_-]+$/)
.optional(),
}),
body,
);
return hf({ op: 'discover', ...input });
}
@Post('storage/:id/buckets') async createBucket(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(
z.object({
name: z.string().min(1).max(100),
bucketName: z.string().regex(/^[a-zA-Z0-9_-]{1,96}$/),
private: z.boolean(),
}),
body,
);
const existing = await db.storage.findUniqueOrThrow({ where: { id } });
const bucket = `${existing.bucket.split('/')[0]}/${input.bucketName}`;
if (await db.storage.findFirst({ where: { bucket } }))
throw new ConflictException('This bucket is already connected.');
await hf({
op: 'create',
bucket,
token: unseal(existing.tokenEncrypted),
private: input.private,
});
const result = await db.storage.create({
data: {
name: input.name,
bucket,
tokenEncrypted: existing.tokenEncrypted,
health: 'CONNECTED',
},
});
await audit(req.user.id, 'BUCKET_CREATED', result.id);
return { id: result.id };
}
@Post('storage/:id/visibility') async visibility(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const { private: isPrivate } = parse(z.object({ private: z.boolean() }), body);
const storage = await db.storage.findUniqueOrThrow({ where: { id } });
await hf({
op: 'visibility',
bucket: storage.bucket,
token: unseal(storage.tokenEncrypted),
private: isPrivate,
});
await audit(req.user.id, 'BUCKET_VISIBILITY_CHANGED', id);
return { ok: true };
}
@Post('storage/:id') async editStorage(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(
z.object({ enabled: z.boolean().optional(), token: z.string().min(10).max(500).optional() }),
body,
);
const storage = await db.storage.findUniqueOrThrow({ where: { id } });
if (input.token) await hf({ op: 'check', bucket: storage.bucket, token: input.token });
await db.storage.update({
where: { id },
data: {
enabled: input.enabled,
...(input.token ? { tokenEncrypted: seal(input.token), health: 'CONNECTED' } : {}),
},
});
await audit(req.user.id, 'STORAGE_UPDATED', id);
return { ok: true };
}
@Post('storage/:id/check') async checkStorage(@Param('id') id: string) {
const storage = await db.storage.findUniqueOrThrow({ where: { id } });
try {
await hf({ op: 'check', bucket: storage.bucket, token: unseal(storage.tokenEncrypted) });
await db.storage.update({ where: { id }, data: { health: 'CONNECTED' } });
return { ok: true };
} catch {
await db.storage.update({ where: { id }, data: { health: 'ERROR' } });
throw new BadRequestException('Unable to read bucket. Check its name and token permissions.');
}
}
@Get('members') members() {
return db.user.findMany({
where: { NOT: { role: { startsWith: 'TRASHED' } } },
select: { id: true, name: true, email: true, role: true, disabled: true, createdAt: true },
orderBy: { createdAt: 'desc' },
});
}
@Post('members/:id') async member(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const { disabled } = parse(z.object({ disabled: z.boolean() }), body);
const target = await db.user.findUniqueOrThrow({ where: { id } });
if (target.role === 'ADMIN')
throw new BadRequestException('Admin accounts cannot be disabled here.');
await db.$transaction([
db.user.update({ where: { id }, data: { disabled } }),
db.session.deleteMany({ where: { userId: id } }),
db.playback.deleteMany({ where: { userId: id } }),
]);
await audit(req.user.id, disabled ? 'MEMBER_DISABLED' : 'MEMBER_ENABLED', id);
return { ok: true };
}
@Post('invites') async invite(@Body() body: unknown, @Req() req: AuthRequest) {
const { email } = parse(z.object({ email: z.string().email().optional() }), body);
const raw = token();
await db.invite.create({
data: {
tokenHash: hash(raw),
email: email?.toLowerCase(),
expiresAt: new Date(Date.now() + 7 * 86400000),
},
});
await audit(req.user.id, 'INVITE_CREATED', email || 'Any email');
return { url: `${origin}/login?invite=${raw}` };
}
@Get('invites') invites() {
return db.invite.findMany({
orderBy: { createdAt: 'desc' },
take: 100,
});
}
@Get('collections') collections() {
return db.collection.findMany({
where: { position: { gte: 0 } },
include: { items: { orderBy: { position: 'asc' } } },
orderBy: { position: 'asc' },
});
}
@Post('collections') async collection(@Body() body: unknown) {
const input = parse(
z.object({
id: z.string().optional(),
name: z.string().min(1).max(100),
position: z.number().int().min(0),
enabled: z.boolean(),
titleIds: z.array(z.string()).max(50),
}),
body,
);
if (new Set(input.titleIds).size !== input.titleIds.length)
throw new BadRequestException('A title can only appear once per collection.');
return db.$transaction(async (tx) => {
const collection = input.id
? await tx.collection.update({
where: { id: input.id },
data: { name: input.name, position: input.position, enabled: input.enabled },
})
: await tx.collection.create({
data: { name: input.name, position: input.position, enabled: input.enabled },
});
await tx.collectionItem.deleteMany({ where: { collectionId: collection.id } });
await tx.collectionItem.createMany({
data: input.titleIds.map((titleId, position) => ({
titleId,
position,
collectionId: collection.id,
})),
});
return collection;
});
}
@Post('collections/:id/delete')
@Delete('collections/:id')
async deleteCollection(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(z.object({ permanent: z.boolean().optional() }).optional(), body || {});
const isPermanent = !!input?.permanent;
const collection = await db.collection.findUniqueOrThrow({ where: { id } });
if (isPermanent) {
await db.collection.delete({ where: { id } });
await removeFromTrash(id);
await audit(req.user.id, 'COLLECTION_PERMANENTLY_DELETED', id);
return { ok: true, permanent: true };
} else {
await db.collection.update({
where: { id },
data: { enabled: false, position: -999 },
});
await addToTrash({
id,
type: 'collection',
name: collection.name,
deletedAt: new Date().toISOString(),
details: `Position: ${collection.position}`,
originalState: { position: collection.position, enabled: collection.enabled },
});
await audit(req.user.id, 'COLLECTION_TRASHED', id);
return { ok: true, permanent: false };
}
}
@Post('titles/:id/delete')
@Delete('titles/:id')
async deleteTitle(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(z.object({ permanent: z.boolean().optional() }).optional(), body || {});
const isPermanent = !!input?.permanent;
const title = await db.title.findUniqueOrThrow({
where: { id },
include: { episodes: { include: { uploads: true } }, products: true },
});
if (isPermanent) {
await db.$transaction(async (tx) => {
const productIds = title.products.map((p) => p.id);
if (productIds.length) {
await tx.entitlement.deleteMany({ where: { productId: { in: productIds } } });
await tx.order.deleteMany({ where: { productId: { in: productIds } } });
}
await tx.title.delete({ where: { id } });
});
for (const episode of title.episodes) {
for (const u of episode.uploads) {
await unlink(join(dataDir, 'uploads', u.id)).catch(() => {});
await rm(join(dataDir, 'processing', u.id), { recursive: true, force: true }).catch(() => {});
}
}
await removeFromTrash(id);
await audit(req.user.id, 'TITLE_PERMANENTLY_DELETED', id);
return { ok: true, permanent: true };
} else {
const prevStatus = title.status.startsWith('TRASHED:') ? title.status.replace('TRASHED:', '') : title.status;
await db.title.update({
where: { id },
data: { status: `TRASHED:${prevStatus}` },
});
await addToTrash({
id,
type: 'title',
name: title.name,
deletedAt: new Date().toISOString(),
details: `${title.format === 'SERIES' ? `${title.episodes.length} episodes` : 'Movie'} · ${title.category}`,
originalState: { status: prevStatus },
});
await audit(req.user.id, 'TITLE_TRASHED', id);
return { ok: true, permanent: false };
}
}
@Post('episodes/:id/delete')
@Delete('episodes/:id')
async deleteEpisode(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(z.object({ permanent: z.boolean().optional() }).optional(), body || {});
const isPermanent = !!input?.permanent;
const episode = await db.episode.findUniqueOrThrow({
where: { id },
include: { title: true, uploads: true },
});
if (episode.title.format === 'MOVIE') {
throw new BadRequestException('Movie entry cannot be deleted separately. Delete the Movie title instead.');
}
if (isPermanent) {
await db.episode.delete({ where: { id } });
for (const u of episode.uploads) {
await unlink(join(dataDir, 'uploads', u.id)).catch(() => {});
await rm(join(dataDir, 'processing', u.id), { recursive: true, force: true }).catch(() => {});
}
await removeFromTrash(id);
await audit(req.user.id, 'EPISODE_PERMANENTLY_DELETED', id);
return { ok: true, permanent: true };
} else {
const origName = episode.name.startsWith('[TRASHED] ') ? episode.name.replace('[TRASHED] ', '') : episode.name;
await db.episode.update({
where: { id },
data: { name: `[TRASHED] ${origName}` },
});
await addToTrash({
id,
type: 'episode',
name: `${episode.title.name}: S${episode.season}E${episode.number} - ${origName}`,
deletedAt: new Date().toISOString(),
details: `Title: ${episode.title.name} (Season ${episode.season}, Episode ${episode.number})`,
originalState: { name: origName, titleId: episode.titleId },
});
await audit(req.user.id, 'EPISODE_TRASHED', id);
return { ok: true, permanent: false };
}
}
@Post('episodes/:id/asset/delete')
@Delete('episodes/:id/asset')
async deleteEpisodeAsset(@Param('id') id: string, @Req() req: AuthRequest) {
const asset = await db.asset.findUnique({ where: { episodeId: id } });
if (!asset) throw new BadRequestException('This episode has no media asset.');
await db.asset.delete({ where: { id: asset.id } });
await db.episode.update({ where: { id }, data: { duration: 0 } });
await audit(req.user.id, 'EPISODE_ASSET_DELETED', id);
return { ok: true };
}
@Get('episodes/:id/download')
async downloadEpisode(
@Param('id') id: string,
@Res() res: Response,
@Req() req: AuthRequest,
) {
const episode = await db.episode.findUniqueOrThrow({
where: { id },
include: {
title: true,
asset: { include: { storage: true } },
uploads: { orderBy: { createdAt: 'desc' } },
},
});
const safeFilename = `${episode.title.name} - ${episode.name}`.replace(/[/\\?%*:|"<>]/g, '_');
// 1. Check if unencrypted original source file exists on local staging or temp-backup
for (const u of episode.uploads) {
const candidates = [
join(dataDir, 'uploads', u.id),
join(dataDir, 'temp-backup', u.id, 'source.mkv'),
];
for (const candidate of candidates) {
try {
const s = await stat(candidate);
if (s.size > 0) {
const ext = u.filename?.includes('.') ? '.' + u.filename.split('.').pop() : '.mkv';
res.setHeader(
'Content-Disposition',
`attachment; filename="${encodeURIComponent(safeFilename + ext)}"`,
);
res.setHeader('Content-Length', String(s.size));
res.setHeader('Content-Type', 'video/x-matroska');
return createReadStream(candidate).pipe(res);
}
} catch {}
}
}
// 2. If original source on disk was cleared, stream remuxed MP4 (with both video and audio)
if (!episode.asset) {
throw new NotFoundException('No downloadable media asset found for this episode.');
}
const asset = episode.asset;
const manifest = asset.manifest as unknown as MediaManifest;
const playlistKeys = Object.keys(manifest.playlists || {}).filter(
(k) => k.startsWith('v') && k.endsWith('.m3u8'),
);
playlistKeys.sort((a, b) => {
const hA = parseInt(a.replace(/[^\d]/g, ''), 10) || 0;
const hB = parseInt(b.replace(/[^\d]/g, ''), 10) || 0;
return hB - hA;
});
const chosenVideo = playlistKeys[0];
if (!chosenVideo || !manifest.playlists[chosenVideo]) {
throw new NotFoundException('No video playlist found in asset.');
}
const audioKeys = Object.keys(manifest.playlists || {}).filter(
(k) => k.startsWith('audio') && k.endsWith('.m3u8'),
);
audioKeys.sort();
const chosenAudio = audioKeys[0];
const videoSegments = manifest.playlists[chosenVideo]
.split(/\r?\n/)
.filter((line) => line && !line.startsWith('#'));
const audioSegments = chosenAudio
? manifest.playlists[chosenAudio]
.split(/\r?\n/)
.filter((line) => line && !line.startsWith('#'))
: [];
if (!videoSegments.length) {
throw new NotFoundException('No video segments found in playlist.');
}
res.setHeader(
'Content-Disposition',
`attachment; filename="${encodeURIComponent(safeFilename + '.mp4')}"`,
);
res.setHeader('Content-Type', 'video/mp4');
const key = Buffer.from(unseal(asset.keyEncrypted), 'hex');
if (!chosenAudio || !audioSegments.length) {
const ffmpeg = spawn(
process.env.FFMPEG_BIN || 'ffmpeg',
[
'-y',
'-i', 'pipe:0',
'-c', 'copy',
'-f', 'mp4',
'-movflags', 'frag_keyframe+empty_moov+default_base_moof',
'pipe:1',
],
{ stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
);
ffmpeg.stdout?.pipe(res);
res.on('close', () => ffmpeg.kill());
for (const seg of videoSegments) {
if (res.writableEnded || res.destroyed) break;
const fileInfo = manifest.files[seg];
if (!fileInfo) continue;
const bytes = await ciphertext(fileInfo.object, asset.storage);
const plain = decrypt(bytes, key, fileInfo.object);
if (!ffmpeg.stdin.write(plain)) {
await new Promise((r) => ffmpeg.stdin.once('drain', r));
}
}
ffmpeg.stdin.end();
return;
}
const ffmpeg = spawn(
process.env.FFMPEG_BIN || 'ffmpeg',
[
'-y',
'-i', 'pipe:3',
'-i', 'pipe:4',
'-c:v', 'copy',
'-c:a', 'aac',
'-ac', '2',
'-b:a', '192k',
'-f', 'mp4',
'-movflags', 'frag_keyframe+empty_moov+default_base_moof',
'pipe:1',
],
{
stdio: ['ignore', 'pipe', 'ignore', 'pipe', 'pipe'],
windowsHide: true,
},
);
ffmpeg.stdout?.pipe(res);
res.on('close', () => ffmpeg.kill());
const videoPipe = ffmpeg.stdio[3] as Writable;
const audioPipe = ffmpeg.stdio[4] as Writable;
const streamVideo = async () => {
for (const seg of videoSegments) {
if (res.writableEnded || res.destroyed) break;
const fileInfo = manifest.files[seg];
if (!fileInfo) continue;
const bytes = await ciphertext(fileInfo.object, asset.storage);
const plain = decrypt(bytes, key, fileInfo.object);
if (!videoPipe.write(plain)) {
await new Promise((r) => videoPipe.once('drain', r));
}
}
videoPipe.end();
};
const streamAudio = async () => {
for (const seg of audioSegments) {
if (res.writableEnded || res.destroyed) break;
const fileInfo = manifest.files[seg];
if (!fileInfo) continue;
const bytes = await ciphertext(fileInfo.object, asset.storage);
const plain = decrypt(bytes, key, fileInfo.object);
if (!audioPipe.write(plain)) {
await new Promise((r) => audioPipe.once('drain', r));
}
}
audioPipe.end();
};
await Promise.all([streamVideo(), streamAudio()]);
}
@Post('storage/:id/delete')
@Delete('storage/:id')
async deleteStorage(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(z.object({ permanent: z.boolean().optional() }).optional(), body || {});
const isPermanent = !!input?.permanent;
const storage = await db.storage.findUniqueOrThrow({
where: { id },
include: { _count: { select: { assets: true } } },
});
if (isPermanent) {
if (storage._count.assets > 0) {
throw new ConflictException(
`Cannot delete storage connection with ${storage._count.assets} active primary media assets. Replicate or migrate them before deleting.`,
);
}
await db.$transaction(async (tx) => {
await tx.assetReplica.deleteMany({ where: { storageId: id } });
await tx.transfer.deleteMany({ where: { storageId: id } });
await tx.upload.deleteMany({ where: { storageId: id } });
await tx.storage.delete({ where: { id } });
});
await removeFromTrash(id);
await audit(req.user.id, 'STORAGE_PERMANENTLY_DELETED', id);
return { ok: true, permanent: true };
} else {
await db.storage.update({
where: { id },
data: { enabled: false, health: 'TRASHED' },
});
await addToTrash({
id,
type: 'storage',
name: storage.name,
deletedAt: new Date().toISOString(),
details: `Bucket: ${storage.bucket}`,
originalState: { health: storage.health, enabled: storage.enabled },
});
await audit(req.user.id, 'STORAGE_TRASHED', id);
return { ok: true, permanent: false };
}
}
@Post('members/:id/delete')
@Delete('members/:id')
async deleteMember(
@Param('id') id: string,
@Body() body: unknown,
@Req() req: AuthRequest,
) {
const input = parse(z.object({ permanent: z.boolean().optional() }).optional(), body || {});
const isPermanent = !!input?.permanent;
const target = await db.user.findUniqueOrThrow({ where: { id } });
if (target.role === 'ADMIN') {
throw new BadRequestException('Admin accounts cannot be deleted.');
}
if (isPermanent) {
await db.$transaction(async (tx) => {
await tx.session.deleteMany({ where: { userId: id } });
await tx.playback.deleteMany({ where: { userId: id } });
await tx.progress.deleteMany({ where: { userId: id } });
await tx.saved.deleteMany({ where: { userId: id } });
await tx.entitlement.deleteMany({ where: { userId: id } });
await tx.order.deleteMany({ where: { userId: id } });
await tx.user.delete({ where: { id } });
});
await removeFromTrash(id);
await audit(req.user.id, 'MEMBER_PERMANENTLY_DELETED', id);
return { ok: true, permanent: true };
} else {
await db.$transaction([
db.user.update({ where: { id }, data: { disabled: true, role: 'TRASHED:MEMBER' } }),
db.session.deleteMany({ where: { userId: id } }),
db.playback.deleteMany({ where: { userId: id } }),
]);
await addToTrash({
id,
type: 'member',
name: target.name,
deletedAt: new Date().toISOString(),
details: `Email: ${target.email}`,
originalState: { role: 'MEMBER' },
});
await audit(req.user.id, 'MEMBER_TRASHED', id);
return { ok: true, permanent: false };
}
}
@Post('invites/:id/delete')
@Delete('invites/:id')
async deleteInvite(@Param('id') id: string, @Req() req: AuthRequest) {
await db.invite.delete({ where: { id } });
await audit(req.user.id, 'INVITE_DELETED', id);
return { ok: true };
}
@Get('recycle-bin')
async recycleBin() {
return getTrash();
}
@Post('recycle-bin/:id/restore')
async restoreFromTrash(@Param('id') id: string, @Req() req: AuthRequest) {
const item = await getTrashItem(id);
if (!item) throw new BadRequestException('Item not found in recycle bin.');
if (item.type === 'title') {
const origStatus = (item.originalState?.status as string) || 'DRAFT';
await db.title.update({
where: { id },
data: { status: origStatus },
});
} else if (item.type === 'episode') {
const origName = (item.originalState?.name as string) || item.name;
await db.episode.update({
where: { id },
data: { name: origName },
});
} else if (item.type === 'storage') {
const origHealth = (item.originalState?.health as string) || 'CONNECTED';
const origEnabled = item.originalState?.enabled !== false;
await db.storage.update({
where: { id },
data: { health: origHealth, enabled: origEnabled },
});
} else if (item.type === 'collection') {
const origPos = typeof item.originalState?.position === 'number' ? item.originalState.position : 0;
const origEnabled = item.originalState?.enabled !== false;
await db.collection.update({
where: { id },
data: { position: Math.max(0, origPos), enabled: origEnabled },
});
} else if (item.type === 'member') {
await db.user.update({
where: { id },
data: { disabled: false, role: 'MEMBER' },
});
} else if (item.type === 'upload') {
const origState = (item.originalState?.state as string) || 'CANCELLED';
await db.upload.update({
where: { id },
data: { state: origState },
});
}
await removeFromTrash(id);
await audit(req.user.id, `${item.type.toUpperCase()}_RESTORED`, id);
return { ok: true, restored: true };
}
@Post('recycle-bin/:id/permanent')
@Delete('recycle-bin/:id')
async permanentDeleteFromTrash(@Param('id') id: string, @Req() req: AuthRequest) {
const item = await getTrashItem(id);
if (!item) {
await removeFromTrash(id);
return { ok: true };
}
if (item.type === 'title') {
await this.deleteTitle(id, { permanent: true }, req);
} else if (item.type === 'episode') {
await this.deleteEpisode(id, { permanent: true }, req);
} else if (item.type === 'storage') {
await this.deleteStorage(id, { permanent: true }, req);
} else if (item.type === 'collection') {
await this.deleteCollection(id, { permanent: true }, req);
} else if (item.type === 'member') {
await this.deleteMember(id, { permanent: true }, req);
} else if (item.type === 'upload') {
await unlink(join(dataDir, 'uploads', id)).catch(() => {});
await rm(join(dataDir, 'processing', id), { recursive: true, force: true }).catch(() => {});
await db.upload.delete({ where: { id } }).catch(() => {});
await removeFromTrash(id);
await audit(req.user.id, 'UPLOAD_PERMANENTLY_DELETED', id);
}
await removeFromTrash(id);
return { ok: true, permanent: true };
}
@Post('recycle-bin/empty')
async emptyRecycleBin(@Req() req: AuthRequest) {
const all = await getTrash();
for (const item of all) {
try {
await this.permanentDeleteFromTrash(item.id, req);
} catch {
// continue emptying other items
}
}
await clearTrash();
await audit(req.user.id, 'RECYCLE_BIN_EMPTIED', 'ALL');
return { ok: true };
}
@Get('orders') orders() {
return db.order.findMany({
include: {
user: { select: { name: true, email: true } },
product: { include: { title: { select: { name: true } } } },
},
orderBy: { createdAt: 'desc' },
take: 200,
});
}
@Get('branding')
async getBranding() {
return getBrandingInfo();
}
@Post('branding/logo')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 12 * 1024 * 1024 } }))
async updateLogo(
@UploadedFile() file: Express.Multer.File,
@Body('mode') mode: 'dark' | 'transparent' | 'original' | undefined,
@Req() req: AuthRequest,
) {
if (!file) throw new BadRequestException('Choose an image file (PNG, JPG, WebP, or SVG).');
const b = file.buffer;
const isPng = b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
const isJpg = b[0] === 255 && b[1] === 216 && b[2] === 255;
const isWebp = b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP';
const isSvg = file.mimetype === 'image/svg+xml' || b.toString('utf8', 0, 100).includes('<svg');
if (!isPng && !isJpg && !isWebp && !isSvg) {
throw new BadRequestException('Use PNG, JPEG, WebP, or SVG format.');
}
const result = await updateBranding(b, { mode });
await audit(req.user.id, 'BRANDING_LOGO_UPDATED', `version=${result.version}`);
return result;
}
}
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Req,
Res,
UseGuards,
BadRequestException,
ConflictException,
NotFoundException,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import type { Response } from 'express';
import { createReadStream } from 'node:fs';
import { spawn } from 'node:child_process';
import type { Writable } from 'node:stream';
import { FileInterceptor } from '@nestjs/platform-express';
import { z } from 'zod';
import { unlink, rm, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { db, parse, seal, unseal, token, hash, audit, origin, dataDir, decrypt, type MediaManifest, type AuthRequest } from './core';
import { AdminGuard } from './auth';
import { hf } from './storage';
import { addToTrash, removeFromTrash, getTrash, getTrashItem, clearTrash } from './recycle-bin';
import { getBrandingInfo, updateBranding } from './branding';
import { clearSourceBackup } from './upload-integrity';
import { ciphertext } from './playback';
const artwork = z
.string()
.max(2000)
.refine(
(v) => v.startsWith('/art/') || v.startsWith('/api/artwork/') || /^https:\/\//.test(v),
'Use an uploaded image or HTTPS image URL',
);
const titleSchema = z.object({
name: z.string().trim().min(1).max(150),
synopsis: z.string().max(4000),
format: z.enum(['MOVIE', 'SERIES']),
category: z.enum(['ANIME', 'CARTOON', 'LIVE_ACTION']),
genres: z.array(z.string().max(40)).max(12),
languages: z.array(z.string().max(40)).max(12),
year: z.number().int().min(1900).max(2100),
ageRating: z.string().max(12),
poster: artwork,
backdrop: artwork,
featured: z.boolean(),
rightsNote: z.string().max(2000).default(''),
availableUntil: z.string().datetime().nullable().optional(),
});
('admin')
(AdminGuard)
export class AdminController {
('overview') async overview() {
const [members, titles, orders, uploads, audits] = await Promise.all([
db.user.count(),
db.title.count(),
db.order.aggregate({ where: { status: 'PAID' }, _sum: { amount: true }, _count: true }),
db.upload.findMany({
take: 12,
orderBy: { createdAt: 'desc' },
include: { episode: { include: { title: { select: { name: true } } } } },
}),
db.audit.findMany({ take: 20, orderBy: { createdAt: 'desc' } }),
]);
return {
members,
titles,
revenue: orders._sum.amount || 0,
purchases: orders._count,
uploads,
audits,
};
}
('titles') titles() {
return db.title.findMany({
where: { NOT: { status: { startsWith: 'TRASHED' } } },
include: {
products: { where: { active: true } },
episodes: {
where: { NOT: { name: { startsWith: '[TRASHED]' } } },
orderBy: [{ season: 'asc' }, { number: 'asc' }],
include: {
asset: { select: { id: true, bytes: true, storageId: true } },
uploads: { orderBy: { createdAt: 'desc' }, take: 1 },
},
},
},
orderBy: { createdAt: 'desc' },
});
}
('titles') async create(() body: unknown, () req: AuthRequest) {
const input = parse(titleSchema, body);
const slug =
input.name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')