assets.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import { Router, Request, Response } from 'express';
  2. import multer from 'multer';
  3. import path from 'path';
  4. import fs from 'fs';
  5. import { v4 as uuidv4 } from 'uuid';
  6. import { prisma, TranscodeStatus } from '../lib/prisma';
  7. import { authMiddleware } from '../lib/auth';
  8. import { startTranscodeJob } from '../worker/dispatcher';
  9. const router = Router();
  10. // ── CORS preflight (must be before authMiddleware — OPTIONS carries no auth token)
  11. router.options('/', (_req, res) => {
  12. res.setHeader('Access-Control-Allow-Origin', '*');
  13. res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,PATCH,OPTIONS');
  14. res.setHeader('Access-Control-Allow-Headers', 'Authorization,Content-Type,X-Requested-With');
  15. res.sendStatus(200);
  16. });
  17. router.options('/upload', (_req, res) => {
  18. res.setHeader('Access-Control-Allow-Origin', '*');
  19. res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,PATCH,OPTIONS');
  20. res.setHeader('Access-Control-Allow-Headers', 'Authorization,Content-Type,X-Requested-With');
  21. res.sendStatus(200);
  22. });
  23. router.use(authMiddleware);
  24. const str = (v: string | string[] | undefined): string => Array.isArray(v) ? v[0] ?? '' : (v ?? '');
  25. // ── Multer ────────────────────────────────────────────────────────────────────
  26. const UPLOAD_DIR = process.env.UPLOAD_DIR || './uploads';
  27. const MAX_SIZE = (parseInt(process.env.MAX_FILE_SIZE_MB || '500') * 1024 * 1024);
  28. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  29. const storage = multer.diskStorage({
  30. destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
  31. filename: (_req, file, cb) => {
  32. const ext = path.extname(file.originalname);
  33. cb(null, `${uuidv4()}${ext}`);
  34. },
  35. });
  36. class MulterFileTypeError extends Error {
  37. code = 'ONLY_VIDEO';
  38. statusCode = 400;
  39. constructor() {
  40. super('Only video files are allowed');
  41. this.name = 'MulterFileTypeError';
  42. }
  43. }
  44. const ALLOWED_VIDEO_MIMETYPES = [
  45. 'video/mp4',
  46. 'video/quicktime', // MOV (ProRes, H.264, etc.)
  47. 'video/webm', // VP8, VP9, AV1
  48. 'video/x-msvideo', // AVI
  49. 'video/mpeg', // MPEG
  50. 'video/x-matroska', // MKV
  51. 'video/3gpp', // 3GP
  52. 'video/3gpp2', // 3G2
  53. 'video/ogg', // OGV (Theora)
  54. 'video/x-ms-wmv', // WMV
  55. 'video/mp2t', // TS
  56. ];
  57. const upload = multer({
  58. storage,
  59. limits: { fileSize: MAX_SIZE },
  60. fileFilter: (_req, file, cb) => {
  61. if (file.mimetype.startsWith('video/')) {
  62. cb(null, true);
  63. } else {
  64. cb(new MulterFileTypeError());
  65. }
  66. },
  67. });
  68. // GET /api/assets — list assets for a project (paginated)
  69. router.get('/', async (req: Request, res: Response) => {
  70. try {
  71. const { projectId } = req.query;
  72. if (!projectId || typeof projectId !== 'string') {
  73. res.status(400).json({ error: 'projectId query param required' });
  74. return;
  75. }
  76. const isAdmin = req.user!.globalRole === 'ADMIN';
  77. // Verify user has access (admin bypass)
  78. if (!isAdmin) {
  79. const membership = await prisma.projectMember.findFirst({
  80. where: { projectId: projectId as string, userId: req.user!.userId },
  81. });
  82. if (!membership) {
  83. res.status(403).json({ error: 'Forbidden' });
  84. return;
  85. }
  86. }
  87. const page = Math.max(1, parseInt(req.query.page as string) || 1);
  88. const limit = Math.min(100, Math.max(1, parseInt(req.query.limit as string) || 20));
  89. const skip = (page - 1) * limit;
  90. const search = typeof req.query.search === 'string' ? req.query.search.trim() : '';
  91. const status = typeof req.query.status === 'string' ? req.query.status.trim() : '';
  92. const where: Record<string, unknown> = { projectId };
  93. if (search) where.title = { contains: search, mode: 'insensitive' };
  94. if (status) where.status = status;
  95. const [assets, total] = await Promise.all([
  96. prisma.asset.findMany({
  97. where,
  98. skip,
  99. take: limit,
  100. include: {
  101. uploader: { select: { id: true, name: true, email: true, avatarUrl: true } },
  102. _count: { select: { comments: { where: { deleted: false } } } },
  103. shareLinks: { select: { id: true }, take: 1 },
  104. },
  105. orderBy: { createdAt: 'desc' },
  106. }),
  107. prisma.asset.count({ where }),
  108. ]);
  109. res.json({ assets, total, page, limit, totalPages: Math.ceil(total / limit) });
  110. } catch (err) {
  111. console.error('List assets error:', err);
  112. res.status(500).json({ error: 'Internal server error' });
  113. }
  114. });
  115. // GET /api/assets/:id/status — lightweight polling endpoint for transcode progress
  116. router.get('/:id/status', async (req: Request, res: Response) => {
  117. try {
  118. const isAdmin = req.user!.globalRole === 'ADMIN';
  119. const asset = await prisma.asset.findFirst({
  120. where: {
  121. id: str(req.params.id),
  122. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  123. },
  124. select: {
  125. id: true,
  126. title: true,
  127. hlsPath: true,
  128. transcodeStatus: true,
  129. transcodeProgress: true,
  130. transcodeError: true,
  131. transcodePaused: true,
  132. thumbnail: true,
  133. duration: true,
  134. codec: true,
  135. status: true,
  136. },
  137. });
  138. if (!asset) {
  139. res.status(404).json({ error: 'Asset not found' });
  140. return;
  141. }
  142. res.json({ asset });
  143. } catch (err) {
  144. console.error('Asset status error:', err);
  145. res.status(500).json({ error: 'Internal server error' });
  146. }
  147. });
  148. // GET /api/assets/:id
  149. router.get('/:id', async (req: Request, res: Response) => {
  150. try {
  151. const isAdmin = req.user!.globalRole === 'ADMIN';
  152. const asset = await prisma.asset.findFirst({
  153. where: {
  154. id: str(req.params.id),
  155. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  156. },
  157. include: {
  158. uploader: { select: { id: true, name: true, email: true, avatarUrl: true } },
  159. project: {
  160. include: {
  161. members: {
  162. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  163. },
  164. },
  165. },
  166. comments: {
  167. include: {
  168. user: { select: { id: true, name: true, email: true, avatarUrl: true } },
  169. resolvedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  170. requestedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  171. replies: {
  172. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  173. },
  174. },
  175. where: { parentId: null },
  176. orderBy: { timestamp: 'asc' },
  177. },
  178. },
  179. });
  180. if (!asset) {
  181. res.status(404).json({ error: 'Asset not found' });
  182. return;
  183. }
  184. res.json({ asset });
  185. } catch (err) {
  186. console.error('Get asset error:', err);
  187. res.status(500).json({ error: 'Internal server error' });
  188. }
  189. });
  190. // POST /api/assets/upload — upload video
  191. router.post('/upload', upload.single('video'), async (req: Request, res: Response) => {
  192. try {
  193. if (!req.file) {
  194. res.status(400).json({ error: 'No video file provided' });
  195. return;
  196. }
  197. const { projectId, title, folderId } = req.body;
  198. if (!projectId) {
  199. res.status(400).json({ error: 'projectId is required' });
  200. return;
  201. }
  202. // Verify user has access
  203. const membership = await prisma.projectMember.findFirst({
  204. where: { projectId, userId: req.user!.userId },
  205. });
  206. if (!membership || !['ADMIN', 'EDITOR'].includes(membership.role)) {
  207. fs.unlinkSync(req.file.path);
  208. res.status(403).json({ error: 'Forbidden — must be admin or editor' });
  209. return;
  210. }
  211. // ── Quota check ──────────────────────────────────────────────────────────
  212. const uploader = await prisma.user.findUnique({ where: { id: req.user!.userId } });
  213. if (!uploader) {
  214. fs.unlinkSync(req.file.path);
  215. res.status(401).json({ error: 'User not found' });
  216. return;
  217. }
  218. const fileSize = BigInt(req.file.size);
  219. if (uploader.storageUsed + fileSize > uploader.storageQuota) {
  220. fs.unlinkSync(req.file.path);
  221. const usedMB = (Number(uploader.storageUsed) / 1024 / 1024).toFixed(1);
  222. const quotaMB = (Number(uploader.storageQuota) / 1024 / 1024).toFixed(1);
  223. const fileMB = (Number(fileSize) / 1024 / 1024).toFixed(1);
  224. res.status(507).json({
  225. error: `Storage quota exceeded. Used: ${usedMB} MB / ${quotaMB} MB. File size: ${fileMB} MB.`,
  226. });
  227. return;
  228. }
  229. const assetTitle = title || path.parse(req.file.originalname).name;
  230. // Create asset immediately with PROCESSING status — worker fills in the rest
  231. const asset = await prisma.asset.create({
  232. data: {
  233. projectId,
  234. uploaderId: req.user!.userId,
  235. title: assetTitle,
  236. filename: req.file.filename,
  237. originalFilename: req.file.originalname,
  238. filePath: req.file.filename,
  239. mimeType: req.file.mimetype,
  240. fileSize,
  241. transcodeStatus: TranscodeStatus.PENDING,
  242. transcodeProgress: 0,
  243. },
  244. });
  245. // Increment storageUsed (add raw video file size)
  246. await prisma.user.update({
  247. where: { id: req.user!.userId },
  248. data: { storageUsed: { increment: fileSize } },
  249. }).catch(() => { /* user may have been deleted, ignore */ });
  250. // Link asset to folder if provided
  251. if (folderId && typeof folderId === 'string') {
  252. await prisma.folderAsset.upsert({
  253. where: { folderId_assetId: { folderId, assetId: asset.id } },
  254. create: { folderId, assetId: asset.id },
  255. update: {},
  256. }).catch(() => { /* folder may not exist, ignore */ });
  257. }
  258. // Fork worker (non-blocking) — no await, runs in background
  259. startTranscodeJob({
  260. assetId: asset.id,
  261. videoPath: req.file.path,
  262. outputDir: UPLOAD_DIR,
  263. });
  264. res.status(201).json({ asset });
  265. } catch (err) {
  266. console.error('Upload error:', err);
  267. res.status(500).json({ error: 'Internal server error' });
  268. }
  269. });
  270. // PUT /api/assets/:id/status — update approval status
  271. router.put('/:id/status', async (req: Request, res: Response) => {
  272. try {
  273. const { status } = req.body;
  274. const validStatuses = ['PENDING_REVIEW', 'CHANGES_REQUESTED', 'APPROVED', 'REJECTED'];
  275. if (!validStatuses.includes(status)) {
  276. res.status(400).json({ error: 'Invalid status' });
  277. return;
  278. }
  279. const isAdmin = req.user!.globalRole === 'ADMIN';
  280. const asset = await prisma.asset.findFirst({
  281. where: {
  282. id: str(req.params.id),
  283. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  284. },
  285. });
  286. if (!asset) {
  287. res.status(404).json({ error: 'Asset not found' });
  288. return;
  289. }
  290. const updated = await prisma.asset.update({
  291. where: { id: str(req.params.id) },
  292. data: { status: status as any },
  293. });
  294. res.json({ asset: updated });
  295. } catch (err) {
  296. console.error('Update status error:', err);
  297. res.status(500).json({ error: 'Internal server error' });
  298. }
  299. });
  300. // POST /api/assets/:id/transcode/cancel — stop/restart a transcode job
  301. router.post('/:id/transcode/cancel', async (req: Request, res: Response) => {
  302. try {
  303. const isAdmin = req.user!.globalRole === 'ADMIN';
  304. const asset = await prisma.asset.findFirst({
  305. where: {
  306. id: str(req.params.id),
  307. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  308. },
  309. });
  310. if (!asset) {
  311. res.status(404).json({ error: 'Asset not found' });
  312. return;
  313. }
  314. if (asset.transcodeStatus === 'COMPLETED') {
  315. res.status(400).json({ error: 'Cannot cancel a completed transcode job' });
  316. return;
  317. }
  318. // Reset to PENDING — worker will pick it up again on next poll
  319. // Clean up any partially-written HLS directory
  320. if (asset.hlsPath) {
  321. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  322. if (fs.existsSync(hlsDir)) {
  323. fs.rmSync(hlsDir, { recursive: true, force: true });
  324. }
  325. }
  326. const updated = await prisma.asset.update({
  327. where: { id: str(req.params.id) },
  328. data: {
  329. transcodeStatus: TranscodeStatus.PENDING,
  330. transcodeProgress: 0,
  331. transcodeError: null,
  332. hlsPath: null,
  333. },
  334. });
  335. res.json({ asset: updated });
  336. } catch (err) {
  337. console.error('Cancel transcode error:', err);
  338. res.status(500).json({ error: 'Internal server error' });
  339. }
  340. });
  341. // POST /api/assets/:id/transcode/pause — pause a running transcode job
  342. router.post('/:id/transcode/pause', async (req: Request, res: Response) => {
  343. try {
  344. const isAdmin = req.user!.globalRole === 'ADMIN';
  345. const asset = await prisma.asset.findFirst({
  346. where: {
  347. id: str(req.params.id),
  348. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  349. },
  350. });
  351. if (!asset) {
  352. res.status(404).json({ error: 'Asset not found' });
  353. return;
  354. }
  355. if (!['PENDING', 'UPLOADING', 'PROCESSING'].includes(asset.transcodeStatus)) {
  356. res.status(400).json({ error: 'Cannot pause a completed or failed transcode' });
  357. return;
  358. }
  359. const updated = await prisma.asset.update({
  360. where: { id: str(req.params.id) },
  361. data: { transcodePaused: true },
  362. });
  363. res.json({ asset: updated });
  364. } catch (err) {
  365. console.error('Pause transcode error:', err);
  366. res.status(500).json({ error: 'Internal server error' });
  367. }
  368. });
  369. // POST /api/assets/:id/transcode/resume — resume a paused transcode job
  370. router.post('/:id/transcode/resume', async (req: Request, res: Response) => {
  371. try {
  372. const isAdmin = req.user!.globalRole === 'ADMIN';
  373. const asset = await prisma.asset.findFirst({
  374. where: {
  375. id: str(req.params.id),
  376. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  377. },
  378. });
  379. if (!asset) {
  380. res.status(404).json({ error: 'Asset not found' });
  381. return;
  382. }
  383. if (!asset.transcodePaused) {
  384. res.status(400).json({ error: 'Transcode is not paused' });
  385. return;
  386. }
  387. const updated = await prisma.asset.update({
  388. where: { id: str(req.params.id) },
  389. data: { transcodePaused: false },
  390. });
  391. res.json({ asset: updated });
  392. } catch (err) {
  393. console.error('Resume transcode error:', err);
  394. res.status(500).json({ error: 'Internal server error' });
  395. }
  396. });
  397. // DELETE /api/assets/:id
  398. router.delete('/:id', async (req: Request, res: Response) => {
  399. try {
  400. const isAdmin = req.user!.globalRole === 'ADMIN';
  401. const asset = await prisma.asset.findFirst({
  402. where: {
  403. id: str(req.params.id),
  404. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId, role: { in: ['ADMIN', 'EDITOR'] } } } } }),
  405. },
  406. });
  407. if (!asset) {
  408. res.status(404).json({ error: 'Asset not found' });
  409. return;
  410. }
  411. // Delete from disk
  412. const fullPath = path.join(UPLOAD_DIR, asset.filePath);
  413. if (fs.existsSync(fullPath)) {
  414. fs.unlinkSync(fullPath);
  415. }
  416. if (asset.thumbnail) {
  417. const thumbPath = path.join(UPLOAD_DIR, asset.thumbnail);
  418. if (fs.existsSync(thumbPath)) {
  419. fs.unlinkSync(thumbPath);
  420. }
  421. }
  422. // Delete HLS directory (all segments + playlist)
  423. if (asset.hlsPath) {
  424. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  425. if (fs.existsSync(hlsDir)) {
  426. fs.rmSync(hlsDir, { recursive: true, force: true });
  427. }
  428. }
  429. // Decrement uploader's storageUsed
  430. if (BigInt(asset.fileSize) > BigInt(0) && asset.uploaderId) {
  431. await prisma.user.update({
  432. where: { id: asset.uploaderId },
  433. data: { storageUsed: { decrement: asset.fileSize } },
  434. }).catch(() => { /* user may have been deleted or no uploader, ignore */ });
  435. }
  436. await prisma.asset.delete({ where: { id: str(req.params.id) } });
  437. res.json({ message: 'Asset deleted' });
  438. } catch (err) {
  439. console.error('Delete asset error:', err);
  440. res.status(500).json({ error: 'Internal server error' });
  441. }
  442. });
  443. // POST /api/assets/admin/reprocess-all — admin-only: reset all PROCESSING jobs to PENDING
  444. router.post('/admin/reprocess-all', async (req: Request, res: Response) => {
  445. try {
  446. if (req.user!.globalRole !== 'ADMIN') {
  447. res.status(403).json({ error: 'Admin access required' });
  448. return;
  449. }
  450. const stuck = await prisma.asset.findMany({
  451. where: { transcodeStatus: 'PROCESSING', transcodePaused: false },
  452. select: { id: true },
  453. });
  454. if (stuck.length === 0) {
  455. res.json({ message: 'No stuck jobs found', count: 0 });
  456. return;
  457. }
  458. await prisma.asset.updateMany({
  459. where: { id: { in: stuck.map(s => s.id) } },
  460. data: { transcodeStatus: 'PENDING', transcodeProgress: 0 },
  461. });
  462. res.json({ message: `Reset ${stuck.length} stuck job(s) to PENDING`, count: stuck.length });
  463. } catch (err) {
  464. console.error('Reprocess-all error:', err);
  465. res.status(500).json({ error: 'Internal server error' });
  466. }
  467. });
  468. export default router;