const path = require("path"); const fs = require("fs"); const sequelize = require("../config/database"); const Video = require("../models/Video"); const VideoEntry = require("../models/VideoEntry"); const Entry = require("../models/Entry"); const configService = require("../services/configService.js"); const asyncWrapper = require("../utils/asyncWrapper"); const videoThumbnailService = require("../services/videoThumbnailService"); const ALLOWED_EXTENSIONS = ["mp4", "webm", "mov", "m4v", "mkv", "avi"]; function parseEntryIds(raw) { if (raw === undefined || raw === null || raw === "") return []; let parsed; try { parsed = typeof raw === "string" ? JSON.parse(raw) : raw; } catch (err) { return null; // signal invalid input to the caller } if (!Array.isArray(parsed)) return null; const ids = [...new Set(parsed.map(Number))].filter( (n) => Number.isInteger(n) && n > 0, ); return ids; } function getVideosDir() { const dataPath = configService.getSettings().userDataPath; return path.join(dataPath, "videos"); } async function removeFileQuietly(filePath) { try { await fs.promises.unlink(filePath); } catch (err) { // file already gone — nothing to clean up } } class VideoController { constructor() { if (!VideoController.instance) { VideoController.instance = this; } return VideoController.instance; } // * GET /discovery-videos?page=1&limit=24 getVideos = asyncWrapper(async (req, res) => { const page = Math.max(parseInt(req.query.page, 10) || 1, 1); const limit = Math.min( Math.max(parseInt(req.query.limit, 10) || 24, 1), 100, ); const { count, rows } = await Video.findAndCountAll({ limit, offset: (page - 1) * limit, order: [["createdAt", "DESC"]], distinct: true, include: [ { model: Entry, as: "entries", attributes: ["id", "title", "poster_path", "is_tvseries"], through: { attributes: [] }, }, ], }); res.status(200).json({ videos: rows, page, limit, total: count, totalPages: Math.ceil(count / limit), }); }); // * POST /discovery-videos (multipart: videos[], description, entryIds) uploadVideos = asyncWrapper(async (req, res) => { const files = req.files; if (!files || files.length === 0) { return res.status(400).json({ message: "No files uploaded" }); } const entryIds = parseEntryIds(req.body.entryIds); if (entryIds === null) { await Promise.all( files.map((file) => removeFileQuietly(path.join(getVideosDir(), file.filename)), ), ); return res.status(400).json({ message: "entryIds must be a JSON array" }); } const invalidFile = files.find((file) => { const ext = file.originalname.split(".").pop().toLowerCase(); return !ALLOWED_EXTENSIONS.includes(ext); }); if (invalidFile) { await Promise.all( files.map((file) => removeFileQuietly(path.join(getVideosDir(), file.filename)), ), ); return res.status(400).json({ message: `Unsupported file type. Allowed: ${ALLOWED_EXTENSIONS.join(", ")}`, }); } const description = typeof req.body.description === "string" ? req.body.description : ""; const createdVideos = []; for (const file of files) { const title = file.originalname.replace(/\.[^.]+$/, "").trim() || "Untitled video"; const video = await Video.create({ title, description, filename: file.filename, original_name: file.originalname, mime_type: file.mimetype, size: file.size, }); if (entryIds.length > 0) { await VideoEntry.bulkCreate( entryIds.map((entryId) => ({ video_id: video.id, entry_id: entryId, })), ); } createdVideos.push(video); } return res.status(200).json(createdVideos); }); // * PUT /discovery-videos/:id (title, description, entryIds) updateVideo = asyncWrapper(async (req, res) => { const video = await Video.findByPk(req.params.id); if (!video) { return res.status(404).json({ message: "Video not found" }); } const { title, description, entryIds } = req.body; if (title !== undefined && typeof title === "string") { video.title = title.trim() || video.title; } if (description !== undefined && typeof description === "string") { video.description = description; } let parsedEntryIds; if (entryIds !== undefined) { parsedEntryIds = parseEntryIds(entryIds); if (parsedEntryIds === null) { return res .status(400) .json({ message: "entryIds must be a JSON array" }); } } await sequelize.transaction(async (t) => { await video.save({ transaction: t }); if (parsedEntryIds !== undefined) { await VideoEntry.destroy({ where: { video_id: video.id }, transaction: t, }); if (parsedEntryIds.length > 0) { await VideoEntry.bulkCreate( parsedEntryIds.map((entryId) => ({ video_id: video.id, entry_id: entryId, })), { transaction: t }, ); } } }); const updated = await Video.findByPk(video.id, { include: [ { model: Entry, as: "entries", attributes: ["id", "title", "poster_path", "is_tvseries"], through: { attributes: [] }, }, ], }); return res.status(200).json(updated); }); // * DELETE /discovery-videos/:id deleteVideo = asyncWrapper(async (req, res) => { const video = await Video.findByPk(req.params.id); if (!video) { return res.status(404).json({ message: "Video not found" }); } await VideoEntry.destroy({ where: { video_id: video.id } }); await video.destroy(); // Remove the video file and its thumbnail. The thumbnail filename is // derived from the video filename, so delete it even if the DB row // never had thumbnail_path set (e.g. a failed update). await removeFileQuietly(path.join(getVideosDir(), video.filename)); const thumbnailNames = new Set([ `${video.filename.split(".")[0]}.jpg`, ...(video.thumbnail_path ? [video.thumbnail_path] : []), ]); for (const name of thumbnailNames) { await removeFileQuietly(path.join(getVideosDir(), "thumbnails", name)); } return res.status(200).json({ message: "Video deleted" }); }); // * GET /discovery-videos/:id/thumbnail // Serves the thumbnail image. If none exists yet, generates it on // demand (deduped + concurrency-limited inside the service) and // serves it in the same response. getThumbnail = asyncWrapper(async (req, res) => { const video = await Video.findByPk(req.params.id); if (!video) { return res.status(404).json({ message: "Video not found" }); } const thumbDir = path.join(getVideosDir(), "thumbnails"); const thumbName = video.thumbnail_path || `${video.filename.split(".")[0]}.jpg`; let filePath = path.join(thumbDir, thumbName); if (!fs.existsSync(filePath)) { const generated = await videoThumbnailService.ensureThumbnail(video); if (generated) { filePath = path.join(thumbDir, generated); } } if (!fs.existsSync(filePath)) { return res.status(404).json({ message: "Thumbnail not available" }); } res.sendFile(filePath, (err) => { if (err && !res.headersSent) { res.status(404).json({ message: "Thumbnail not available" }); } }); }); // * GET /discovery-videos/:id/stream (supports HTTP Range via res.sendFile) streamVideo = asyncWrapper(async (req, res) => { const video = await Video.findByPk(req.params.id); if (!video) { return res.status(404).json({ message: "Video not found" }); } const filePath = path.join(getVideosDir(), video.filename); res.sendFile(filePath, (err) => { if (err && !res.headersSent) { res.status(404).json({ message: "Video file not found" }); } }); }); } module.exports = new VideoController();