mirror of
https://github.com/screentinker/screentinker.git
synced 2026-08-13 13:53:12 -06:00
Found by driving the real server and a real browser, not by reading. Each fix has a
test that fails without it.
1. A missing upload answered 200 with the DASHBOARD. express.static falls through on a
miss and the SPA catch-all caught it, so GET /uploads/content/<gone>.mp4 returned
15KB of index.html as text/html — under the `immutable, max-age=30d` header the mount
sets before it knows the file exists. Every player downloader treats 200 as success,
so a panel stores the HTML page AS the video and caches it for a month, rendering a
black frame with nothing in any log. Reachable exactly when it hurts: a content
replace writes a new random filename and unlinks the old one. The mount now
terminates a miss with a 404 and drops the cache header.
2. Four dashboard->device socket handlers had no capability gate. dashboard:device-command
has always refused a command the panel cannot honour, and the comment above it is right
about why ("hiding the button is not enforcement — this socket is reachable directly").
Every word applied to the four handlers immediately above it, which had none: a display
declaring [] still received screenshot-request, remote-touch, remote-key and
remote-start. Measured, not inferred. They now refuse on remote.screenshot /
remote.input / remote.stream and name the capability in the ack; remote-stop stays
ungated for the same reason set_debug does. The undeclared fleet is unaffected — an
absent declaration still resolves to its platform baseline and keeps everything.
The wall panel list (#235) made this visible: it offered a Screenshot button for every
panel, including a BrightSign, which has no screenshot capability at all, and popped a
toast promising an image that was never coming. GET /api/devices now ships the RESOLVED
capability array rather than the raw column ('[]' as a STRING, which Array.isArray reads
as "pre-capability server, show everything" — wrong in the one case that matters), so
the wall list and the fleet cards can hide what a panel cannot do. The remote pad's
Scrn Off / Scrn On were gated on remote.input while the Info tab gated the same two
commands on display.power; both now agree.
3. A register with no `platform` ERASED the stored one. captureIdentity coerces a missing
field to the literal 'unknown' and persistIdentity wrote it straight over. That column
is load-bearing: platformFamily() reads it, so one reconnect from an older build turned
a Tizen panel into a browser tab and handed it a volume slider the .wgt has no handler
for — the exact control BASELINE.tizen exists to hide — while a BrightSign lost screen
power and reboot and gained screenshots it cannot take. platform and client_type are
now preserved (physical facts); client_version and contract_version still decay, because
there "we no longer know" is the truthful answer. client_type 'wgt' is also read as a
second signal for a Tizen TV.
4. PUT /api/content/:id/replace carried its own shorter copy of the ingest logic. Replacing
a video left duration_sec at the OLD clip's length and nulled width/height, so #237's
brand-new "default an item to the clip's own length" then handed out the wrong number
for every later add — 32s scheduled for a 5s video is 27s of frozen frame. Replacing an
image measured it with raw sharp metadata and thumbnailed without .rotate(),
re-introducing the EXIF-orientation bug #172 had just fixed at ingest. Both paths now
share lib/content-ingest.deriveMediaMetadata.
Verified working and NOT changed: all six item-duration insert paths (a 31.7s clip stores
32 everywhere, an explicit value always wins, and no path can store a 0); the content
revision bump + filepath refresh reaching a real device socket; a landscape wall producing
byte-identical geometry to the pre-#236 expression; a portrait wall reaching the player as
side-by-side halves; cross-workspace isolation across 29 probes.
Full suite green (1319).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uaeo9MvzKoyXuN6ZsbhtkL
106 lines
5.5 KiB
JavaScript
106 lines
5.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');
|
|
const { videoDisplayDims, imageDisplayDims } = require('./media-orientation');
|
|
const { finalizeUpload } = require('./upload-sniff');
|
|
|
|
// 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'));
|
|
}
|
|
|
|
/*
|
|
* Everything we can learn from the BYTES: thumbnail, display dimensions, duration.
|
|
*
|
|
* Extracted so PUT /api/content/:id/replace derives them the same way an upload does. It used
|
|
* to carry its own shorter copy that handled images only — so replacing a video wiped the row's
|
|
* duration, dimensions and thumbnail, and replacing a portrait photo re-introduced the EXIF
|
|
* orientation bug (#170) that the ingest path fixes with imageDisplayDims + .rotate(). A second
|
|
* copy of this logic is a second place for it to rot; there is now one.
|
|
*
|
|
* Best-effort by contract: a missing ffprobe or a sharp failure yields nulls and a warning, never
|
|
* a throw — the file itself is already stored and is worth more than its metadata.
|
|
*
|
|
* @returns {{width:number|null, height:number|null, durationSec:number|null, thumbnailPath:string|null}}
|
|
*/
|
|
async function deriveMediaMetadata(sourcePath, filepath, mime) {
|
|
let width = null, height = null, durationSec = null, thumbnailPath = null;
|
|
try {
|
|
// SVG is deliberately NOT handed to sharp: rasterising it goes through librsvg, which
|
|
// is where the outstanding libvips CVEs live, and an SVG is already its own thumbnail.
|
|
if (mime === 'image/svg+xml') {
|
|
thumbnailPath = filepath;
|
|
} else if (mime.startsWith('image/')) {
|
|
const sharp = require('sharp');
|
|
const metadata = await sharp(sourcePath).metadata();
|
|
// #170: honor EXIF orientation so a portrait photo isn't stored as landscape.
|
|
({ width, height } = imageDisplayDims(metadata));
|
|
thumbnailPath = `thumb_${filepath}`;
|
|
await sharp(sourcePath)
|
|
.rotate() // #170: auto-orient per EXIF (and strip the tag) so the thumbnail matches
|
|
.resize(config.thumbnailWidth)
|
|
.jpeg({ quality: 70 })
|
|
.toFile(path.join(config.contentDir, thumbnailPath));
|
|
} else if (mime.startsWith('video/')) {
|
|
try {
|
|
const { execFileSync } = require('child_process');
|
|
const probe = execFileSync('ffprobe', ['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', sourcePath],
|
|
{ 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) {
|
|
// #170: honor the rotation/Display-Matrix so a portrait video isn't stored landscape.
|
|
// (ffmpeg auto-rotates the thumbnail below by default, so only the dims need fixing.)
|
|
({ width, height } = videoDisplayDims(videoStream));
|
|
}
|
|
thumbnailPath = `thumb_${filepath.replace(/\.[^.]+$/, '.jpg')}`;
|
|
try {
|
|
execFileSync('ffmpeg', ['-y', '-i', sourcePath, '-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);
|
|
}
|
|
return { width, height, durationSec, thumbnailPath };
|
|
}
|
|
|
|
// 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();
|
|
// Content-derived extension + mime. Throws UnsupportedUploadError (and removes the temp
|
|
// file) when the bytes are not a supported media type; the caller maps that to a 400.
|
|
const { filepath, mime } = finalizeUpload(file);
|
|
const { width, height, durationSec, thumbnailPath } = await deriveMediaMetadata(file.path, filepath, mime);
|
|
|
|
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, mime, file.size, durationSec, thumbnailPath, width, height, folderId || null);
|
|
|
|
return db.prepare('SELECT * FROM content WHERE id = ?').get(id);
|
|
}
|
|
|
|
module.exports = { ingestUploadedFile, safeFilename, deriveMediaMetadata };
|