Files
vitfit-r2/V2/app/modules/videos/service.js
T
2026-06-16 07:17:49 -04:00

169 lines
5.9 KiB
JavaScript

'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { Op } = require('sequelize');
const { AppError } = require('../../core/errors');
const { log: auditLog } = require('../../core/audit');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', '..', 'uploads');
const ALLOWED_MIMES = ['video/mp4', 'video/quicktime', 'video/x-m4v'];
const EXT_MAP = { 'video/mp4': '.mp4', 'video/quicktime': '.mov', 'video/x-m4v': '.m4v' };
async function validateMimeType(filePath, allowedMimes) {
const { fileTypeFromBuffer } = await import('file-type');
const fd = fs.openSync(filePath, 'r');
const buf = Buffer.alloc(12);
fs.readSync(fd, buf, 0, 12, 0);
fs.closeSync(fd);
const result = await fileTypeFromBuffer(buf);
const mime = result?.mime;
if (!mime || !allowedMimes.includes(mime)) {
throw new AppError('UPLOAD_TYPE_INVALID', 'Only MP4, MOV, and M4V video files are supported.', 400);
}
return mime;
}
async function getVideos(models, orgId, { category, search, page = 1, limit = 50 } = {}) {
const where = { organizationId: orgId };
if (category) where.category = category;
if (search) where.description = { [Op.like]: `%${search}%` };
const offset = (page - 1) * limit;
const { rows, count } = await models.Video.findAndCountAll({
where, limit, offset, order: [['createdAt', 'DESC']],
});
const uploadsDir = UPLOADS_DIR();
const base = '/api/v1/videos/stream/';
return {
rows: rows.map(v => ({
...v.toJSON(),
streamUrl: base + v.filename,
fileExists: fs.existsSync(path.join(uploadsDir, v.filename)),
})),
count,
};
}
async function uploadVideo(models, req, orgId, file, { description, category }) {
const uploadsDir = UPLOADS_DIR();
await fs.promises.mkdir(uploadsDir, { recursive: true });
let detectedMime;
try {
detectedMime = await validateMimeType(file.path, ALLOWED_MIMES);
const ext = EXT_MAP[detectedMime];
const safeName = `${Date.now()}_${crypto.randomBytes(8).toString('hex')}${ext}`;
await fs.promises.rename(file.path, path.join(uploadsDir, safeName));
const video = await models.Video.create({
organizationId: orgId,
filename: safeName,
description: description || '',
category,
mimeType: detectedMime,
fileSizeBytes: file.size,
});
await auditLog(req, 'video.upload', 'video', video.id, { filename: safeName, category, fileSizeBytes: file.size });
return { ...video.toJSON(), streamUrl: '/api/v1/videos/stream/' + safeName };
} finally {
await fs.promises.unlink(file.path).catch(() => {});
}
}
async function deleteVideo(models, req, videoId, orgId) {
const video = await models.Video.findOne({ where: { id: videoId, organizationId: orgId } });
if (!video) throw new AppError('NOT_FOUND', 'Video not found.', 404);
const filePath = path.join(UPLOADS_DIR(), video.filename);
await fs.promises.unlink(filePath).catch(() => {}); // ignore ENOENT
const snapshot = video.toJSON();
await video.destroy();
await auditLog(req, 'video.delete', 'video', videoId, snapshot);
}
async function streamVideo(models, orgId, filename, rangeHeader, res) {
const safeName = path.basename(filename);
if (safeName !== filename) {
throw new AppError('NOT_FOUND', 'Invalid filename.', 404);
}
const video = await models.Video.findOne({ where: { filename: safeName, organizationId: orgId } });
if (!video) throw new AppError('NOT_FOUND', 'Video not found.', 404);
const filePath = path.join(UPLOADS_DIR(), safeName);
const resolvedPath = path.resolve(filePath);
const resolvedDir = path.resolve(UPLOADS_DIR());
if (!resolvedPath.startsWith(resolvedDir + path.sep)) {
throw new AppError('NOT_FOUND', 'Invalid filename.', 404);
}
let stat;
try {
stat = fs.statSync(filePath);
} catch {
throw new AppError('NOT_FOUND', 'Video file not found on disk.', 404);
}
const fileSize = stat.size;
const mimeType = video.mimeType || 'video/mp4';
if (rangeHeader) {
const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-');
const start = parseInt(startStr, 10);
const end = endStr ? parseInt(endStr, 10) : Math.min(start + 1024 * 1024, fileSize - 1);
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1,
'Content-Type': mimeType,
});
fs.createReadStream(filePath, { start, end }).pipe(res);
} else {
res.writeHead(200, {
'Content-Length': fileSize,
'Content-Type': mimeType,
'Accept-Ranges': 'bytes',
});
fs.createReadStream(filePath).pipe(res);
}
}
async function getCategories(models, orgId) {
return models.Category.findAll({ where: { organizationId: orgId }, order: [['name', 'ASC']] });
}
async function createCategory(models, req, orgId, name) {
let category;
try {
category = await models.Category.create({ organizationId: orgId, name });
} catch (err) {
if (err.name === 'SequelizeUniqueConstraintError') {
throw new AppError('CONFLICT', 'Category already exists.', 409, 'name');
}
throw err;
}
await auditLog(req, 'category.create', 'category', category.id, { name });
return category;
}
async function deleteCategory(models, req, categoryId, orgId) {
const category = await models.Category.findOne({ where: { id: categoryId, organizationId: orgId } });
if (!category) throw new AppError('NOT_FOUND', 'Category not found.', 404);
const videoCount = await models.Video.count({ where: { organizationId: orgId, category: category.name } });
if (videoCount > 0) {
throw new AppError('CONFLICT', 'This category has videos. Move or delete the videos first.', 409);
}
await auditLog(req, 'category.delete', 'category', categoryId, { name: category.name });
await category.destroy();
}
module.exports = { getVideos, uploadVideo, deleteVideo, streamVideo, getCategories, createCategory, deleteCategory };