diff --git a/backend/config/relations.js b/backend/config/relations.js index efe4ab3..0b0824e 100644 --- a/backend/config/relations.js +++ b/backend/config/relations.js @@ -19,6 +19,8 @@ const Credit = require('../models/Credit'); const WatchBuddy = require('../models/WatchBuddy'); const EntrySeenBuddy = require('../models/EntrySeenBuddy'); const EpisodeSeenBuddy = require('../models/EpisodeSeenBuddy'); +const Video = require('../models/Video'); +const VideoEntry = require('../models/VideoEntry'); // ? one to one // A hasOne B = A > B @@ -289,3 +291,20 @@ WatchBuddy.belongsToMany(EpisodeSeen, { otherKey: 'episode_seen_id', as: 'episodeSeens', }); + +// * VIDEO & ENTRY - MANY TO MANY (discovery videos) +Video.belongsToMany(Entry, { + through: VideoEntry, + foreignKey: 'video_id', + otherKey: 'entry_id', + onDelete: 'CASCADE', + as: 'entries', +}); + +Entry.belongsToMany(Video, { + through: VideoEntry, + foreignKey: 'entry_id', + otherKey: 'video_id', + onDelete: 'CASCADE', + as: 'videos', +}); diff --git a/backend/controllers/videoController.js b/backend/controllers/videoController.js new file mode 100644 index 0000000..0ba0d51 --- /dev/null +++ b/backend/controllers/videoController.js @@ -0,0 +1,280 @@ +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(); diff --git a/backend/models/Video.js b/backend/models/Video.js new file mode 100644 index 0000000..f750daa --- /dev/null +++ b/backend/models/Video.js @@ -0,0 +1,23 @@ +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); + +const Video = sequelize.define("video", { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + + title: { type: DataTypes.STRING(500) }, + description: { type: DataTypes.TEXT, allowNull: true }, + + filename: { type: DataTypes.STRING(200) }, + original_name: { type: DataTypes.STRING(500), field: "original_name" }, + mime_type: { type: DataTypes.STRING(100), field: "mime_type" }, + size: { type: DataTypes.BIGINT }, + + duration: { type: DataTypes.INTEGER, allowNull: true }, + thumbnail_path: { + type: DataTypes.STRING(200), + field: "thumbnail_path", + allowNull: true, + }, +}); + +module.exports = Video; diff --git a/backend/models/VideoEntry.js b/backend/models/VideoEntry.js new file mode 100644 index 0000000..29aa5cf --- /dev/null +++ b/backend/models/VideoEntry.js @@ -0,0 +1,17 @@ +const { DataTypes } = require("sequelize"); +const sequelize = require("../config/database"); + +// Junction table linking discovery videos to library entries (many-to-many) +const VideoEntry = sequelize.define( + "VideoEntry", + { + id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, + video_id: { type: DataTypes.INTEGER }, + entry_id: { type: DataTypes.INTEGER }, + }, + { + tableName: "video_entries", + }, +); + +module.exports = VideoEntry; diff --git a/backend/package.json b/backend/package.json index 0165572..1f6332d 100644 --- a/backend/package.json +++ b/backend/package.json @@ -30,6 +30,7 @@ "body-parser": "^1.20.3", "dotenv": "^16.4.7", "express": "^4.21.2", + "ffmpeg-static": "^5.3.0", "jsonwebtoken": "^9.0.3", "multer": "^1.4.5-lts.1", "mysql2": "^3.12.0", diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yaml index d1fa86d..cb90ba8 100644 --- a/backend/pnpm-lock.yaml +++ b/backend/pnpm-lock.yaml @@ -20,6 +20,12 @@ importers: express: specifier: ^4.21.2 version: 4.21.2 + ffmpeg-static: + specifier: ^5.3.0 + version: 5.3.0 + jsonwebtoken: + specifier: ^9.0.3 + version: 9.0.3 multer: specifier: ^1.4.5-lts.1 version: 1.4.5-lts.1 @@ -34,7 +40,7 @@ importers: version: 0.1.4 sequelize: specifier: ^6.37.5 - version: 6.37.5(mysql2@3.12.0) + version: 6.37.5(mysql2@3.12.0)(supports-color@5.5.0) sharp: specifier: ^0.33.5 version: 0.33.5 @@ -44,6 +50,10 @@ importers: packages: + '@derhuerst/http-basic@8.2.4': + resolution: {integrity: sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==} + engines: {node: '>=6.0.0'} + '@emnapi/runtime@1.3.1': resolution: {integrity: sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==} @@ -73,67 +83,79 @@ packages: resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-arm@1.0.5': resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-s390x@1.0.4': resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-x64@1.0.4': resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.0.4': resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.0.4': resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-linux-arm64@0.33.5': resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-linux-arm@0.33.5': resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-linux-s390x@0.33.5': resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-linux-x64@0.33.5': resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-linuxmusl-arm64@0.33.5': resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-linuxmusl-x64@0.33.5': resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-wasm32@0.33.5': resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} @@ -158,6 +180,9 @@ packages: '@types/ms@2.1.0': resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} + '@types/node@10.17.60': + resolution: {integrity: sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==} + '@types/node@22.10.10': resolution: {integrity: sha512-X47y/mPNzxviAGY5TcYPtYL8JsY3kAq2n8fMmKoRCxq/c4v4pyGNCzM2R6+M5/umG4ZfHuT+sgqDYqWc9rJ6ww==} @@ -168,6 +193,10 @@ packages: resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} engines: {node: '>= 0.6'} + agent-base@6.0.2: + resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} + engines: {node: '>= 6.0.0'} + anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -206,6 +235,9 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + buffer-equal-constant-time@1.0.1: + resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==} + buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} @@ -225,6 +257,9 @@ packages: resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==} engines: {node: '>= 0.4'} + caseless@0.12.0: + resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==} + chokidar@3.6.0: resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} engines: {node: '>= 8.10.0'} @@ -254,6 +289,10 @@ packages: resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==} engines: {'0': node >= 0.8} + concat-stream@2.0.0: + resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==} + engines: {'0': node >= 6.0} + content-disposition@0.5.4: resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} engines: {node: '>= 0.6'} @@ -315,11 +354,15 @@ packages: dottie@2.0.6: resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} + ecdsa-sig-formatter@1.0.11: + resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==} + ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} @@ -331,6 +374,10 @@ packages: resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} engines: {node: '>= 0.8'} + env-paths@2.2.1: + resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} + engines: {node: '>=6'} + es-define-property@1.0.1: resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} engines: {node: '>= 0.4'} @@ -354,6 +401,10 @@ packages: resolution: {integrity: sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==} engines: {node: '>= 0.10.0'} + ffmpeg-static@5.3.0: + resolution: {integrity: sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==} + engines: {node: '>=16'} + fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} @@ -426,6 +477,13 @@ packages: resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==} engines: {node: '>= 0.8'} + http-response-object@3.0.2: + resolution: {integrity: sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==} + + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + iconv-lite@0.4.24: resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} engines: {node: '>=0.10.0'} @@ -473,6 +531,37 @@ packages: isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} + jsonwebtoken@9.0.3: + resolution: {integrity: sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==} + engines: {node: '>=12', npm: '>=6'} + + jwa@2.0.1: + resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==} + + jws@4.0.1: + resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==} + + lodash.includes@4.3.0: + resolution: {integrity: sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==} + + lodash.isboolean@3.0.3: + resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==} + + lodash.isinteger@4.0.4: + resolution: {integrity: sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==} + + lodash.isnumber@3.0.3: + resolution: {integrity: sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==} + + lodash.isplainobject@4.0.6: + resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==} + + lodash.isstring@4.0.1: + resolution: {integrity: sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==} + + lodash.once@4.1.1: + resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==} + lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} @@ -540,6 +629,7 @@ packages: multer@1.4.5-lts.1: resolution: {integrity: sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==} engines: {node: '>= 6.0.0'} + deprecated: Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version. mysql2@3.12.0: resolution: {integrity: sha512-C8fWhVysZoH63tJbX8d10IAoYCyXy4fdRFz2Ihrt9jtPILYynFEKUUzpp1U7qxzDc3tMbotvaBH+sl6bFnGZiw==} @@ -577,6 +667,9 @@ packages: optional@0.1.4: resolution: {integrity: sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==} + parse-cache-control@1.0.1: + resolution: {integrity: sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==} + parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} @@ -594,6 +687,10 @@ packages: process-nextick-args@2.0.1: resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} + progress@2.0.3: + resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} + engines: {node: '>=0.4.0'} + proxy-addr@2.0.7: resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} engines: {node: '>= 0.10'} @@ -619,6 +716,10 @@ packages: readable-stream@2.3.8: resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + readdirp@3.6.0: resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} engines: {node: '>=8.10.0'} @@ -785,6 +886,7 @@ packages: uuid@8.3.2: resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true validator@13.12.0: @@ -804,6 +906,13 @@ packages: snapshots: + '@derhuerst/http-basic@8.2.4': + dependencies: + caseless: 0.12.0 + concat-stream: 2.0.0 + http-response-object: 3.0.2 + parse-cache-control: 1.0.1 + '@emnapi/runtime@1.3.1': dependencies: tslib: 2.8.1 @@ -890,6 +999,8 @@ snapshots: '@types/ms@2.1.0': {} + '@types/node@10.17.60': {} + '@types/node@22.10.10': dependencies: undici-types: 6.20.0 @@ -901,6 +1012,12 @@ snapshots: mime-types: 2.1.35 negotiator: 0.6.3 + agent-base@6.0.2: + dependencies: + debug: 4.4.0(supports-color@5.5.0) + transitivePeerDependencies: + - supports-color + anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -952,6 +1069,8 @@ snapshots: dependencies: fill-range: 7.1.1 + buffer-equal-constant-time@1.0.1: {} + buffer-from@1.1.2: {} busboy@1.6.0: @@ -970,6 +1089,8 @@ snapshots: call-bind-apply-helpers: 1.0.1 get-intrinsic: 1.2.7 + caseless@0.12.0: {} + chokidar@3.6.0: dependencies: anymatch: 3.1.3 @@ -1011,6 +1132,13 @@ snapshots: readable-stream: 2.3.8 typedarray: 0.0.6 + concat-stream@2.0.0: + dependencies: + buffer-from: 1.1.2 + inherits: 2.0.4 + readable-stream: 3.6.2 + typedarray: 0.0.6 + content-disposition@0.5.4: dependencies: safe-buffer: 5.2.1 @@ -1053,12 +1181,18 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 + ecdsa-sig-formatter@1.0.11: + dependencies: + safe-buffer: 5.2.1 + ee-first@1.1.1: {} encodeurl@1.0.2: {} encodeurl@2.0.0: {} + env-paths@2.2.1: {} + es-define-property@1.0.1: {} es-errors@1.3.0: {} @@ -1107,6 +1241,15 @@ snapshots: transitivePeerDependencies: - supports-color + ffmpeg-static@5.3.0: + dependencies: + '@derhuerst/http-basic': 8.2.4 + env-paths: 2.2.1 + https-proxy-agent: 5.0.1 + progress: 2.0.3 + transitivePeerDependencies: + - supports-color + fill-range@7.1.1: dependencies: to-regex-range: 5.0.1 @@ -1184,6 +1327,17 @@ snapshots: statuses: 2.0.1 toidentifier: 1.0.1 + http-response-object@3.0.2: + dependencies: + '@types/node': 10.17.60 + + https-proxy-agent@5.0.1: + dependencies: + agent-base: 6.0.2 + debug: 4.4.0(supports-color@5.5.0) + transitivePeerDependencies: + - supports-color + iconv-lite@0.4.24: dependencies: safer-buffer: 2.1.2 @@ -1218,6 +1372,44 @@ snapshots: isarray@1.0.0: {} + jsonwebtoken@9.0.3: + dependencies: + jws: 4.0.1 + lodash.includes: 4.3.0 + lodash.isboolean: 3.0.3 + lodash.isinteger: 4.0.4 + lodash.isnumber: 3.0.3 + lodash.isplainobject: 4.0.6 + lodash.isstring: 4.0.1 + lodash.once: 4.1.1 + ms: 2.1.3 + semver: 7.6.3 + + jwa@2.0.1: + dependencies: + buffer-equal-constant-time: 1.0.1 + ecdsa-sig-formatter: 1.0.11 + safe-buffer: 5.2.1 + + jws@4.0.1: + dependencies: + jwa: 2.0.1 + safe-buffer: 5.2.1 + + lodash.includes@4.3.0: {} + + lodash.isboolean@3.0.3: {} + + lodash.isinteger@4.0.4: {} + + lodash.isnumber@3.0.3: {} + + lodash.isplainobject@4.0.6: {} + + lodash.isstring@4.0.1: {} + + lodash.once@4.1.1: {} + lodash@4.17.21: {} long@5.2.4: {} @@ -1315,6 +1507,8 @@ snapshots: optional@0.1.4: {} + parse-cache-control@1.0.1: {} + parseurl@1.3.3: {} path-to-regexp@0.1.12: {} @@ -1325,6 +1519,8 @@ snapshots: process-nextick-args@2.0.1: {} + progress@2.0.3: {} + proxy-addr@2.0.7: dependencies: forwarded: 0.2.0 @@ -1357,6 +1553,12 @@ snapshots: string_decoder: 1.1.1 util-deprecate: 1.0.2 + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.1.1 + util-deprecate: 1.0.2 + readdirp@3.6.0: dependencies: picomatch: 2.3.1 @@ -1393,7 +1595,7 @@ snapshots: sequelize-pool@7.1.0: {} - sequelize@6.37.5(mysql2@3.12.0): + sequelize@6.37.5(mysql2@3.12.0)(supports-color@5.5.0): dependencies: '@types/debug': 4.1.12 '@types/validator': 13.12.2 diff --git a/backend/pnpm-workspace.yaml b/backend/pnpm-workspace.yaml new file mode 100644 index 0000000..df2f4ef --- /dev/null +++ b/backend/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +allowBuilds: + ffmpeg-static: true + sharp: false diff --git a/backend/routes/routes.js b/backend/routes/routes.js index 66d74ee..61a9b3b 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -16,6 +16,7 @@ const aiQueryRouter = require("./ai-query.routes"); const authRouter = require("./auth.routes"); const watchBuddyRouter = require("./watch-buddy.routes"); const homepageIntegrationRouter = require("./homepage-integration.routes"); +const videoRouter = require("./video.routes"); const router = express.Router(); router.use("/auth", authRouter); @@ -37,5 +38,6 @@ router.use("/ping", pingRouter); router.use("/people", peopleRouter); router.use("/ai-query", aiQueryRouter); router.use("/homepage-integration", homepageIntegrationRouter); +router.use("/discovery-videos", videoRouter); module.exports = router; diff --git a/backend/routes/video.routes.js b/backend/routes/video.routes.js new file mode 100644 index 0000000..5082d92 --- /dev/null +++ b/backend/routes/video.routes.js @@ -0,0 +1,17 @@ +const express = require("express"); +const videoRouter = express.Router(); + +const videoController = require("../controllers/videoController.js"); +const { videosUpload } = require("../services/mutlerStorageLocations"); + +const upload = videosUpload.array("videos", 10); + +// ! /discovery-videos +videoRouter.get("/", videoController.getVideos); +videoRouter.post("/", upload, videoController.uploadVideos); +videoRouter.put("/:id", videoController.updateVideo); +videoRouter.delete("/:id", videoController.deleteVideo); +videoRouter.get("/:id/thumbnail", videoController.getThumbnail); +videoRouter.get("/:id/stream", videoController.streamVideo); + +module.exports = videoRouter; diff --git a/backend/services/configService.js b/backend/services/configService.js index 665635a..068ec9a 100644 --- a/backend/services/configService.js +++ b/backend/services/configService.js @@ -120,6 +120,7 @@ class ConfigService { "peoples", "profiles", ); + const videosDir = path.join(dataPath, "videos"); fs.mkdirSync(posterDir, { recursive: true }); fs.mkdirSync(backdropDir, { recursive: true }); @@ -129,6 +130,7 @@ class ConfigService { fs.mkdirSync(seasonsPostersDir, { recursive: true }); fs.mkdirSync(episodesStillsDir, { recursive: true }); fs.mkdirSync(peopleProfilesDir, { recursive: true }); + fs.mkdirSync(videosDir, { recursive: true }); } getTmdbApiUrl() { diff --git a/backend/services/mutlerStorageLocations.js b/backend/services/mutlerStorageLocations.js index c74f7b5..ab07fc9 100644 --- a/backend/services/mutlerStorageLocations.js +++ b/backend/services/mutlerStorageLocations.js @@ -1,4 +1,5 @@ const multer = require("multer"); +const fs = require("fs"); const { v4: uuidv4 } = require("uuid"); const path = require("path"); const configService = require("./configService"); @@ -57,8 +58,27 @@ const peoplePicturesUpload = multer({ }), }); +// ? discovery videos +const videosUpload = multer({ + storage: multer.diskStorage({ + destination: function (req, file, cb) { + const dataPath = configService.getSettings().userDataPath; + const videosDir = path.join(dataPath, "videos"); + // ensure the folder exists even if createMediaFolders() was never called + fs.mkdirSync(videosDir, { recursive: true }); + cb(null, videosDir); + }, + filename: function (req, file, cb) { + const uniqueFilename = uuidv4(); + const extension = file.originalname.split(".").pop(); + cb(null, `${uniqueFilename}.${extension}`); + }, + }), +}); + module.exports = { entryPicturesUpload, collectionPicturesUpload, peoplePicturesUpload, + videosUpload, }; diff --git a/backend/services/videoThumbnailService.js b/backend/services/videoThumbnailService.js new file mode 100644 index 0000000..8502999 --- /dev/null +++ b/backend/services/videoThumbnailService.js @@ -0,0 +1,151 @@ +const path = require("path"); +const fs = require("fs"); +const { execFile } = require("child_process"); + +const configService = require("./configService"); +const Video = require("../models/Video"); + +const { logToFile } = require("./logService"); + +// Limit concurrent ffmpeg jobs so a page full of missing thumbnails +// doesn't start one heavy process per image request at once. +const MAX_CONCURRENT_JOBS = 2; +let activeJobs = 0; +const jobQueue = []; + +function resolveFfmpeg() { + try { + const bin = require("ffmpeg-static"); + if (bin && fs.existsSync(bin)) return bin; + } catch { + // ffmpeg-static not installed + } + return "ffmpeg"; // fall back to a system-wide ffmpeg on PATH +} + +function extractFrame(ffmpeg, inputPath, outputPath, seek) { + return new Promise((resolve, reject) => { + execFile( + ffmpeg, + [ + "-y", + "-ss", + seek, + "-i", + inputPath, + "-frames:v", + "1", + "-vf", + "scale=640:-2", + "-q:v", + "3", + outputPath, + ], + { timeout: 60000, windowsHide: true }, + (err) => (err ? reject(err) : resolve()), + ); + }); +} + +function runLimited(job) { + return new Promise((resolve, reject) => { + const run = async () => { + try { + resolve(await job()); + } catch (err) { + reject(err); + } finally { + activeJobs -= 1; + const next = jobQueue.shift(); + if (next) { + activeJobs += 1; + next(); + } + } + }; + + if (activeJobs < MAX_CONCURRENT_JOBS) { + activeJobs += 1; + run(); + } else { + jobQueue.push(run); + } + }); +} + +/** + * Generates a thumbnail for a video: extracts a frame at 1s (falls back + * to frame 0 for very short videos) and stores `{uuid}.jpg` in + * data/videos/thumbnails/. + * + * Returns the thumbnail filename on success, or null on failure. + * Never throws — a missing thumbnail must not break requests. + */ +async function generateThumbnail(video) { + try { + // Re-check against the DB — the thumbnail may have been generated + // since this video instance was loaded. + const fresh = await Video.findByPk(video.id); + if (!fresh) return null; + + const dataPath = configService.getSettings().userDataPath; + const videosDir = path.join(dataPath, "videos"); + const thumbDir = path.join(videosDir, "thumbnails"); + + const inputPath = path.join(videosDir, fresh.filename); + if (!fs.existsSync(inputPath)) return null; + + const thumbName = `${fresh.filename.split(".")[0]}.jpg`; + const outputPath = path.join(thumbDir, thumbName); + + // Already generated → just make sure the DB knows about it + if (fs.existsSync(outputPath)) { + if (!fresh.thumbnail_path) { + await fresh.update({ thumbnail_path: thumbName }); + } + return thumbName; + } + + fs.mkdirSync(thumbDir, { recursive: true }); + + const ffmpeg = resolveFfmpeg(); + try { + await extractFrame(ffmpeg, inputPath, outputPath, "1"); + } catch { + // very short videos — grab the first frame instead + await extractFrame(ffmpeg, inputPath, outputPath, "0"); + } + + if (!fs.existsSync(outputPath)) return null; + + await fresh.update({ thumbnail_path: thumbName }); + logToFile(`Video Thumbnail | Generated for video ${fresh.id}`); + return thumbName; + } catch (err) { + logToFile(`Video Thumbnail | Error for video ${video.id}`); + logToFile(err); + return null; + } +} + +const inFlight = new Map(); // videoId -> Promise + +/** + * On-demand thumbnail generation. + * - Per-video dedup: concurrent requests for the same video share one job. + * - Global concurrency limit (MAX_CONCURRENT_JOBS ffmpeg processes). + * Called only from the thumbnail endpoint, i.e. when a client actually + * requests a thumbnail that doesn't exist yet. + */ +function ensureThumbnail(video) { + if (inFlight.has(video.id)) return inFlight.get(video.id); + + const tracked = runLimited(() => generateThumbnail(video)); + const shared = tracked.finally(() => { + inFlight.delete(video.id); + }); + inFlight.set(video.id, shared); + return shared; +} + +module.exports = { ensureThumbnail, generateThumbnail }; diff --git a/docs-vault/API Reference.md b/docs-vault/API Reference.md index 3d96ee1..b344f3a 100644 --- a/docs-vault/API Reference.md +++ b/docs-vault/API Reference.md @@ -170,6 +170,23 @@ See [[Media System]] for details. --- +## Discovery Videos + +> [!info] File: `routes/video.routes.js` → `controllers/videoController.js` + +See [[Discovery Videos]] for details. + +| Method | Path | Description | +|---|---|---| +| `GET` | `/discovery-videos?page=&limit=` | Paginated list (includes linked entries) | +| `POST` | `/discovery-videos` | Multipart upload: `videos[]` (≤ 10), `description`, `entryIds` (JSON array) | +| `PUT` | `/discovery-videos/:id` | Update title / description / entry links | +| `DELETE` | `/discovery-videos/:id` | Delete record + files from disk | +| `GET` | `/discovery-videos/:id/thumbnail` | Thumbnail image — generated on demand when missing | +| `GET` | `/discovery-videos/:id/stream` | Video stream with HTTP Range support (`?token=` auth) | + +--- + ## People > [!info] File: `routes/people.routes.js` → `controllers/peopleController.js` diff --git a/docs-vault/Backend.md b/docs-vault/Backend.md index 78d6762..f0c96fb 100644 --- a/docs-vault/Backend.md +++ b/docs-vault/Backend.md @@ -37,10 +37,10 @@ backend/ │ ├── relations.js All model associations → [[Database#Relationships]] │ ├── dataInitializer.js Genre seeding (27 TMDB genres) │ └── sequelizeHooks.js UserCollectionEntry hooks (order management) -├── controllers/ Route handlers (14 controllers) +├── controllers/ Route handlers (15 controllers) ├── services/ Business logic (16 services) → [[Services]] -├── models/ Sequelize models (17 models) → [[Models]] -├── routes/ Express routers (14 route files) → [[API Reference]] +├── models/ Sequelize models (19 models) → [[Models]] +├── routes/ Express routers (15 route files) → [[API Reference]] ├── errors/ Custom error classes → [[Error Handling]] ├── middleware/ │ └── errorHandler.js Central error catching @@ -96,3 +96,4 @@ See [[Media System]] for the complete download → optimize → serve flow. - [[Error Handling]] — Error classes and middleware - [[TMDB Integration]] — External API - [[Media System]] — Image handling +- [[Discovery Videos]] — Video upload/stream API diff --git a/docs-vault/Components.md b/docs-vault/Components.md index 1dc2f08..68ebadd 100644 --- a/docs-vault/Components.md +++ b/docs-vault/Components.md @@ -68,13 +68,27 @@ See [[Statistics]] for data details. | `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection | | `MarkSeasonWatchedDialog` | `dialogs/MarkSeasonWatchedDialog.tsx` | Mark season as watched — single date or scatter mode | +## Discovery Video Components + +> [!info] Folder: `components/discovery-videos/` + +See [[Discovery Videos]]. + +| Component | File | Description | +|---|---|---| +| `VideoCard` | `discovery-videos/VideoCard.tsx` | Card with lazy thumbnail (`loading="lazy"`, on-demand generation) + play overlay, linked-entry chips, edit/delete actions | +| `VideoPlayerDialog` | `discovery-videos/VideoPlayerDialog.tsx` | Playback dialog — autoplay, ↑/↓ (and ←/→) prev/next navigation, linked-entry chips, inline edit | +| `AddVideoDialog` | `discovery-videos/AddVideoDialog.tsx` | Upload (create) and edit modes — dropzone + description + entry multi-select | +| `VideoDropzone` | `discovery-videos/VideoDropzone.tsx` | Native HTML5 drag & drop zone (no dependency) | +| `EntryMultiSelect` | `discovery-videos/EntryMultiSelect.tsx` | Search-first library entry picker (debounced 250 ms) reading from [[Stores\|library store]] | + ## Skeletons > [!info] File: `components/skeletons/PageSkeletons.tsx` -14 named skeleton exports used as `` fallbacks for lazy-loaded pages: +15 named skeleton exports used as `` fallbacks for lazy-loaded pages: -`HomeSkeleton`, `LibrarySkeleton`, `WatchlistSkeleton`, `DashboardSkeleton`, `CollectionsSkeleton`, `CollectionDetailsSkeleton`, `MediaSkeleton`, `CalendarSkeleton`, `EntryDetailsSkeleton`, `SeasonSkeleton`, `EpisodeSkeleton`, `PeopleSkeleton`, `PersonDetailsSkeleton`, `SettingsSkeleton` +`HomeSkeleton`, `LibrarySkeleton`, `WatchlistSkeleton`, `DashboardSkeleton`, `CollectionsSkeleton`, `CollectionDetailsSkeleton`, `MediaSkeleton`, `CalendarSkeleton`, `EntryDetailsSkeleton`, `SeasonSkeleton`, `EpisodeSkeleton`, `PeopleSkeleton`, `PersonDetailsSkeleton`, `SettingsSkeleton`, `DiscoveryVideosSkeleton` ## Command Palette diff --git a/docs-vault/Database.md b/docs-vault/Database.md index 62450e7..77fdae9 100644 --- a/docs-vault/Database.md +++ b/docs-vault/Database.md @@ -30,6 +30,7 @@ erDiagram Entry }o--o{ Genre : tagged Entry }o--o{ Network : airs-on Entry }o--o{ Collection : belongs-to + Entry }o--o{ Video : links-to Season ||--o{ Episode : contains Episode ||--o{ EpisodeSeen : has @@ -63,6 +64,7 @@ Defined in `backend/config/relations.js`: | Credit | Entry | `belongsTo` | — | — | | People | Credit | `hasMany` (as 'roles') | — | — | | Media | * | Polymorphic scopes | `mediaable` + `mediaableId` | — | +| Video | Entry | `belongsToMany` | VideoEntry | CASCADE | ### Polymorphic Media Scopes @@ -101,6 +103,8 @@ See [[Models]] for detailed field definitions of every model. | [[Models#Genre\|Genre]] | Genres (seeded from TMDB) | No | | [[Models#Network\|Network]] | TV networks | No | | [[Models#Franchise\|Franchise]] | Franchise grouping (unused) | No | +| [[Models#Video\|Video]] | Discovery videos | Yes | +| [[Models#VideoEntry\|VideoEntry]] | Video ↔ Entry join | Yes | ## Important Files diff --git a/docs-vault/Discovery Videos.md b/docs-vault/Discovery Videos.md new file mode 100644 index 0000000..9d1c1d9 --- /dev/null +++ b/docs-vault/Discovery Videos.md @@ -0,0 +1,122 @@ +--- +title: Discovery Videos +tags: + - feature + - frontend + - backend + - videos +aliases: + - Videos + - Saved Videos + - Video Vault +--- + +# Discovery Videos + +Personal video vault page — upload local videos (recommendations, anything worth watching later), add a description, and link them to one or more [[Library]] entries. + +**Route:** `/discovery-videos` (sidebar label: "Discover") + +> [!note] Naming +> This page is distinct from [[Pages#DiscoverPage|DiscoverPage]], which is the TMDB browse page at `/discover/:category`. + +--- + +## Overview + +**Responsibilities:** + +- Upload video files via drag & drop (up to 10 at once) +- Store a description per upload +- Link videos to one or many library entries (M:N) +- Display all saved videos in a lazy-loaded grid with inline playback +- Edit / delete videos (deletion also removes the file from disk) + +**Key Flows:** + +1. **Upload:** `AddVideoDialog` → drop files → description + entry multi-select → `POST /discovery-videos` (multipart) → files stored to `data/videos/` with UUID names +2. **Browse:** `DiscoveryVideosPage` → `GET /discovery-videos?page=&limit=` (24/page) → infinite scroll via IntersectionObserver +3. **Play:** clicking a card opens `VideoPlayerDialog` — the video plays in the dialog; ↑/↓ (and ←/→ when the player isn't focused) navigate to the previous/next video. Streamed via `GET /discovery-videos/:id/stream` with HTTP Range support +4. **Thumbnails (on demand):** cards always request `GET /discovery-videos/:id/thumbnail`; when no thumbnail exists yet, the endpoint generates it (ffmpeg frame at 1s) and serves it in the same response — nothing is generated eagerly or at startup + +**Entry linking UX:** the picker in `AddVideoDialog` lists entries only once the user starts typing (debounced 250 ms) — the full library is never rendered at once. + +--- + +## Lazy Loading & Performance + +| Layer | Mechanism | +|---|---| +| Route | `React.lazy()` + `` with `DiscoveryVideosSkeleton` | +| Data | Paginated API + `useInfiniteQuery` + IntersectionObserver sentinel (`rootMargin: "400px"`) — only metadata travels, never video bytes | +| Thumbnails | `` requesting the thumbnail endpoint — generated **on demand** on first request (no eager/startup generation), deduped + limited to 2 concurrent ffmpeg jobs | +| Media | Video plays only inside the player dialog — nothing is fetched until the user opens it; `res.sendFile` → native `Accept-Ranges`/`206` support → browser pulls only the segments it needs on seek/play | + +--- + +## Data Model + +See [[Models#Video]] and [[Models#VideoEntry]] for field details, [[Database#Relationships]] for the relations. + +``` +videos (id, title, description, filename, original_name, mime_type, size, ...) + └── video_entries (video_id, entry_id) ── entries +``` + +--- + +## API + +| Method | Path | Description | +|---|---|---| +| `GET` | `/discovery-videos?page=&limit=` | Paginated list (includes linked entries) | +| `POST` | `/discovery-videos` | Multipart upload: `videos[]` (≤ 10), `description`, `entryIds` (JSON array) | +| `PUT` | `/discovery-videos/:id` | Update title / description / entry links | +| `DELETE` | `/discovery-videos/:id` | Delete record + files from disk | +| `GET` | `/discovery-videos/:id/stream` | Video stream with HTTP Range support | +| `GET` | `/discovery-videos/:id/thumbnail` | Thumbnail image — generated on demand when missing (served in the same response) | + +**Auth:** stream URLs append `?token=` (the `