mirror of
https://github.com/screentinker/screentinker.git
synced 2026-08-13 22:03:13 -06:00
Agency-portal uploads previously all landed at the workspace library root, unsorted. Instead of the issue's whole-workspace folder dropdown (which would leak every folder name to an external party), bind ONE folder per agency token — admin-controlled and agency-invisible — and scope the portal picker strictly to that folder's own subtree (Hybrid-C). Fully backwards-compatible: no bound folder -> root, exactly as before. Model / multi-workspace: an agency token is bound to ONE workspace at issuance, so the token key IS that workspace's private link and the bound folder lives in that workspace. An admin with N workspaces mints one token per workspace (each with its own auto-folder). No workspace-switcher in the portal — the token is the tenant boundary. Backend: - api_tokens.upload_folder_id (additive; ON DELETE SET NULL -> deleting the folder falls back to root). - lib/agency-targets.folderSubtree(): recursive-CTE helper = the SINGLE confinement source shared by GET /api/agency/folders AND the POST /api/agency/content target check, so the set the agency can SEE and the set it may WRITE to can never drift. Workspace-guarded at the anchor row; descendants inherit the workspace (folders.js forbids cross-ws parents). - routes/agency.js: GET /folders (bound subtree only); POST /content defaults to the bound folder and 403s any folder_id outside the subtree. - routes/tokens.js: create auto-creates "Agency — <name>" (or binds a picked folder, validated same-workspace, respecting the 100-folder cap) inside the token tx; new PUT /:id/upload-folder to rebind; listing surfaces the bound folder name. - middleware/apiToken.js + lib/content-ingest.js: upload_folder_id onto req.apiToken; ingest writes folder_id. Frontend: - Agency portal: folder <select> shown only when a real subfolder choice exists (identifies the "Main folder" root client-side without learning the token's folder id). - Settings: folder pick at token creation, bound-folder display, rebind modal. - i18n: 7 new apitoken.* keys across all 5 locales. Tests (429/429): - test/agency-folder.test.js: 5 folderSubtree confinement bites (subtree in, siblings out, workspace guard, null -> root). - test/agency.test.js (+1 e2e): auto-create, default-to-bound, in-subtree pick lands there, sibling -> 403, admin-pick, unknown-pick -> 400, rebind-to-root. Closes #158. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
78 lines
3.5 KiB
JavaScript
78 lines
3.5 KiB
JavaScript
'use strict';
|
|
|
|
// #73: shared content-ingest core. Extracted from routes/content.js POST / so the agency
|
|
// upload (routes/agency.js) produces BYTE-IDENTICAL first-class content (same thumbnail/
|
|
// dimensions/duration/insert) - an agency asset is indistinguishable from a dashboard
|
|
// upload. routes/content.js POST / is now a thin caller; behavior is unchanged (its
|
|
// existing tests are the regression guard).
|
|
|
|
const path = require('path');
|
|
const { v4: uuidv4 } = require('uuid');
|
|
const { db } = require('../db/database');
|
|
const config = require('../config');
|
|
const { sanitizeString } = require('../middleware/sanitize');
|
|
|
|
// Multer takes file.originalname from the multipart header, bypassing sanitizeBody, so
|
|
// HTML-escape here (renders as text in every UI sink). .normalize('NFC') first: macOS
|
|
// sends NFD-decomposed names; Linux/renderers expect NFC. Single point - every filename
|
|
// storage site flows through here.
|
|
function safeFilename(name) {
|
|
return sanitizeString((name || '').normalize('NFC'));
|
|
}
|
|
|
|
// Process a multer-uploaded file (thumbnail + dimensions + duration) and insert a content
|
|
// row. Returns the content row. Throws on a hard failure (the caller maps to 500);
|
|
// thumbnail/metadata failures are best-effort (logged, non-fatal) exactly as before.
|
|
async function ingestUploadedFile({ file, userId, workspaceId, folderId = null }) {
|
|
const id = uuidv4();
|
|
const filepath = file.filename;
|
|
let width = null, height = null, durationSec = null, thumbnailPath = null;
|
|
|
|
try {
|
|
if (file.mimetype.startsWith('image/')) {
|
|
const sharp = require('sharp');
|
|
const metadata = await sharp(file.path).metadata();
|
|
width = metadata.width;
|
|
height = metadata.height;
|
|
thumbnailPath = `thumb_${filepath}`;
|
|
await sharp(file.path)
|
|
.resize(config.thumbnailWidth)
|
|
.jpeg({ quality: 70 })
|
|
.toFile(path.join(config.contentDir, thumbnailPath));
|
|
} else if (file.mimetype.startsWith('video/')) {
|
|
try {
|
|
const { execFileSync } = require('child_process');
|
|
const probe = execFileSync('ffprobe', ['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', file.path],
|
|
{ timeout: 15000 }
|
|
).toString();
|
|
const info = JSON.parse(probe);
|
|
if (info.format?.duration) durationSec = parseFloat(info.format.duration);
|
|
const videoStream = info.streams?.find(s => s.codec_type === 'video');
|
|
if (videoStream) {
|
|
width = videoStream.width;
|
|
height = videoStream.height;
|
|
}
|
|
thumbnailPath = `thumb_${filepath.replace(/\.[^.]+$/, '.jpg')}`;
|
|
try {
|
|
execFileSync('ffmpeg', ['-y', '-i', file.path, '-ss', '2', '-vframes', '1', '-vf', `scale=${config.thumbnailWidth}:-1`, path.join(config.contentDir, thumbnailPath)],
|
|
{ timeout: 15000 }
|
|
);
|
|
} catch { thumbnailPath = null; }
|
|
} catch (e) {
|
|
console.warn('ffprobe failed:', e.message);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.warn('Thumbnail/metadata generation failed:', e.message);
|
|
}
|
|
|
|
db.prepare(`
|
|
INSERT INTO content (id, user_id, workspace_id, filename, filepath, mime_type, file_size, duration_sec, thumbnail_path, width, height, folder_id)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(id, userId, workspaceId, safeFilename(file.originalname), filepath, file.mimetype, file.size, durationSec, thumbnailPath, width, height, folderId || null);
|
|
|
|
return db.prepare('SELECT * FROM content WHERE id = ?').get(id);
|
|
}
|
|
|
|
module.exports = { ingestUploadedFile, safeFilename };
|