assets.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. router.use(authMiddleware);
  11. const str = (v: string | string[] | undefined): string => Array.isArray(v) ? v[0] ?? '' : (v ?? '');
  12. // ── Multer ────────────────────────────────────────────────────────────────────
  13. const UPLOAD_DIR = process.env.UPLOAD_DIR || './uploads';
  14. const MAX_SIZE = (parseInt(process.env.MAX_FILE_SIZE_MB || '500') * 1024 * 1024);
  15. fs.mkdirSync(UPLOAD_DIR, { recursive: true });
  16. const storage = multer.diskStorage({
  17. destination: (_req, _file, cb) => cb(null, UPLOAD_DIR),
  18. filename: (_req, file, cb) => {
  19. const ext = path.extname(file.originalname);
  20. cb(null, `${uuidv4()}${ext}`);
  21. },
  22. });
  23. class MulterFileTypeError extends Error {
  24. code = 'ONLY_VIDEO';
  25. statusCode = 400;
  26. constructor() {
  27. super('Only video files are allowed');
  28. this.name = 'MulterFileTypeError';
  29. }
  30. }
  31. const ALLOWED_VIDEO_MIMETYPES = [
  32. 'video/mp4',
  33. 'video/quicktime', // MOV (ProRes, H.264, etc.)
  34. 'video/webm', // VP8, VP9, AV1
  35. 'video/x-msvideo', // AVI
  36. 'video/mpeg', // MPEG
  37. 'video/x-matroska', // MKV
  38. 'video/3gpp', // 3GP
  39. 'video/3gpp2', // 3G2
  40. 'video/ogg', // OGV (Theora)
  41. 'video/x-ms-wmv', // WMV
  42. 'video/mp2t', // TS
  43. ];
  44. const upload = multer({
  45. storage,
  46. limits: { fileSize: MAX_SIZE },
  47. fileFilter: (_req, file, cb) => {
  48. if (file.mimetype.startsWith('video/')) {
  49. cb(null, true);
  50. } else {
  51. cb(new MulterFileTypeError());
  52. }
  53. },
  54. });
  55. // GET /api/assets — list assets for a project
  56. router.get('/', async (req: Request, res: Response) => {
  57. try {
  58. const { projectId } = req.query;
  59. if (!projectId || typeof projectId !== 'string') {
  60. res.status(400).json({ error: 'projectId query param required' });
  61. return;
  62. }
  63. const isAdmin = req.user!.globalRole === 'ADMIN';
  64. // Verify user has access (admin bypass)
  65. if (!isAdmin) {
  66. const membership = await prisma.projectMember.findFirst({
  67. where: { projectId: projectId as string, userId: req.user!.userId },
  68. });
  69. if (!membership) {
  70. res.status(403).json({ error: 'Forbidden' });
  71. return;
  72. }
  73. }
  74. const assets = await prisma.asset.findMany({
  75. where: { projectId },
  76. include: {
  77. _count: { select: { comments: true } },
  78. },
  79. orderBy: { createdAt: 'desc' },
  80. });
  81. res.json({ assets });
  82. } catch (err) {
  83. console.error('List assets error:', err);
  84. res.status(500).json({ error: 'Internal server error' });
  85. }
  86. });
  87. // GET /api/assets/:id/status — lightweight polling endpoint for transcode progress
  88. router.get('/:id/status', async (req: Request, res: Response) => {
  89. try {
  90. const isAdmin = req.user!.globalRole === 'ADMIN';
  91. const asset = await prisma.asset.findFirst({
  92. where: {
  93. id: str(req.params.id),
  94. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  95. },
  96. select: {
  97. id: true,
  98. title: true,
  99. hlsPath: true,
  100. transcodeStatus: true,
  101. transcodeProgress: true,
  102. transcodeError: true,
  103. thumbnail: true,
  104. duration: true,
  105. codec: true,
  106. status: true,
  107. },
  108. });
  109. if (!asset) {
  110. res.status(404).json({ error: 'Asset not found' });
  111. return;
  112. }
  113. res.json({ asset });
  114. } catch (err) {
  115. console.error('Asset status error:', err);
  116. res.status(500).json({ error: 'Internal server error' });
  117. }
  118. });
  119. // GET /api/assets/:id
  120. router.get('/:id', async (req: Request, res: Response) => {
  121. try {
  122. const isAdmin = req.user!.globalRole === 'ADMIN';
  123. const asset = await prisma.asset.findFirst({
  124. where: {
  125. id: str(req.params.id),
  126. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  127. },
  128. include: {
  129. project: {
  130. include: {
  131. members: {
  132. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  133. },
  134. },
  135. },
  136. comments: {
  137. include: {
  138. user: { select: { id: true, name: true, email: true, avatarUrl: true } },
  139. resolvedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  140. requestedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  141. replies: {
  142. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  143. },
  144. },
  145. where: { parentId: null },
  146. orderBy: { timestamp: 'asc' },
  147. },
  148. },
  149. });
  150. if (!asset) {
  151. res.status(404).json({ error: 'Asset not found' });
  152. return;
  153. }
  154. res.json({ asset });
  155. } catch (err) {
  156. console.error('Get asset error:', err);
  157. res.status(500).json({ error: 'Internal server error' });
  158. }
  159. });
  160. // POST /api/assets/upload — upload video
  161. router.post('/upload', upload.single('video'), async (req: Request, res: Response) => {
  162. try {
  163. if (!req.file) {
  164. res.status(400).json({ error: 'No video file provided' });
  165. return;
  166. }
  167. const { projectId, title } = req.body;
  168. if (!projectId) {
  169. res.status(400).json({ error: 'projectId is required' });
  170. return;
  171. }
  172. // Verify user has access
  173. const membership = await prisma.projectMember.findFirst({
  174. where: { projectId, userId: req.user!.userId },
  175. });
  176. if (!membership || !['ADMIN', 'EDITOR'].includes(membership.role)) {
  177. fs.unlinkSync(req.file.path);
  178. res.status(403).json({ error: 'Forbidden — must be admin or editor' });
  179. return;
  180. }
  181. const assetTitle = title || path.parse(req.file.originalname).name;
  182. // Create asset immediately with PROCESSING status — worker fills in the rest
  183. const asset = await prisma.asset.create({
  184. data: {
  185. projectId,
  186. title: assetTitle,
  187. filename: req.file.filename,
  188. filePath: req.file.filename,
  189. mimeType: req.file.mimetype,
  190. transcodeStatus: TranscodeStatus.PENDING,
  191. transcodeProgress: 0,
  192. },
  193. });
  194. // Fork worker (non-blocking) — no await, runs in background
  195. startTranscodeJob({
  196. assetId: asset.id,
  197. videoPath: req.file.path,
  198. outputDir: UPLOAD_DIR,
  199. });
  200. res.status(201).json({ asset });
  201. } catch (err) {
  202. console.error('Upload error:', err);
  203. res.status(500).json({ error: 'Internal server error' });
  204. }
  205. });
  206. // PUT /api/assets/:id/status — update approval status
  207. router.put('/:id/status', async (req: Request, res: Response) => {
  208. try {
  209. const { status } = req.body;
  210. const validStatuses = ['PENDING_REVIEW', 'CHANGES_REQUESTED', 'APPROVED', 'REJECTED'];
  211. if (!validStatuses.includes(status)) {
  212. res.status(400).json({ error: 'Invalid status' });
  213. return;
  214. }
  215. const isAdmin = req.user!.globalRole === 'ADMIN';
  216. const asset = await prisma.asset.findFirst({
  217. where: {
  218. id: str(req.params.id),
  219. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  220. },
  221. });
  222. if (!asset) {
  223. res.status(404).json({ error: 'Asset not found' });
  224. return;
  225. }
  226. const updated = await prisma.asset.update({
  227. where: { id: str(req.params.id) },
  228. data: { status: status as any },
  229. });
  230. res.json({ asset: updated });
  231. } catch (err) {
  232. console.error('Update status error:', err);
  233. res.status(500).json({ error: 'Internal server error' });
  234. }
  235. });
  236. // POST /api/assets/:id/transcode/cancel — stop/restart a transcode job
  237. router.post('/:id/transcode/cancel', async (req: Request, res: Response) => {
  238. try {
  239. const isAdmin = req.user!.globalRole === 'ADMIN';
  240. const asset = await prisma.asset.findFirst({
  241. where: {
  242. id: str(req.params.id),
  243. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  244. },
  245. });
  246. if (!asset) {
  247. res.status(404).json({ error: 'Asset not found' });
  248. return;
  249. }
  250. if (asset.transcodeStatus === 'COMPLETED') {
  251. res.status(400).json({ error: 'Cannot cancel a completed transcode job' });
  252. return;
  253. }
  254. // Reset to PENDING — worker will pick it up again on next poll
  255. // Clean up any partially-written HLS directory
  256. if (asset.hlsPath) {
  257. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  258. if (fs.existsSync(hlsDir)) {
  259. fs.rmSync(hlsDir, { recursive: true, force: true });
  260. }
  261. }
  262. const updated = await prisma.asset.update({
  263. where: { id: str(req.params.id) },
  264. data: {
  265. transcodeStatus: TranscodeStatus.PENDING,
  266. transcodeProgress: 0,
  267. transcodeError: null,
  268. hlsPath: null,
  269. },
  270. });
  271. res.json({ asset: updated });
  272. } catch (err) {
  273. console.error('Cancel transcode error:', err);
  274. res.status(500).json({ error: 'Internal server error' });
  275. }
  276. });
  277. // DELETE /api/assets/:id
  278. router.delete('/:id', async (req: Request, res: Response) => {
  279. try {
  280. const isAdmin = req.user!.globalRole === 'ADMIN';
  281. const asset = await prisma.asset.findFirst({
  282. where: {
  283. id: str(req.params.id),
  284. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId, role: { in: ['ADMIN', 'EDITOR'] } } } } }),
  285. },
  286. });
  287. if (!asset) {
  288. res.status(404).json({ error: 'Asset not found' });
  289. return;
  290. }
  291. // Delete from disk
  292. const fullPath = path.join(UPLOAD_DIR, asset.filePath);
  293. if (fs.existsSync(fullPath)) {
  294. fs.unlinkSync(fullPath);
  295. }
  296. if (asset.thumbnail) {
  297. const thumbPath = path.join(UPLOAD_DIR, asset.thumbnail);
  298. if (fs.existsSync(thumbPath)) {
  299. fs.unlinkSync(thumbPath);
  300. }
  301. }
  302. // Delete HLS directory (all segments + playlist)
  303. if (asset.hlsPath) {
  304. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  305. if (fs.existsSync(hlsDir)) {
  306. fs.rmSync(hlsDir, { recursive: true, force: true });
  307. }
  308. }
  309. await prisma.asset.delete({ where: { id: str(req.params.id) } });
  310. res.json({ message: 'Asset deleted' });
  311. } catch (err) {
  312. console.error('Delete asset error:', err);
  313. res.status(500).json({ error: 'Internal server error' });
  314. }
  315. });
  316. export default router;