assets.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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
  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 assets = await prisma.asset.findMany({
  88. where: { projectId },
  89. include: {
  90. _count: { select: { comments: true } },
  91. },
  92. orderBy: { createdAt: 'desc' },
  93. });
  94. res.json({ assets });
  95. } catch (err) {
  96. console.error('List assets error:', err);
  97. res.status(500).json({ error: 'Internal server error' });
  98. }
  99. });
  100. // GET /api/assets/:id/status — lightweight polling endpoint for transcode progress
  101. router.get('/:id/status', async (req: Request, res: Response) => {
  102. try {
  103. const isAdmin = req.user!.globalRole === 'ADMIN';
  104. const asset = await prisma.asset.findFirst({
  105. where: {
  106. id: str(req.params.id),
  107. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  108. },
  109. select: {
  110. id: true,
  111. title: true,
  112. hlsPath: true,
  113. transcodeStatus: true,
  114. transcodeProgress: true,
  115. transcodeError: true,
  116. thumbnail: true,
  117. duration: true,
  118. codec: true,
  119. status: true,
  120. },
  121. });
  122. if (!asset) {
  123. res.status(404).json({ error: 'Asset not found' });
  124. return;
  125. }
  126. res.json({ asset });
  127. } catch (err) {
  128. console.error('Asset status error:', err);
  129. res.status(500).json({ error: 'Internal server error' });
  130. }
  131. });
  132. // GET /api/assets/:id
  133. router.get('/:id', async (req: Request, res: Response) => {
  134. try {
  135. const isAdmin = req.user!.globalRole === 'ADMIN';
  136. const asset = await prisma.asset.findFirst({
  137. where: {
  138. id: str(req.params.id),
  139. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  140. },
  141. include: {
  142. project: {
  143. include: {
  144. members: {
  145. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  146. },
  147. },
  148. },
  149. comments: {
  150. include: {
  151. user: { select: { id: true, name: true, email: true, avatarUrl: true } },
  152. resolvedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  153. requestedBy: { select: { id: true, name: true, email: true, avatarUrl: true } },
  154. replies: {
  155. include: { user: { select: { id: true, name: true, email: true, avatarUrl: true } } },
  156. },
  157. },
  158. where: { parentId: null },
  159. orderBy: { timestamp: 'asc' },
  160. },
  161. },
  162. });
  163. if (!asset) {
  164. res.status(404).json({ error: 'Asset not found' });
  165. return;
  166. }
  167. res.json({ asset });
  168. } catch (err) {
  169. console.error('Get asset error:', err);
  170. res.status(500).json({ error: 'Internal server error' });
  171. }
  172. });
  173. // POST /api/assets/upload — upload video
  174. router.post('/upload', upload.single('video'), async (req: Request, res: Response) => {
  175. try {
  176. if (!req.file) {
  177. res.status(400).json({ error: 'No video file provided' });
  178. return;
  179. }
  180. const { projectId, title } = req.body;
  181. if (!projectId) {
  182. res.status(400).json({ error: 'projectId is required' });
  183. return;
  184. }
  185. // Verify user has access
  186. const membership = await prisma.projectMember.findFirst({
  187. where: { projectId, userId: req.user!.userId },
  188. });
  189. if (!membership || !['ADMIN', 'EDITOR'].includes(membership.role)) {
  190. fs.unlinkSync(req.file.path);
  191. res.status(403).json({ error: 'Forbidden — must be admin or editor' });
  192. return;
  193. }
  194. // ── Quota check ──────────────────────────────────────────────────────────
  195. const uploader = await prisma.user.findUnique({ where: { id: req.user!.userId } });
  196. if (!uploader) {
  197. fs.unlinkSync(req.file.path);
  198. res.status(401).json({ error: 'User not found' });
  199. return;
  200. }
  201. const fileSize = req.file.size;
  202. if (uploader.storageUsed + fileSize > uploader.storageQuota) {
  203. fs.unlinkSync(req.file.path);
  204. const usedMB = (uploader.storageUsed / 1024 / 1024).toFixed(1);
  205. const quotaMB = (uploader.storageQuota / 1024 / 1024).toFixed(1);
  206. const fileMB = (fileSize / 1024 / 1024).toFixed(1);
  207. res.status(507).json({
  208. error: `Storage quota exceeded. Used: ${usedMB} MB / ${quotaMB} MB. File size: ${fileMB} MB.`,
  209. });
  210. return;
  211. }
  212. const assetTitle = title || path.parse(req.file.originalname).name;
  213. // Create asset immediately with PROCESSING status — worker fills in the rest
  214. const asset = await prisma.asset.create({
  215. data: {
  216. projectId,
  217. uploaderId: req.user!.userId,
  218. title: assetTitle,
  219. filename: req.file.filename,
  220. filePath: req.file.filename,
  221. mimeType: req.file.mimetype,
  222. fileSize,
  223. transcodeStatus: TranscodeStatus.PENDING,
  224. transcodeProgress: 0,
  225. },
  226. });
  227. // Increment storageUsed (add raw video file size)
  228. await prisma.user.update({
  229. where: { id: req.user!.userId },
  230. data: { storageUsed: { increment: fileSize } },
  231. }).catch(() => { /* user may have been deleted, ignore */ });
  232. // Fork worker (non-blocking) — no await, runs in background
  233. startTranscodeJob({
  234. assetId: asset.id,
  235. videoPath: req.file.path,
  236. outputDir: UPLOAD_DIR,
  237. });
  238. res.status(201).json({ asset });
  239. } catch (err) {
  240. console.error('Upload error:', err);
  241. res.status(500).json({ error: 'Internal server error' });
  242. }
  243. });
  244. // PUT /api/assets/:id/status — update approval status
  245. router.put('/:id/status', async (req: Request, res: Response) => {
  246. try {
  247. const { status } = req.body;
  248. const validStatuses = ['PENDING_REVIEW', 'CHANGES_REQUESTED', 'APPROVED', 'REJECTED'];
  249. if (!validStatuses.includes(status)) {
  250. res.status(400).json({ error: 'Invalid status' });
  251. return;
  252. }
  253. const isAdmin = req.user!.globalRole === 'ADMIN';
  254. const asset = await prisma.asset.findFirst({
  255. where: {
  256. id: str(req.params.id),
  257. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  258. },
  259. });
  260. if (!asset) {
  261. res.status(404).json({ error: 'Asset not found' });
  262. return;
  263. }
  264. const updated = await prisma.asset.update({
  265. where: { id: str(req.params.id) },
  266. data: { status: status as any },
  267. });
  268. res.json({ asset: updated });
  269. } catch (err) {
  270. console.error('Update status error:', err);
  271. res.status(500).json({ error: 'Internal server error' });
  272. }
  273. });
  274. // POST /api/assets/:id/transcode/cancel — stop/restart a transcode job
  275. router.post('/:id/transcode/cancel', async (req: Request, res: Response) => {
  276. try {
  277. const isAdmin = req.user!.globalRole === 'ADMIN';
  278. const asset = await prisma.asset.findFirst({
  279. where: {
  280. id: str(req.params.id),
  281. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId } } } }),
  282. },
  283. });
  284. if (!asset) {
  285. res.status(404).json({ error: 'Asset not found' });
  286. return;
  287. }
  288. if (asset.transcodeStatus === 'COMPLETED') {
  289. res.status(400).json({ error: 'Cannot cancel a completed transcode job' });
  290. return;
  291. }
  292. // Reset to PENDING — worker will pick it up again on next poll
  293. // Clean up any partially-written HLS directory
  294. if (asset.hlsPath) {
  295. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  296. if (fs.existsSync(hlsDir)) {
  297. fs.rmSync(hlsDir, { recursive: true, force: true });
  298. }
  299. }
  300. const updated = await prisma.asset.update({
  301. where: { id: str(req.params.id) },
  302. data: {
  303. transcodeStatus: TranscodeStatus.PENDING,
  304. transcodeProgress: 0,
  305. transcodeError: null,
  306. hlsPath: null,
  307. },
  308. });
  309. res.json({ asset: updated });
  310. } catch (err) {
  311. console.error('Cancel transcode error:', err);
  312. res.status(500).json({ error: 'Internal server error' });
  313. }
  314. });
  315. // DELETE /api/assets/:id
  316. router.delete('/:id', async (req: Request, res: Response) => {
  317. try {
  318. const isAdmin = req.user!.globalRole === 'ADMIN';
  319. const asset = await prisma.asset.findFirst({
  320. where: {
  321. id: str(req.params.id),
  322. ...(isAdmin ? {} : { project: { members: { some: { userId: req.user!.userId, role: { in: ['ADMIN', 'EDITOR'] } } } } }),
  323. },
  324. });
  325. if (!asset) {
  326. res.status(404).json({ error: 'Asset not found' });
  327. return;
  328. }
  329. // Delete from disk
  330. const fullPath = path.join(UPLOAD_DIR, asset.filePath);
  331. if (fs.existsSync(fullPath)) {
  332. fs.unlinkSync(fullPath);
  333. }
  334. if (asset.thumbnail) {
  335. const thumbPath = path.join(UPLOAD_DIR, asset.thumbnail);
  336. if (fs.existsSync(thumbPath)) {
  337. fs.unlinkSync(thumbPath);
  338. }
  339. }
  340. // Delete HLS directory (all segments + playlist)
  341. if (asset.hlsPath) {
  342. const hlsDir = path.join(UPLOAD_DIR, 'hls', asset.id);
  343. if (fs.existsSync(hlsDir)) {
  344. fs.rmSync(hlsDir, { recursive: true, force: true });
  345. }
  346. }
  347. // Decrement uploader's storageUsed
  348. if (asset.fileSize > 0 && asset.uploaderId) {
  349. await prisma.user.update({
  350. where: { id: asset.uploaderId },
  351. data: { storageUsed: { decrement: asset.fileSize } },
  352. }).catch(() => { /* user may have been deleted or no uploader, ignore */ });
  353. }
  354. await prisma.asset.delete({ where: { id: str(req.params.id) } });
  355. res.json({ message: 'Asset deleted' });
  356. } catch (err) {
  357. console.error('Delete asset error:', err);
  358. res.status(500).json({ error: 'Internal server error' });
  359. }
  360. });
  361. export default router;