proper video streaming with audio and subtitle track support
@@ -58,16 +58,24 @@
58
58
- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
59
59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
60
60
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
61
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
61
62
62
63
## server/routes/share.js
63
64
- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
64
65
- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
65
66
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
66
67
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
68
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
67
69
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
68
70
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
69
71
- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
70
72
73
## server/video-stream.js
74
- createVideoStreamSession(sourcePath) - Probes the input, attempts WebVTT conversion for all subtitle streams (skipping only failed conversions), starts ffmpeg HLS transcoding, and resolves once stream output begins; returns subtitleTracks plus subtitleSummary {total, converted, skipped}.
75
- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
76
- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
77
- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
78
71
79
## server/db.js
72
80
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
73
81
- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
@@ -80,8 +88,12 @@
80
88
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
81
89
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
82
90
91
## public/index.html
92
- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
93
83
94
## public/app.js
84
95
- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
96
- showAuthOverlay(setupMode) - Displays the login/setup overlay and switches the password autocomplete token between current-password and new-password based on mode.
85
97
- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
86
98
- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
87
99
- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
@@ -111,6 +123,7 @@
111
123
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
112
124
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
113
125
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
126
- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source and initial subtitle track config; warns when subtitle streams exist but none are web-compatible.
114
127
115
128
## tests/thumbnail-cache.test.js
116
129
- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
@@ -180,4 +193,11 @@
180
193
## tests/page.load.test.js
181
194
- bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
182
195
- waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
183
- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions for file sharing and downloading.
196
- login overlay uses username and current-password autocomplete tokens - Verifies normal sign-in mode exposes browser-friendly login autocomplete attributes.
197
- first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
198
- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
199
- expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
200
201
## tests/video-stream.test.js
202
- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
203
- createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
@@ -58,16 +58,24 @@58
- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
58
- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
60
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
60
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
61
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
61
62
62
## server/routes/share.js
63
## server/routes/share.js
63
- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
64
- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
64
- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
65
- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
65
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
66
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
66
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
67
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
68
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
67
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
69
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
68
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
70
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
69
- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
71
- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
70
72
73
## server/video-stream.js
74
- createVideoStreamSession(sourcePath) - Probes the input, attempts WebVTT conversion for all subtitle streams (skipping only failed conversions), starts ffmpeg HLS transcoding, and resolves once stream output begins; returns subtitleTracks plus subtitleSummary {total, converted, skipped}.
75
- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
76
- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
77
- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
78
71
## server/db.js
79
## server/db.js
72
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
80
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
73
- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
81
- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
@@ -80,8 +88,12 @@80
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
88
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
81
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
89
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
82
90
91
## public/index.html
92
- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
93
83
## public/app.js
94
## public/app.js
84
- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
95
- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
96
- showAuthOverlay(setupMode) - Displays the login/setup overlay and switches the password autocomplete token between current-password and new-password based on mode.
85
- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
97
- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
86
- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
98
- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
87
- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
99
- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
@@ -111,6 +123,7 @@111
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
123
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
112
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
124
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
113
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
125
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
126
- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source and initial subtitle track config; warns when subtitle streams exist but none are web-compatible.
114
127
115
## tests/thumbnail-cache.test.js
128
## tests/thumbnail-cache.test.js
116
- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
129
- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
@@ -180,4 +193,11 @@180
## tests/page.load.test.js
193
## tests/page.load.test.js
181
- bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
194
- bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
182
- waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
195
- waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
183
- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions for file sharing and downloading.
196
- login overlay uses username and current-password autocomplete tokens - Verifies normal sign-in mode exposes browser-friendly login autocomplete attributes.
197
- first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
198
- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
199
- expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
200
201
## tests/video-stream.test.js
202
- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
203
- createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
@@ -44,6 +44,7 @@
44
44
- `GET /api/files/root-access`
45
45
- `folder icon endpoints`
46
46
- `GET /api/files/download-zip`
47
- `video streaming routes`
47
48
48
49
---
49
50
@@ -56,6 +57,7 @@
56
57
- `POST /api/share/create`
57
58
- `GET /api/share/info/:token`
58
59
- `GET /api/share/preview/:token`
60
- `GET /api/share/video-stream/:token`
59
61
- `GET /api/share/download/:token`
60
62
- `pruneZipCache`
61
63
@@ -65,3 +67,8 @@
65
67
- `thumbnail cache worker`
66
68
67
69
---
70
71
## `test/video-stream.test.js`
72
- `video stream bootstrap`
73
74
---
@@ -44,6 +44,7 @@44
- `GET /api/files/root-access`44
- `GET /api/files/root-access`45
- `folder icon endpoints`45
- `folder icon endpoints`46
- `GET /api/files/download-zip`46
- `GET /api/files/download-zip`47
- `video streaming routes`47
48
48
---49
---49
50
@@ -56,6 +57,7 @@56
- `POST /api/share/create`57
- `POST /api/share/create`57
- `GET /api/share/info/:token`58
- `GET /api/share/info/:token`58
- `GET /api/share/preview/:token`59
- `GET /api/share/preview/:token`60
- `GET /api/share/video-stream/:token`59
- `GET /api/share/download/:token`61
- `GET /api/share/download/:token`60
- `pruneZipCache`62
- `pruneZipCache`61
63
@@ -65,3 +67,8 @@65
- `thumbnail cache worker`67
- `thumbnail cache worker`66
68
67
---69
---70
71
## `test/video-stream.test.js`72
- `video stream bootstrap`73
74
---@@ -17,7 +17,8 @@
17
17
"multer": "^1.4.5-lts.1",
18
18
"node-sqlite3-wasm": "^0.8.10",
19
19
"sharp": "^0.34.5",
20
"uuid": "^9.0.0"
20
"uuid": "^9.0.0",
21
"video.js": "^8.23.7"
21
22
},
22
23
"devDependencies": {
23
24
"jest-environment-jsdom": "^30.3.0",
@@ -496,6 +497,15 @@
496
497
"@babel/core": "^7.0.0-0"
497
498
}
498
499
},
500
"node_modules/@babel/runtime": {
501
"version": "7.29.2",
502
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
503
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
504
"license": "MIT",
505
"engines": {
506
"node": ">=6.9.0"
507
}
508
},
499
509
"node_modules/@babel/template": {
500
510
"version": "7.28.6",
501
511
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
@@ -2037,6 +2047,63 @@
2037
2047
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
2038
2048
"license": "MIT"
2039
2049
},
2050
"node_modules/@videojs/http-streaming": {
2051
"version": "3.17.4",
2052
"resolved": "https://registry.npmjs.org/@videojs/http-streaming/-/http-streaming-3.17.4.tgz",
2053
"integrity": "sha512-XAvdG2dolBuV2Fx8bu1kjmQ2D4TonGzZH68Pgv/O9xMSFWdZtITSMFismeQLEAtMmGwze8qNJp3RgV+jStrJqg==",
2054
"license": "Apache-2.0",
2055
"dependencies": {
2056
"@babel/runtime": "^7.12.5",
2057
"@videojs/vhs-utils": "^4.1.1",
2058
"aes-decrypter": "^4.0.2",
2059
"global": "^4.4.0",
2060
"m3u8-parser": "^7.2.0",
2061
"mpd-parser": "^1.3.1",
2062
"mux.js": "7.1.0",
2063
"video.js": "^7 || ^8"
2064
},
2065
"engines": {
2066
"node": ">=8",
2067
"npm": ">=5"
2068
},
2069
"peerDependencies": {
2070
"video.js": "^8.19.0"
2071
}
2072
},
2073
"node_modules/@videojs/vhs-utils": {
2074
"version": "4.1.1",
2075
"resolved": "https://registry.npmjs.org/@videojs/vhs-utils/-/vhs-utils-4.1.1.tgz",
2076
"integrity": "sha512-5iLX6sR2ownbv4Mtejw6Ax+naosGvoT9kY+gcuHzANyUZZ+4NpeNdKMUhb6ag0acYej1Y7cmr/F2+4PrggMiVA==",
2077
"license": "MIT",
2078
"dependencies": {
2079
"@babel/runtime": "^7.12.5",
2080
"global": "^4.4.0"
2081
},
2082
"engines": {
2083
"node": ">=8",
2084
"npm": ">=5"
2085
}
2086
},
2087
"node_modules/@videojs/xhr": {
2088
"version": "2.7.0",
2089
"resolved": "https://registry.npmjs.org/@videojs/xhr/-/xhr-2.7.0.tgz",
2090
"integrity": "sha512-giab+EVRanChIupZK7gXjHy90y3nncA2phIOyG3Ne5fvpiMJzvqYwiTOnEVW2S4CoYcuKJkomat7bMXA/UoUZQ==",
2091
"license": "MIT",
2092
"dependencies": {
2093
"@babel/runtime": "^7.5.5",
2094
"global": "~4.4.0",
2095
"is-function": "^1.0.1"
2096
}
2097
},
2098
"node_modules/@xmldom/xmldom": {
2099
"version": "0.8.13",
2100
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
2101
"integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
2102
"license": "MIT",
2103
"engines": {
2104
"node": ">=10.0.0"
2105
}
2106
},
2040
2107
"node_modules/abab": {
2041
2108
"version": "2.0.6",
2042
2109
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",
@@ -2113,6 +2180,18 @@
2113
2180
"node": ">=0.4.0"
2114
2181
}
2115
2182
},
2183
"node_modules/aes-decrypter": {
2184
"version": "4.0.2",
2185
"resolved": "https://registry.npmjs.org/aes-decrypter/-/aes-decrypter-4.0.2.tgz",
2186
"integrity": "sha512-lc+/9s6iJvuaRe5qDlMTpCFjnwpkeOXp8qP3oiZ5jsj1MRg+SBVUmmICrhxHvc8OELSmc+fEyyxAuppY6hrWzw==",
2187
"license": "Apache-2.0",
2188
"dependencies": {
2189
"@babel/runtime": "^7.12.5",
2190
"@videojs/vhs-utils": "^4.1.1",
2191
"global": "^4.4.0",
2192
"pkcs7": "^1.0.4"
2193
}
2194
},
2116
2195
"node_modules/agent-base": {
2117
2196
"version": "6.0.2",
2118
2197
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -3449,6 +3528,11 @@
3449
3528
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
3450
3529
}
3451
3530
},
3531
"node_modules/dom-walk": {
3532
"version": "0.1.2",
3533
"resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz",
3534
"integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w=="
3535
},
3452
3536
"node_modules/domexception": {
3453
3537
"version": "4.0.0",
3454
3538
"resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz",
@@ -4161,6 +4245,16 @@
4161
4245
"url": "https://github.com/sponsors/isaacs"
4162
4246
}
4163
4247
},
4248
"node_modules/global": {
4249
"version": "4.4.0",
4250
"resolved": "https://registry.npmjs.org/global/-/global-4.4.0.tgz",
4251
"integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==",
4252
"license": "MIT",
4253
"dependencies": {
4254
"min-document": "^2.19.0",
4255
"process": "^0.11.10"
4256
}
4257
},
4164
4258
"node_modules/gopd": {
4165
4259
"version": "1.2.0",
4166
4260
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -4488,6 +4582,12 @@
4488
4582
"node": ">=8"
4489
4583
}
4490
4584
},
4585
"node_modules/is-function": {
4586
"version": "1.0.2",
4587
"resolved": "https://registry.npmjs.org/is-function/-/is-function-1.0.2.tgz",
4588
"integrity": "sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ==",
4589
"license": "MIT"
4590
},
4491
4591
"node_modules/is-generator-fn": {
4492
4592
"version": "2.1.0",
4493
4593
"resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz",
@@ -5983,6 +6083,17 @@
5983
6083
"yallist": "^3.0.2"
5984
6084
}
5985
6085
},
6086
"node_modules/m3u8-parser": {
6087
"version": "7.2.0",
6088
"resolved": "https://registry.npmjs.org/m3u8-parser/-/m3u8-parser-7.2.0.tgz",
6089
"integrity": "sha512-CRatFqpjVtMiMaKXxNvuI3I++vUumIXVVT/JpCpdU/FynV/ceVw1qpPyyBNindL+JlPMSesx+WX1QJaZEJSaMQ==",
6090
"license": "Apache-2.0",
6091
"dependencies": {
6092
"@babel/runtime": "^7.12.5",
6093
"@videojs/vhs-utils": "^4.1.1",
6094
"global": "^4.4.0"
6095
}
6096
},
5986
6097
"node_modules/make-dir": {
5987
6098
"version": "3.1.0",
5988
6099
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
@@ -6113,6 +6224,15 @@
6113
6224
"node": ">=6"
6114
6225
}
6115
6226
},
6227
"node_modules/min-document": {
6228
"version": "2.19.2",
6229
"resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.2.tgz",
6230
"integrity": "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A==",
6231
"license": "MIT",
6232
"dependencies": {
6233
"dom-walk": "^0.1.0"
6234
}
6235
},
6116
6236
"node_modules/minimatch": {
6117
6237
"version": "3.1.5",
6118
6238
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
@@ -6186,6 +6306,21 @@
6186
6306
"mkdirp": "bin/cmd.js"
6187
6307
}
6188
6308
},
6309
"node_modules/mpd-parser": {
6310
"version": "1.3.1",
6311
"resolved": "https://registry.npmjs.org/mpd-parser/-/mpd-parser-1.3.1.tgz",
6312
"integrity": "sha512-1FuyEWI5k2HcmhS1HkKnUAQV7yFPfXPht2DnRRGtoiiAAW+ESTbtEXIDpRkwdU+XyrQuwrIym7UkoPKsZ0SyFw==",
6313
"license": "Apache-2.0",
6314
"dependencies": {
6315
"@babel/runtime": "^7.12.5",
6316
"@videojs/vhs-utils": "^4.0.0",
6317
"@xmldom/xmldom": "^0.8.3",
6318
"global": "^4.4.0"
6319
},
6320
"bin": {
6321
"mpd-to-m3u8-json": "bin/parse.js"
6322
}
6323
},
6189
6324
"node_modules/ms": {
6190
6325
"version": "2.0.0",
6191
6326
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
@@ -6211,6 +6346,23 @@
6211
6346
"node": ">= 6.0.0"
6212
6347
}
6213
6348
},
6349
"node_modules/mux.js": {
6350
"version": "7.1.0",
6351
"resolved": "https://registry.npmjs.org/mux.js/-/mux.js-7.1.0.tgz",
6352
"integrity": "sha512-NTxawK/BBELJrYsZThEulyUMDVlLizKdxyAsMuzoCD1eFj97BVaA8D/CvKsKu6FOLYkFojN5CbM9h++ZTZtknA==",
6353
"license": "Apache-2.0",
6354
"dependencies": {
6355
"@babel/runtime": "^7.11.2",
6356
"global": "^4.4.0"
6357
},
6358
"bin": {
6359
"muxjs-transmux": "bin/transmux.js"
6360
},
6361
"engines": {
6362
"node": ">=8",
6363
"npm": ">=5"
6364
}
6365
},
6214
6366
"node_modules/natural-compare": {
6215
6367
"version": "1.4.0",
6216
6368
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -6574,6 +6726,18 @@
6574
6726
"node": ">= 6"
6575
6727
}
6576
6728
},
6729
"node_modules/pkcs7": {
6730
"version": "1.0.4",
6731
"resolved": "https://registry.npmjs.org/pkcs7/-/pkcs7-1.0.4.tgz",
6732
"integrity": "sha512-afRERtHn54AlwaF2/+LFszyAANTCggGilmcmILUzEjvs3XgFZT+xE6+QWQcAGmu4xajy+Xtj7acLOPdx5/eXWQ==",
6733
"license": "Apache-2.0",
6734
"dependencies": {
6735
"@babel/runtime": "^7.5.5"
6736
},
6737
"bin": {
6738
"pkcs7": "bin/cli.js"
6739
}
6740
},
6577
6741
"node_modules/pkg-dir": {
6578
6742
"version": "4.2.0",
6579
6743
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
@@ -7673,6 +7837,57 @@
7673
7837
"node": ">= 0.8"
7674
7838
}
7675
7839
},
7840
"node_modules/video.js": {
7841
"version": "8.23.7",
7842
"resolved": "https://registry.npmjs.org/video.js/-/video.js-8.23.7.tgz",
7843
"integrity": "sha512-cG4HOygYt+Z8j6Sf5DuK6OgEOoM+g9oGP6vpqoZRaD13aHE4PMITbyjJUXZcIQbgB0wJEadBRaVm5lJIzo2jAA==",
7844
"license": "Apache-2.0",
7845
"dependencies": {
7846
"@babel/runtime": "^7.28.4",
7847
"@videojs/http-streaming": "^3.17.3",
7848
"@videojs/vhs-utils": "^4.1.1",
7849
"@videojs/xhr": "2.7.0",
7850
"aes-decrypter": "^4.0.2",
7851
"global": "4.4.0",
7852
"m3u8-parser": "^7.2.0",
7853
"mpd-parser": "^1.3.1",
7854
"mux.js": "^7.0.1",
7855
"videojs-contrib-quality-levels": "4.1.0",
7856
"videojs-font": "4.2.0",
7857
"videojs-vtt.js": "0.15.5"
7858
}
7859
},
7860
"node_modules/videojs-contrib-quality-levels": {
7861
"version": "4.1.0",
7862
"resolved": "https://registry.npmjs.org/videojs-contrib-quality-levels/-/videojs-contrib-quality-levels-4.1.0.tgz",
7863
"integrity": "sha512-TfrXJJg1Bv4t6TOCMEVMwF/CoS8iENYsWNKip8zfhB5kTcegiFYezEA0eHAJPU64ZC8NQbxQgOwAsYU8VXbOWA==",
7864
"license": "Apache-2.0",
7865
"dependencies": {
7866
"global": "^4.4.0"
7867
},
7868
"engines": {
7869
"node": ">=16",
7870
"npm": ">=8"
7871
},
7872
"peerDependencies": {
7873
"video.js": "^8"
7874
}
7875
},
7876
"node_modules/videojs-font": {
7877
"version": "4.2.0",
7878
"resolved": "https://registry.npmjs.org/videojs-font/-/videojs-font-4.2.0.tgz",
7879
"integrity": "sha512-YPq+wiKoGy2/M7ccjmlvwi58z2xsykkkfNMyIg4xb7EZQQNwB71hcSsB3o75CqQV7/y5lXkXhI/rsGAS7jfEmQ==",
7880
"license": "Apache-2.0"
7881
},
7882
"node_modules/videojs-vtt.js": {
7883
"version": "0.15.5",
7884
"resolved": "https://registry.npmjs.org/videojs-vtt.js/-/videojs-vtt.js-0.15.5.tgz",
7885
"integrity": "sha512-yZbBxvA7QMYn15Lr/ZfhhLPrNpI/RmCSCqgIff57GC2gIrV5YfyzLfLyZMj0NnZSAz8syB4N0nHXpZg9MyrMOQ==",
7886
"license": "Apache-2.0",
7887
"dependencies": {
7888
"global": "^4.3.1"
7889
}
7890
},
7676
7891
"node_modules/w3c-xmlserializer": {
7677
7892
"version": "4.0.0",
7678
7893
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz",
@@ -17,7 +17,8 @@17
"multer": "^1.4.5-lts.1",17
"multer": "^1.4.5-lts.1",18
"node-sqlite3-wasm": "^0.8.10",18
"node-sqlite3-wasm": "^0.8.10",19
"sharp": "^0.34.5",19
"sharp": "^0.34.5",20
"uuid": "^9.0.0"20
"uuid": "^9.0.0",21
"video.js": "^8.23.7"21
},22
},22
"devDependencies": {23
"devDependencies": {23
"jest-environment-jsdom": "^30.3.0",24
"jest-environment-jsdom": "^30.3.0",@@ -496,6 +497,15 @@496
"@babel/core": "^7.0.0-0"497
"@babel/core": "^7.0.0-0"497
}498
}498
},499
},500
"node_modules/@babel/runtime": {501
"version": "7.29.2",502
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",503
"integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",504
"license": "MIT",505
"engines": {506
"node": ">=6.9.0"507
}508
},499
"node_modules/@babel/template": {509
"node_modules/@babel/template": {500
"version": "7.28.6",510
"version": "7.28.6",501
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",511
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",@@ -2037,6 +2047,63 @@2037
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",2047
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",2038
"license": "MIT"2048
"license": "MIT"2039
},2049
},2050
"node_modules/@videojs/http-streaming": {2051
"version": "3.17.4",2052
"resolved": "https://registry.npmjs.org/@videojs/http-streaming/-/http-streaming-3.17.4.tgz",2053
"integrity": "sha512-XAvdG2dolBuV2Fx8bu1kjmQ2D4TonGzZH68Pgv/O9xMSFWdZtITSMFismeQLEAtMmGwze8qNJp3RgV+jStrJqg==",2054
"license": "Apache-2.0",2055
"dependencies": {2056
"@babel/runtime": "^7.12.5",2057
"@videojs/vhs-utils": "^4.1.1",2058
"aes-decrypter": "^4.0.2",2059
"global": "^4.4.0",2060
"m3u8-parser": "^7.2.0",2061
"mpd-parser": "^1.3.1",2062
"mux.js": "7.1.0",2063
"video.js": "^7 || ^8"2064
},2065
"engines": {2066
"node": ">=8",2067
"npm": ">=5"2068
},2069
"peerDependencies": {2070
"video.js": "^8.19.0"2071
}2072
},2073
"node_modules/@videojs/vhs-utils": {2074
"version": "4.1.1",2075
"resolved": "https://registry.npmjs.org/@videojs/vhs-utils/-/vhs-utils-4.1.1.tgz",2076
"integrity": "sha512-5iLX6sR2ownbv4Mtejw6Ax+naosGvoT9kY+gcuHzANyUZZ+4NpeNdKMUhb6ag0acYej1Y7cmr/F2+4PrggMiVA==",2077
"license": "MIT",2078
"dependencies": {2079
"@babel/runtime": "^7.12.5",2080
"global": "^4.4.0"2081
},2082
"engines": {2083
"node": ">=8",2084
"npm": ">=5"2085
}2086
},2087
"node_modules/@videojs/xhr": {2088
"version": "2.7.0",2089
"resolved": "https://registry.npmjs.org/@videojs/xhr/-/xhr-2.7.0.tgz",2090
"integrity": "sha512-giab+EVRanChIupZK7gXjHy90y3nncA2phIOyG3Ne5fvpiMJzvqYwiTOnEVW2S4CoYcuKJkomat7bMXA/UoUZQ==",2091
"license": "MIT",2092
"dependencies": {2093
"@babel/runtime": "^7.5.5",2094
"global": "~4.4.0",2095
"is-function": "^1.0.1"2096
}2097
},2098
"node_modules/@xmldom/xmldom": {2099
"version": "0.8.13",2100
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",2101
"integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",2102
"license": "MIT",2103
"engines": {2104
"node": ">=10.0.0"2105
}2106
},2040
"node_modules/abab": {2107
"node_modules/abab": {2041
"version": "2.0.6",2108
"version": "2.0.6",2042
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",2109
"resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz",@@ -2113,6 +2180,18 @@2113
"node": ">=0.4.0"2180
"node": ">=0.4.0"2114
}2181
}2115
},2182
},2183
"node_modules/aes-decrypter": {2184
"version": "4.0.2",2185
"resolved": "https://registry.npmjs.org/aes-decrypter/-/aes-decrypter-4.0.2.tgz",2186
"integrity": "sha512-lc+/9s6iJvuaRe5qDlMTpCFjnwpkeOXp8qP3oiZ5jsj1MRg+SBVUmmICrhxHvc8OELSmc+fEyyxAuppY6hrWzw==",2187
"license": "Apache-2.0",2188
"dependencies": {2189
"@babel/runtime": "^7.12.5",2190
"@videojs/vhs-utils": "^4.1.1",2191
"global": "^4.4.0",2192
"pkcs7": "^1.0.4"2193
}2194
},2116
"node_modules/agent-base": {2195
"node_modules/agent-base": {2117
"version": "6.0.2",2196
"version": "6.0.2",2118
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",2197
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",@@ -3449,6 +3528,11 @@3449
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"3528
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"3450
}3529
}3451
},3530
},3531
"node_modules/dom-walk": {3532
"version": "0.1.2",3533
"resolved": "https://registry.npmjs.org/dom-walk/-/dom-walk-0.1.2.tgz",3534
"integrity": "sha512-6QvTW9mrGeIegrFXdtQi9pk7O/nSK6lSdXW2eqUspN5LWD7UTji2Fqw5V2YLjBpHEoU9Xl/eUWNpDeZvoyOv2w=="3535
},3452
"node_modules/domexception": {3536
"node_modules/domexception": {3453
"version": "4.0.0",3537
"version": "4.0.0",3454
"resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz",3538
"resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz",@@ -4161,6 +4245,16 @@4161
"url": "https://github.com/sponsors/isaacs"4245
"url": "https://github.com/sponsors/isaacs"4162
}4246
}4163
},4247
},4248
"node_modules/global": {4249
"version": "4.4.0",4250
"resolved": "https://registry.npmjs.org/global/-/global-4.4.0.tgz",4251
"integrity": "sha512-wv/LAoHdRE3BeTGz53FAamhGlPLhlssK45usmGFThIi4XqnBmjKQ16u+RNbP7WvigRZDxUsM0J3gcQ5yicaL0w==",4252
"license": "MIT",4253
"dependencies": {4254
"min-document": "^2.19.0",4255
"process": "^0.11.10"4256
}4257
},4164
"node_modules/gopd": {4258
"node_modules/gopd": {4165
"version": "1.2.0",4259
"version": "1.2.0",4166
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",4260
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",@@ -4488,6 +4582,12 @@4488
"node": ">=8"4582
"node": ">=8"4489
}4583
}4490
},4584
},4585
"node_modules/is-function": {4586
"version": "1.0.2",4587
"resolved": "https://registry.npmjs.org/is-function/-/is-function-1.0.2.tgz",4588
"integrity": "sha512-lw7DUp0aWXYg+CBCN+JKkcE0Q2RayZnSvnZBlwgxHBQhqt5pZNVy4Ri7H9GmmXkdu7LUthszM+Tor1u/2iBcpQ==",4589
"license": "MIT"4590
},4491
"node_modules/is-generator-fn": {4591
"node_modules/is-generator-fn": {4492
"version": "2.1.0",4592
"version": "2.1.0",4493
"resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz",4593
"resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz",@@ -5983,6 +6083,17 @@5983
"yallist": "^3.0.2"6083
"yallist": "^3.0.2"5984
}6084
}5985
},6085
},6086
"node_modules/m3u8-parser": {6087
"version": "7.2.0",6088
"resolved": "https://registry.npmjs.org/m3u8-parser/-/m3u8-parser-7.2.0.tgz",6089
"integrity": "sha512-CRatFqpjVtMiMaKXxNvuI3I++vUumIXVVT/JpCpdU/FynV/ceVw1qpPyyBNindL+JlPMSesx+WX1QJaZEJSaMQ==",6090
"license": "Apache-2.0",6091
"dependencies": {6092
"@babel/runtime": "^7.12.5",6093
"@videojs/vhs-utils": "^4.1.1",6094
"global": "^4.4.0"6095
}6096
},5986
"node_modules/make-dir": {6097
"node_modules/make-dir": {5987
"version": "3.1.0",6098
"version": "3.1.0",5988
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",6099
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",@@ -6113,6 +6224,15 @@6113
"node": ">=6"6224
"node": ">=6"6114
}6225
}6115
},6226
},6227
"node_modules/min-document": {6228
"version": "2.19.2",6229
"resolved": "https://registry.npmjs.org/min-document/-/min-document-2.19.2.tgz",6230
"integrity": "sha512-8S5I8db/uZN8r9HSLFVWPdJCvYOejMcEC82VIzNUc6Zkklf/d1gg2psfE79/vyhWOj4+J8MtwmoOz3TmvaGu5A==",6231
"license": "MIT",6232
"dependencies": {6233
"dom-walk": "^0.1.0"6234
}6235
},6116
"node_modules/minimatch": {6236
"node_modules/minimatch": {6117
"version": "3.1.5",6237
"version": "3.1.5",6118
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",6238
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",@@ -6186,6 +6306,21 @@6186
"mkdirp": "bin/cmd.js"6306
"mkdirp": "bin/cmd.js"6187
}6307
}6188
},6308
},6309
"node_modules/mpd-parser": {6310
"version": "1.3.1",6311
"resolved": "https://registry.npmjs.org/mpd-parser/-/mpd-parser-1.3.1.tgz",6312
"integrity": "sha512-1FuyEWI5k2HcmhS1HkKnUAQV7yFPfXPht2DnRRGtoiiAAW+ESTbtEXIDpRkwdU+XyrQuwrIym7UkoPKsZ0SyFw==",6313
"license": "Apache-2.0",6314
"dependencies": {6315
"@babel/runtime": "^7.12.5",6316
"@videojs/vhs-utils": "^4.0.0",6317
"@xmldom/xmldom": "^0.8.3",6318
"global": "^4.4.0"6319
},6320
"bin": {6321
"mpd-to-m3u8-json": "bin/parse.js"6322
}6323
},6189
"node_modules/ms": {6324
"node_modules/ms": {6190
"version": "2.0.0",6325
"version": "2.0.0",6191
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",6326
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",@@ -6211,6 +6346,23 @@6211
"node": ">= 6.0.0"6346
"node": ">= 6.0.0"6212
}6347
}6213
},6348
},6349
"node_modules/mux.js": {6350
"version": "7.1.0",6351
"resolved": "https://registry.npmjs.org/mux.js/-/mux.js-7.1.0.tgz",6352
"integrity": "sha512-NTxawK/BBELJrYsZThEulyUMDVlLizKdxyAsMuzoCD1eFj97BVaA8D/CvKsKu6FOLYkFojN5CbM9h++ZTZtknA==",6353
"license": "Apache-2.0",6354
"dependencies": {6355
"@babel/runtime": "^7.11.2",6356
"global": "^4.4.0"6357
},6358
"bin": {6359
"muxjs-transmux": "bin/transmux.js"6360
},6361
"engines": {6362
"node": ">=8",6363
"npm": ">=5"6364
}6365
},6214
"node_modules/natural-compare": {6366
"node_modules/natural-compare": {6215
"version": "1.4.0",6367
"version": "1.4.0",6216
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",6368
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",@@ -6574,6 +6726,18 @@6574
"node": ">= 6"6726
"node": ">= 6"6575
}6727
}6576
},6728
},6729
"node_modules/pkcs7": {6730
"version": "1.0.4",6731
"resolved": "https://registry.npmjs.org/pkcs7/-/pkcs7-1.0.4.tgz",6732
"integrity": "sha512-afRERtHn54AlwaF2/+LFszyAANTCggGilmcmILUzEjvs3XgFZT+xE6+QWQcAGmu4xajy+Xtj7acLOPdx5/eXWQ==",6733
"license": "Apache-2.0",6734
"dependencies": {6735
"@babel/runtime": "^7.5.5"6736
},6737
"bin": {6738
"pkcs7": "bin/cli.js"6739
}6740
},6577
"node_modules/pkg-dir": {6741
"node_modules/pkg-dir": {6578
"version": "4.2.0",6742
"version": "4.2.0",6579
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",6743
"resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",@@ -7673,6 +7837,57 @@7673
"node": ">= 0.8"7837
"node": ">= 0.8"7674
}7838
}7675
},7839
},7840
"node_modules/video.js": {7841
"version": "8.23.7",7842
"resolved": "https://registry.npmjs.org/video.js/-/video.js-8.23.7.tgz",7843
"integrity": "sha512-cG4HOygYt+Z8j6Sf5DuK6OgEOoM+g9oGP6vpqoZRaD13aHE4PMITbyjJUXZcIQbgB0wJEadBRaVm5lJIzo2jAA==",7844
"license": "Apache-2.0",7845
"dependencies": {7846
"@babel/runtime": "^7.28.4",7847
"@videojs/http-streaming": "^3.17.3",7848
"@videojs/vhs-utils": "^4.1.1",7849
"@videojs/xhr": "2.7.0",7850
"aes-decrypter": "^4.0.2",7851
"global": "4.4.0",7852
"m3u8-parser": "^7.2.0",7853
"mpd-parser": "^1.3.1",7854
"mux.js": "^7.0.1",7855
"videojs-contrib-quality-levels": "4.1.0",7856
"videojs-font": "4.2.0",7857
"videojs-vtt.js": "0.15.5"7858
}7859
},7860
"node_modules/videojs-contrib-quality-levels": {7861
"version": "4.1.0",7862
"resolved": "https://registry.npmjs.org/videojs-contrib-quality-levels/-/videojs-contrib-quality-levels-4.1.0.tgz",7863
"integrity": "sha512-TfrXJJg1Bv4t6TOCMEVMwF/CoS8iENYsWNKip8zfhB5kTcegiFYezEA0eHAJPU64ZC8NQbxQgOwAsYU8VXbOWA==",7864
"license": "Apache-2.0",7865
"dependencies": {7866
"global": "^4.4.0"7867
},7868
"engines": {7869
"node": ">=16",7870
"npm": ">=8"7871
},7872
"peerDependencies": {7873
"video.js": "^8"7874
}7875
},7876
"node_modules/videojs-font": {7877
"version": "4.2.0",7878
"resolved": "https://registry.npmjs.org/videojs-font/-/videojs-font-4.2.0.tgz",7879
"integrity": "sha512-YPq+wiKoGy2/M7ccjmlvwi58z2xsykkkfNMyIg4xb7EZQQNwB71hcSsB3o75CqQV7/y5lXkXhI/rsGAS7jfEmQ==",7880
"license": "Apache-2.0"7881
},7882
"node_modules/videojs-vtt.js": {7883
"version": "0.15.5",7884
"resolved": "https://registry.npmjs.org/videojs-vtt.js/-/videojs-vtt.js-0.15.5.tgz",7885
"integrity": "sha512-yZbBxvA7QMYn15Lr/ZfhhLPrNpI/RmCSCqgIff57GC2gIrV5YfyzLfLyZMj0NnZSAz8syB4N0nHXpZg9MyrMOQ==",7886
"license": "Apache-2.0",7887
"dependencies": {7888
"global": "^4.3.1"7889
}7890
},7676
"node_modules/w3c-xmlserializer": {7891
"node_modules/w3c-xmlserializer": {7677
"version": "4.0.0",7892
"version": "4.0.0",7678
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz",7893
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz",@@ -17,7 +17,8 @@
17
17
"multer": "^1.4.5-lts.1",
18
18
"node-sqlite3-wasm": "^0.8.10",
19
19
"sharp": "^0.34.5",
20
"uuid": "^9.0.0"
20
"uuid": "^9.0.0",
21
"video.js": "^8.23.7"
21
22
},
22
23
"jest": {
23
24
"testEnvironment": "node",
@@ -17,7 +17,8 @@17
"multer": "^1.4.5-lts.1",17
"multer": "^1.4.5-lts.1",18
"node-sqlite3-wasm": "^0.8.10",18
"node-sqlite3-wasm": "^0.8.10",19
"sharp": "^0.34.5",19
"sharp": "^0.34.5",20
"uuid": "^9.0.0"20
"uuid": "^9.0.0",21
"video.js": "^8.23.7"21
},22
},22
"jest": {23
"jest": {23
"testEnvironment": "node",24
"testEnvironment": "node",@@ -48,6 +48,8 @@ const STATE = {
48
48
49
49
// Preview overlay state
50
50
previewObjectUrl: null,
51
previewCleanup: null,
52
previewDownloadAction: null,
51
53
previewSourceEl: null, // SVG element that triggered the preview
52
54
previewClosing: false, // guard to prevent double-close during animation
53
55
previewExpandState: null, // in-place expanded tile preview state
@@ -61,6 +63,7 @@ const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
61
63
const MOBILE_LONG_PRESS_MS = 420;
62
64
const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
63
65
const THUMB_OBSERVER_ROOT_MARGIN = '120px';
66
let videoJsLoaderPromise = null;
64
67
65
68
// ───────────────────────────────────────────────────────────────────────────
66
69
// CRYPTO HELPERS (Web Crypto API)
@@ -667,6 +670,8 @@ function showAuthOverlay (setupMode = false)
667
670
if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
668
671
document.getElementById('app').classList.add('hidden');
669
672
const overlay = document.getElementById('auth-overlay');
673
const usernameInput = document.getElementById('auth-username');
674
const passwordInput = document.getElementById('auth-password');
670
675
overlay.classList.remove('hidden');
671
676
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
672
677
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
@@ -674,9 +679,11 @@ function showAuthOverlay (setupMode = false)
674
679
submitBtn.disabled = false;
675
680
submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
676
681
document.getElementById('auth-error').classList.add('hidden');
677
document.getElementById('auth-username').value = '';
678
document.getElementById('auth-password').value = '';
679
document.getElementById('auth-username').focus();
682
usernameInput.value = '';
683
passwordInput.value = '';
684
usernameInput.autocomplete = 'username';
685
passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password';
686
usernameInput.focus();
680
687
document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
681
688
}
682
689
@@ -2092,11 +2099,130 @@ function highlightCode (raw, lang)
2092
2099
2093
2100
function clearPreviewObjectUrl ()
2094
2101
{
2102
if (typeof STATE.previewCleanup === 'function')
2103
{
2104
try { STATE.previewCleanup(); } catch { /* ignore */ }
2105
}
2106
STATE.previewCleanup = null;
2107
STATE.previewDownloadAction = null;
2095
2108
if (!STATE.previewObjectUrl) return;
2096
URL.revokeObjectURL(STATE.previewObjectUrl);
2109
if (String(STATE.previewObjectUrl).startsWith('blob:'))
2110
{
2111
URL.revokeObjectURL(STATE.previewObjectUrl);
2112
}
2097
2113
STATE.previewObjectUrl = null;
2098
2114
}
2099
2115
2116
function ensureStylesheet (id, href)
2117
{
2118
let link = document.getElementById(id);
2119
if (link) return Promise.resolve(link);
2120
2121
link = document.createElement('link');
2122
link.id = id;
2123
link.rel = 'stylesheet';
2124
link.href = href;
2125
2126
return new Promise((resolve, reject) =>
2127
{
2128
link.addEventListener('load', () => resolve(link), { once: true });
2129
link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });
2130
document.head.appendChild(link);
2131
});
2132
}
2133
2134
function ensureScript (id, src)
2135
{
2136
let script = document.getElementById(id);
2137
if (script && window.videojs) return Promise.resolve(window.videojs);
2138
2139
if (!script)
2140
{
2141
script = document.createElement('script');
2142
script.id = id;
2143
script.src = src;
2144
}
2145
2146
return new Promise((resolve, reject) =>
2147
{
2148
script.addEventListener('load', () => resolve(window.videojs), { once: true });
2149
script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });
2150
if (!script.isConnected) document.head.appendChild(script);
2151
});
2152
}
2153
2154
async function ensureVideoJsLoaded ()
2155
{
2156
if (window.videojs) return window.videojs;
2157
if (!videoJsLoaderPromise)
2158
{
2159
videoJsLoaderPromise = Promise.all([
2160
ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),
2161
ensureScript('videojs-script', '/vendor/video.js/video.min.js'),
2162
]).then(() => window.videojs);
2163
}
2164
return videoJsLoaderPromise;
2165
}
2166
2167
async function createVideoStreamSessionForItem (item)
2168
{
2169
return api('POST', '/files/video-stream', { filePath: item.path });
2170
}
2171
2172
async function preparePreviewDownload (item)
2173
{
2174
const blob = await fetchFileBlob(item);
2175
if (!blob)
2176
{
2177
toast('Download failed.', 'err');
2178
return;
2179
}
2180
2181
const objectUrl = URL.createObjectURL(blob);
2182
triggerDownload(item.name, objectUrl);
2183
setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
2184
}
2185
2186
async function renderStreamedVideoPreview (item, targetEl)
2187
{
2188
const videojs = await ensureVideoJsLoaded();
2189
const session = await createVideoStreamSessionForItem(item);
2190
2191
if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2192
{
2193
toast('This video has subtitle tracks, but none are compatible with web playback.', 'err');
2194
}
2195
2196
STATE.previewDownloadAction = () => preparePreviewDownload(item);
2197
2198
const video = document.createElement('video');
2199
video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
2200
video.controls = true;
2201
video.preload = 'auto';
2202
video.playsInline = true;
2203
targetEl.appendChild(video);
2204
2205
const player = videojs(video, {
2206
controls: true,
2207
fluid: true,
2208
responsive: true,
2209
preload: 'auto',
2210
sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2211
tracks: (session.subtitleTracks || []).map((track) => ({
2212
kind: 'subtitles',
2213
src: track.src,
2214
srclang: track.language || 'und',
2215
label: track.label,
2216
default: !!track.default,
2217
})),
2218
});
2219
2220
STATE.previewCleanup = () =>
2221
{
2222
try { player.dispose(); } catch { /* ignore */ }
2223
};
2224
}
2225
2100
2226
function fileAccentColor (name)
2101
2227
{
2102
2228
const ext = extOf(name || '');
@@ -2211,9 +2337,14 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2211
2337
dlBtn.className = 'preview-expand-download';
2212
2338
dlBtn.type = 'button';
2213
2339
dlBtn.textContent = 'Download';
2214
dlBtn.addEventListener('click', (e) =>
2340
dlBtn.addEventListener('click', async (e) =>
2215
2341
{
2216
2342
e.stopPropagation();
2343
if (STATE.previewDownloadAction)
2344
{
2345
await STATE.previewDownloadAction();
2346
return;
2347
}
2217
2348
if (!STATE.previewObjectUrl)
2218
2349
{
2219
2350
toast('Preview still loading.', 'err');
@@ -2232,6 +2363,11 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2232
2363
openShareModal(item);
2233
2364
});
2234
2365
2366
const actionsEl = document.createElement('div');
2367
actionsEl.className = 'preview-expand-actions';
2368
actionsEl.appendChild(shareBtn);
2369
actionsEl.appendChild(dlBtn);
2370
2235
2371
iconEl.innerHTML = '';
2236
2372
2237
2373
if (originalIconSvg)
@@ -2252,8 +2388,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2252
2388
2253
2389
tileEl.insertBefore(titleEl, tileEl.firstChild);
2254
2390
tileEl.appendChild(closeBtn);
2255
tileEl.appendChild(dlBtn);
2256
tileEl.appendChild(shareBtn);
2391
tileEl.appendChild(actionsEl);
2257
2392
2258
2393
STATE.previewExpandState = {
2259
2394
item,
@@ -2478,6 +2613,14 @@ async function downloadOrView (item, sourceSvgEl = null)
2478
2613
STATE.previewSourceEl = sourceSvgEl;
2479
2614
const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>
2480
2615
{
2616
if (VIDEO_EXTS.has(extOf(item.name)))
2617
{
2618
clearPreviewObjectUrl();
2619
previewMount.innerHTML = '';
2620
await renderStreamedVideoPreview(item, previewMount);
2621
return;
2622
}
2623
2481
2624
const blob = await fetchFileBlob(item);
2482
2625
if (!blob) throw new Error('Download failed');
2483
2626
@@ -3361,13 +3504,16 @@ async function loadOneThumbnail (iconEl)
3361
3504
else if (kind === 'image')
3362
3505
{
3363
3506
const ext = extOf(item.name || '');
3364
const useDirectSvg =
3365
ext === 'svg' &&
3366
typeof item.size === 'number' &&
3367
item.size > 0 &&
3368
item.size <= MAX_DIRECT_SVG_THUMB_BYTES;
3369
3370
const url = useDirectSvg
3507
const useDirectSource =
3508
ext === 'ico' ||
3509
(
3510
ext === 'svg' &&
3511
typeof item.size === 'number' &&
3512
item.size > 0 &&
3513
item.size <= MAX_DIRECT_SVG_THUMB_BYTES
3514
);
3515
3516
const url = useDirectSource
3371
3517
? `/api/files/download?file=${encodeURIComponent(filePath)}`
3372
3518
: `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;
3373
3519
@@ -3385,7 +3531,7 @@ async function loadOneThumbnail (iconEl)
3385
3531
return;
3386
3532
}
3387
3533
3388
if (!useDirectSvg && res.status === 404)
3534
if (!useDirectSource && res.status === 404)
3389
3535
{
3390
3536
setThumbnailPending(iconEl, true);
3391
3537
return;
@@ -48,6 +48,8 @@ const STATE = {48
48
49
// Preview overlay state49
// Preview overlay state50
previewObjectUrl: null,50
previewObjectUrl: null,51
previewCleanup: null,52
previewDownloadAction: null,51
previewSourceEl: null, // SVG element that triggered the preview53
previewSourceEl: null, // SVG element that triggered the preview52
previewClosing: false, // guard to prevent double-close during animation54
previewClosing: false, // guard to prevent double-close during animation53
previewExpandState: null, // in-place expanded tile preview state55
previewExpandState: null, // in-place expanded tile preview state@@ -61,6 +63,7 @@ const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';61
const MOBILE_LONG_PRESS_MS = 420;63
const MOBILE_LONG_PRESS_MS = 420;62
const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;64
const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;63
const THUMB_OBSERVER_ROOT_MARGIN = '120px';65
const THUMB_OBSERVER_ROOT_MARGIN = '120px';66
let videoJsLoaderPromise = null;64
67
65
// ───────────────────────────────────────────────────────────────────────────68
// ───────────────────────────────────────────────────────────────────────────66
// CRYPTO HELPERS (Web Crypto API)69
// CRYPTO HELPERS (Web Crypto API)@@ -667,6 +670,8 @@ function showAuthOverlay (setupMode = false)667
if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;670
if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;668
document.getElementById('app').classList.add('hidden');671
document.getElementById('app').classList.add('hidden');669
const overlay = document.getElementById('auth-overlay');672
const overlay = document.getElementById('auth-overlay');673
const usernameInput = document.getElementById('auth-username');674
const passwordInput = document.getElementById('auth-password');670
overlay.classList.remove('hidden');675
overlay.classList.remove('hidden');671
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';676
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';672
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);677
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);@@ -674,9 +679,11 @@ function showAuthOverlay (setupMode = false)674
submitBtn.disabled = false;679
submitBtn.disabled = false;675
submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';680
submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';676
document.getElementById('auth-error').classList.add('hidden');681
document.getElementById('auth-error').classList.add('hidden');677
document.getElementById('auth-username').value = '';682
usernameInput.value = '';678
document.getElementById('auth-password').value = '';683
passwordInput.value = '';679
document.getElementById('auth-username').focus();684
usernameInput.autocomplete = 'username';685
passwordInput.autocomplete = setupMode ? 'new-password' : 'current-password';686
usernameInput.focus();680
document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';687
document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';681
}688
}682
689
@@ -2092,11 +2099,130 @@ function highlightCode (raw, lang)2092
2099
2093
function clearPreviewObjectUrl ()2100
function clearPreviewObjectUrl ()2094
{2101
{2102
if (typeof STATE.previewCleanup === 'function')2103
{2104
try { STATE.previewCleanup(); } catch { /* ignore */ }2105
}2106
STATE.previewCleanup = null;2107
STATE.previewDownloadAction = null;2095
if (!STATE.previewObjectUrl) return;2108
if (!STATE.previewObjectUrl) return;2096
URL.revokeObjectURL(STATE.previewObjectUrl);2109
if (String(STATE.previewObjectUrl).startsWith('blob:'))2110
{2111
URL.revokeObjectURL(STATE.previewObjectUrl);2112
}2097
STATE.previewObjectUrl = null;2113
STATE.previewObjectUrl = null;2098
}2114
}2099
2115
2116
function ensureStylesheet (id, href)2117
{2118
let link = document.getElementById(id);2119
if (link) return Promise.resolve(link);2120
2121
link = document.createElement('link');2122
link.id = id;2123
link.rel = 'stylesheet';2124
link.href = href;2125
2126
return new Promise((resolve, reject) =>2127
{2128
link.addEventListener('load', () => resolve(link), { once: true });2129
link.addEventListener('error', () => reject(new Error('Failed to load video player styles.')), { once: true });2130
document.head.appendChild(link);2131
});2132
}2133
2134
function ensureScript (id, src)2135
{2136
let script = document.getElementById(id);2137
if (script && window.videojs) return Promise.resolve(window.videojs);2138
2139
if (!script)2140
{2141
script = document.createElement('script');2142
script.id = id;2143
script.src = src;2144
}2145
2146
return new Promise((resolve, reject) =>2147
{2148
script.addEventListener('load', () => resolve(window.videojs), { once: true });2149
script.addEventListener('error', () => reject(new Error('Failed to load video player script.')), { once: true });2150
if (!script.isConnected) document.head.appendChild(script);2151
});2152
}2153
2154
async function ensureVideoJsLoaded ()2155
{2156
if (window.videojs) return window.videojs;2157
if (!videoJsLoaderPromise)2158
{2159
videoJsLoaderPromise = Promise.all([2160
ensureStylesheet('videojs-styles', '/vendor/video.js/video-js.css'),2161
ensureScript('videojs-script', '/vendor/video.js/video.min.js'),2162
]).then(() => window.videojs);2163
}2164
return videoJsLoaderPromise;2165
}2166
2167
async function createVideoStreamSessionForItem (item)2168
{2169
return api('POST', '/files/video-stream', { filePath: item.path });2170
}2171
2172
async function preparePreviewDownload (item)2173
{2174
const blob = await fetchFileBlob(item);2175
if (!blob)2176
{2177
toast('Download failed.', 'err');2178
return;2179
}2180
2181
const objectUrl = URL.createObjectURL(blob);2182
triggerDownload(item.name, objectUrl);2183
setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);2184
}2185
2186
async function renderStreamedVideoPreview (item, targetEl)2187
{2188
const videojs = await ensureVideoJsLoaded();2189
const session = await createVideoStreamSessionForItem(item);2190
2191
if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)2192
{2193
toast('This video has subtitle tracks, but none are compatible with web playback.', 'err');2194
}2195
2196
STATE.previewDownloadAction = () => preparePreviewDownload(item);2197
2198
const video = document.createElement('video');2199
video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';2200
video.controls = true;2201
video.preload = 'auto';2202
video.playsInline = true;2203
targetEl.appendChild(video);2204
2205
const player = videojs(video, {2206
controls: true,2207
fluid: true,2208
responsive: true,2209
preload: 'auto',2210
sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],2211
tracks: (session.subtitleTracks || []).map((track) => ({2212
kind: 'subtitles',2213
src: track.src,2214
srclang: track.language || 'und',2215
label: track.label,2216
default: !!track.default,2217
})),2218
});2219
2220
STATE.previewCleanup = () =>2221
{2222
try { player.dispose(); } catch { /* ignore */ }2223
};2224
}2225
2100
function fileAccentColor (name)2226
function fileAccentColor (name)2101
{2227
{2102
const ext = extOf(name || '');2228
const ext = extOf(name || '');@@ -2211,9 +2337,14 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo2211
dlBtn.className = 'preview-expand-download';2337
dlBtn.className = 'preview-expand-download';2212
dlBtn.type = 'button';2338
dlBtn.type = 'button';2213
dlBtn.textContent = 'Download';2339
dlBtn.textContent = 'Download';2214
dlBtn.addEventListener('click', (e) =>2340
dlBtn.addEventListener('click', async (e) =>2215
{2341
{2216
e.stopPropagation();2342
e.stopPropagation();2343
if (STATE.previewDownloadAction)2344
{2345
await STATE.previewDownloadAction();2346
return;2347
}2217
if (!STATE.previewObjectUrl)2348
if (!STATE.previewObjectUrl)2218
{2349
{2219
toast('Preview still loading.', 'err');2350
toast('Preview still loading.', 'err');@@ -2232,6 +2363,11 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo2232
openShareModal(item);2363
openShareModal(item);2233
});2364
});2234
2365
2366
const actionsEl = document.createElement('div');2367
actionsEl.className = 'preview-expand-actions';2368
actionsEl.appendChild(shareBtn);2369
actionsEl.appendChild(dlBtn);2370
2235
iconEl.innerHTML = '';2371
iconEl.innerHTML = '';2236
2372
2237
if (originalIconSvg)2373
if (originalIconSvg)@@ -2252,8 +2388,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo2252
2388
2253
tileEl.insertBefore(titleEl, tileEl.firstChild);2389
tileEl.insertBefore(titleEl, tileEl.firstChild);2254
tileEl.appendChild(closeBtn);2390
tileEl.appendChild(closeBtn);2255
tileEl.appendChild(dlBtn);2391
tileEl.appendChild(actionsEl);2256
tileEl.appendChild(shareBtn);2257
2392
2258
STATE.previewExpandState = {2393
STATE.previewExpandState = {2259
item,2394
item,@@ -2478,6 +2613,14 @@ async function downloadOrView (item, sourceSvgEl = null)2478
STATE.previewSourceEl = sourceSvgEl;2613
STATE.previewSourceEl = sourceSvgEl;2479
const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>2614
const expanded = await openExpandedTilePreview(item, sourceTileEl, sourceSvgEl, async (previewMount) =>2480
{2615
{2616
if (VIDEO_EXTS.has(extOf(item.name)))2617
{2618
clearPreviewObjectUrl();2619
previewMount.innerHTML = '';2620
await renderStreamedVideoPreview(item, previewMount);2621
return;2622
}2623
2481
const blob = await fetchFileBlob(item);2624
const blob = await fetchFileBlob(item);2482
if (!blob) throw new Error('Download failed');2625
if (!blob) throw new Error('Download failed');2483
2626
@@ -3361,13 +3504,16 @@ async function loadOneThumbnail (iconEl)3361
else if (kind === 'image')3504
else if (kind === 'image')3362
{3505
{3363
const ext = extOf(item.name || '');3506
const ext = extOf(item.name || '');3364
const useDirectSvg =3507
const useDirectSource =3365
ext === 'svg' &&3508
ext === 'ico' ||3366
typeof item.size === 'number' &&3509
(3367
item.size > 0 &&3510
ext === 'svg' &&3368
item.size <= MAX_DIRECT_SVG_THUMB_BYTES;3511
typeof item.size === 'number' &&3369
3512
item.size > 0 &&3370
const url = useDirectSvg3513
item.size <= MAX_DIRECT_SVG_THUMB_BYTES3514
);3515
3516
const url = useDirectSource3371
? `/api/files/download?file=${encodeURIComponent(filePath)}`3517
? `/api/files/download?file=${encodeURIComponent(filePath)}`3372
: `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;3518
: `/api/files/thumbnail?file=${encodeURIComponent(filePath)}`;3373
3519
@@ -3385,7 +3531,7 @@ async function loadOneThumbnail (iconEl)3385
return;3531
return;3386
}3532
}3387
3533
3388
if (!useDirectSvg && res.status === 404)3534
if (!useDirectSource && res.status === 404)3389
{3535
{3390
setThumbnailPending(iconEl, true);3536
setThumbnailPending(iconEl, true);3391
return;3537
return;@@ -128,7 +128,7 @@
128
128
align-items: center;
129
129
justify-content: center;
130
130
overflow: auto;
131
padding: 1rem;
131
padding: 1rem 1rem 0.75rem;
132
132
box-sizing: border-box;
133
133
}
134
134
@@ -164,6 +164,16 @@
164
164
object-fit: contain;
165
165
}
166
166
167
.file-item.file-item--preview .icon .preview-video-js {
168
width: 100%;
169
height: 100%;
170
background: transparent;
171
}
172
173
.file-item.file-item--preview .icon .preview-video-js .vjs-tech {
174
object-fit: contain;
175
}
176
167
177
.file-item.file-item--preview .icon .preview-frame {
168
178
width: 100%;
169
179
height: 100%;
@@ -229,11 +239,19 @@
229
239
background: rgba(255, 255, 255, 0.14);
230
240
}
231
241
232
/* Download button — bottom-right corner */
233
.preview-expand-download {
234
position: absolute;
235
bottom: 14px;
236
right: 14px;
242
/* Action row below the preview content */
243
.preview-expand-actions {
244
display: flex;
245
justify-content: flex-end;
246
gap: 0.65rem;
247
padding: 0 1rem 1rem;
248
border-top: 1px solid rgba(46, 50, 71, 0.9);
249
background: linear-gradient(180deg, rgba(26, 29, 39, 0) 0%, rgba(26, 29, 39, 0.92) 42%);
250
flex-shrink: 0;
251
}
252
253
.preview-expand-download,
254
.preview-expand-share {
237
255
background: var(--accent, #5b7fff);
238
256
color: #fff;
239
257
border: none;
@@ -241,7 +259,6 @@
241
259
padding: 7px 18px;
242
260
cursor: pointer;
243
261
font-size: 0.9rem;
244
z-index: 10001;
245
262
transition: opacity 0.15s ease;
246
263
flex-shrink: 0;
247
264
}
@@ -250,27 +267,31 @@
250
267
opacity: 0.85;
251
268
}
252
269
253
/* Share button — next to download button */
254
270
.preview-expand-share {
255
position: absolute;
256
bottom: 14px;
257
right: 112px;
258
271
background: rgba(20, 25, 40, 0.84);
259
272
color: #fff;
260
273
border: 1px solid rgba(255, 255, 255, 0.18);
261
274
border-radius: 6px;
262
275
padding: 7px 14px;
263
cursor: pointer;
264
font-size: 0.9rem;
265
z-index: 10001;
266
transition: opacity 0.15s ease;
267
flex-shrink: 0;
268
276
}
269
277
270
278
.preview-expand-share:hover {
271
279
opacity: 0.85;
272
280
}
273
281
282
@media (max-width: 700px) {
283
.preview-expand-actions {
284
justify-content: stretch;
285
padding: 0 0.75rem 0.75rem;
286
}
287
288
.preview-expand-download,
289
.preview-expand-share {
290
flex: 1;
291
justify-content: center;
292
}
293
}
294
274
295
/* Spinner shown inside the expanded tile while content is loading */
275
296
.preview-loading-spinner {
276
297
width: 40px;
@@ -128,7 +128,7 @@128
align-items: center;
128
align-items: center;
129
justify-content: center;
129
justify-content: center;
130
overflow: auto;
130
overflow: auto;
131
padding: 1rem;
131
padding: 1rem 1rem 0.75rem;
132
box-sizing: border-box;
132
box-sizing: border-box;
133
}
133
}
134
134
@@ -164,6 +164,16 @@164
object-fit: contain;
164
object-fit: contain;
165
}
165
}
166
166
167
.file-item.file-item--preview .icon .preview-video-js {
168
width: 100%;
169
height: 100%;
170
background: transparent;
171
}
172
173
.file-item.file-item--preview .icon .preview-video-js .vjs-tech {
174
object-fit: contain;
175
}
176
167
.file-item.file-item--preview .icon .preview-frame {
177
.file-item.file-item--preview .icon .preview-frame {
168
width: 100%;
178
width: 100%;
169
height: 100%;
179
height: 100%;
@@ -229,11 +239,19 @@229
background: rgba(255, 255, 255, 0.14);
239
background: rgba(255, 255, 255, 0.14);
230
}
240
}
231
241
232
/* Download button — bottom-right corner */
242
/* Action row below the preview content */
233
.preview-expand-download {
243
.preview-expand-actions {
234
position: absolute;
244
display: flex;
235
bottom: 14px;
245
justify-content: flex-end;
236
right: 14px;
246
gap: 0.65rem;
247
padding: 0 1rem 1rem;
248
border-top: 1px solid rgba(46, 50, 71, 0.9);
249
background: linear-gradient(180deg, rgba(26, 29, 39, 0) 0%, rgba(26, 29, 39, 0.92) 42%);
250
flex-shrink: 0;
251
}
252
253
.preview-expand-download,
254
.preview-expand-share {
237
background: var(--accent, #5b7fff);
255
background: var(--accent, #5b7fff);
238
color: #fff;
256
color: #fff;
239
border: none;
257
border: none;
@@ -241,7 +259,6 @@241
padding: 7px 18px;
259
padding: 7px 18px;
242
cursor: pointer;
260
cursor: pointer;
243
font-size: 0.9rem;
261
font-size: 0.9rem;
244
z-index: 10001;
245
transition: opacity 0.15s ease;
262
transition: opacity 0.15s ease;
246
flex-shrink: 0;
263
flex-shrink: 0;
247
}
264
}
@@ -250,27 +267,31 @@250
opacity: 0.85;
267
opacity: 0.85;
251
}
268
}
252
269
253
/* Share button — next to download button */
254
.preview-expand-share {
270
.preview-expand-share {
255
position: absolute;
256
bottom: 14px;
257
right: 112px;
258
background: rgba(20, 25, 40, 0.84);
271
background: rgba(20, 25, 40, 0.84);
259
color: #fff;
272
color: #fff;
260
border: 1px solid rgba(255, 255, 255, 0.18);
273
border: 1px solid rgba(255, 255, 255, 0.18);
261
border-radius: 6px;
274
border-radius: 6px;
262
padding: 7px 14px;
275
padding: 7px 14px;
263
cursor: pointer;
264
font-size: 0.9rem;
265
z-index: 10001;
266
transition: opacity 0.15s ease;
267
flex-shrink: 0;
268
}
276
}
269
277
270
.preview-expand-share:hover {
278
.preview-expand-share:hover {
271
opacity: 0.85;
279
opacity: 0.85;
272
}
280
}
273
281
282
@media (max-width: 700px) {
283
.preview-expand-actions {
284
justify-content: stretch;
285
padding: 0 0.75rem 0.75rem;
286
}
287
288
.preview-expand-download,
289
.preview-expand-share {
290
flex: 1;
291
justify-content: center;
292
}
293
}
294
274
/* Spinner shown inside the expanded tile while content is loading */
295
/* Spinner shown inside the expanded tile while content is loading */
275
.preview-loading-spinner {
296
.preview-loading-spinner {
276
width: 40px;
297
width: 40px;
@@ -22,11 +22,11 @@
22
22
<form id="auth-form" autocomplete="off">
23
23
<label>
24
24
Username
25
<input id="auth-username" type="text" autocomplete="off" required />
25
<input id="auth-username" type="text" autocomplete="username" required />
26
26
</label>
27
27
<label>
28
28
Password
29
<input id="auth-password" type="password" autocomplete="new-password" required />
29
<input id="auth-password" type="password" autocomplete="current-password" required />
30
30
</label>
31
31
<p id="auth-error" class="error hidden"></p>
32
32
<button type="submit" id="auth-submit">Sign In</button>
@@ -175,7 +175,7 @@
175
175
<form id="user-form">
176
176
<label>Username<input id="user-username" type="text" required /></label>
177
177
<label id="user-password-label">
178
Password<input id="user-password" type="password" placeholder="Min 8 characters" />
178
Password<input id="user-password" type="password" placeholder="Min 8 characters" autocomplete="new-password" />
179
179
</label>
180
180
<label class="checkbox-label">
181
181
<input id="user-is-admin" type="checkbox" />
@@ -22,11 +22,11 @@22
<form id="auth-form" autocomplete="off">22
<form id="auth-form" autocomplete="off">23
<label>23
<label>24
Username24
Username25
<input id="auth-username" type="text" autocomplete="off" required />25
<input id="auth-username" type="text" autocomplete="username" required />26
</label>26
</label>27
<label>27
<label>28
Password28
Password29
<input id="auth-password" type="password" autocomplete="new-password" required />29
<input id="auth-password" type="password" autocomplete="current-password" required />30
</label>30
</label>31
<p id="auth-error" class="error hidden"></p>31
<p id="auth-error" class="error hidden"></p>32
<button type="submit" id="auth-submit">Sign In</button>32
<button type="submit" id="auth-submit">Sign In</button>@@ -175,7 +175,7 @@175
<form id="user-form">175
<form id="user-form">176
<label>Username<input id="user-username" type="text" required /></label>176
<label>Username<input id="user-username" type="text" required /></label>177
<label id="user-password-label">177
<label id="user-password-label">178
Password<input id="user-password" type="password" placeholder="Min 8 characters" />178
Password<input id="user-password" type="password" placeholder="Min 8 characters" autocomplete="new-password" />179
</label>179
</label>180
<label class="checkbox-label">180
<label class="checkbox-label">181
<input id="user-is-admin" type="checkbox" />181
<input id="user-is-admin" type="checkbox" />@@ -17,6 +17,7 @@ const shareRoutes = require('./routes/share');
17
17
const app = express();
18
18
19
19
app.use(express.json({ limit: '50mb' }));
20
app.use('/vendor/video.js', express.static(path.join(__dirname, '../node_modules/video.js/dist')));
20
21
app.use(express.static(path.join(__dirname, '../public')));
21
22
22
23
app.use('/api/auth', authRoutes);
@@ -17,6 +17,7 @@ const shareRoutes = require('./routes/share');17
const app = express();17
const app = express();18
18
19
app.use(express.json({ limit: '50mb' }));19
app.use(express.json({ limit: '50mb' }));20
app.use('/vendor/video.js', express.static(path.join(__dirname, '../node_modules/video.js/dist')));20
app.use(express.static(path.join(__dirname, '../public')));21
app.use(express.static(path.join(__dirname, '../public')));21
22
22
app.use('/api/auth', authRoutes);23
app.use('/api/auth', authRoutes);@@ -12,6 +12,7 @@ const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('.
12
12
const { requireAuth } = require('../auth');
13
13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14
14
const { buildZip } = require('./share');
15
const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream');
15
16
16
17
// ---------------------------------------------------------------------------
17
18
// Multer storage — files are staged into temporary files and only promoted
@@ -623,6 +624,62 @@ router.get('/download', requireAuth, (req, res) =>
623
624
res.download(file, path.basename(file));
624
625
});
625
626
627
// ---------------------------------------------------------------------------
628
// POST /api/files/video-stream
629
// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
630
// ---------------------------------------------------------------------------
631
router.post('/video-stream', requireAuth, async (req, res, next) =>
632
{
633
try
634
{
635
const filePath = String(req.body?.filePath || '').trim();
636
if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
637
638
const roots = effectivePaths();
639
const info = resolveRoot(filePath, roots);
640
if (!info || !canRead(req.user, info.label))
641
{
642
return res.status(403).json({ error: 'Access denied.' });
643
}
644
645
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
646
{
647
return res.status(404).json({ error: 'File not found.' });
648
}
649
650
const session = await createVideoStreamSession(filePath);
651
res.json({
652
sessionId: session.sessionId,
653
playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
654
subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
655
subtitleTracks: session.subtitleTracks.map((track) => ({
656
label: track.label,
657
language: track.language,
658
default: !!track.isDefault,
659
src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
660
})),
661
});
662
} catch (err)
663
{
664
next(err);
665
}
666
});
667
668
// ---------------------------------------------------------------------------
669
// GET /api/files/video-stream/:sessionId/:assetPath(*)
670
// Streams HLS assets for a previously created short-lived video session.
671
// ---------------------------------------------------------------------------
672
router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
673
{
674
try
675
{
676
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);
677
} catch (err)
678
{
679
next(err);
680
}
681
});
682
626
683
// ---------------------------------------------------------------------------
627
684
// GET /api/files/download-zip?dir=<absolute-path>
628
685
// Authenticated. Streams a zip of the given directory.
@@ -12,6 +12,7 @@ const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('.12
const { requireAuth } = require('../auth');12
const { requireAuth } = require('../auth');13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');14
const { buildZip } = require('./share');14
const { buildZip } = require('./share');15
const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream');15
16
16
// ---------------------------------------------------------------------------17
// ---------------------------------------------------------------------------17
// Multer storage — files are staged into temporary files and only promoted18
// Multer storage — files are staged into temporary files and only promoted@@ -623,6 +624,62 @@ router.get('/download', requireAuth, (req, res) =>623
res.download(file, path.basename(file));624
res.download(file, path.basename(file));624
});625
});625
626
627
// ---------------------------------------------------------------------------628
// POST /api/files/video-stream629
// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.630
// ---------------------------------------------------------------------------631
router.post('/video-stream', requireAuth, async (req, res, next) =>632
{633
try634
{635
const filePath = String(req.body?.filePath || '').trim();636
if (!filePath) return res.status(400).json({ error: 'filePath is required.' });637
638
const roots = effectivePaths();639
const info = resolveRoot(filePath, roots);640
if (!info || !canRead(req.user, info.label))641
{642
return res.status(403).json({ error: 'Access denied.' });643
}644
645
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())646
{647
return res.status(404).json({ error: 'File not found.' });648
}649
650
const session = await createVideoStreamSession(filePath);651
res.json({652
sessionId: session.sessionId,653
playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,654
subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },655
subtitleTracks: session.subtitleTracks.map((track) => ({656
label: track.label,657
language: track.language,658
default: !!track.isDefault,659
src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,660
})),661
});662
} catch (err)663
{664
next(err);665
}666
});667
668
// ---------------------------------------------------------------------------669
// GET /api/files/video-stream/:sessionId/:assetPath(*)670
// Streams HLS assets for a previously created short-lived video session.671
// ---------------------------------------------------------------------------672
router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>673
{674
try675
{676
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);677
} catch (err)678
{679
next(err);680
}681
});682
626
// ---------------------------------------------------------------------------683
// ---------------------------------------------------------------------------627
// GET /api/files/download-zip?dir=<absolute-path>684
// GET /api/files/download-zip?dir=<absolute-path>628
// Authenticated. Streams a zip of the given directory.685
// Authenticated. Streams a zip of the given directory.@@ -0,0 +1,489 @@
1
'use strict';
2
3
const { spawn } = require('child_process');
4
const crypto = require('crypto');
5
const fs = require('fs');
6
const os = require('os');
7
const path = require('path');
8
9
const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');
10
const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;
11
const STREAM_READY_TIMEOUT_MS = 20 * 1000;
12
const sessions = new Map();
13
14
function hasAnyFiles (dirPath)
15
{
16
try
17
{
18
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
19
for (const entry of entries)
20
{
21
const fullPath = path.join(dirPath, entry.name);
22
if (entry.isFile()) return true;
23
if (entry.isDirectory() && hasAnyFiles(fullPath)) return true;
24
}
25
return false;
26
} catch
27
{
28
return false;
29
}
30
}
31
32
function makeHttpError (status, message)
33
{
34
const err = new Error(message);
35
err.status = status;
36
return err;
37
}
38
39
function ensureStreamRootDir ()
40
{
41
fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true });
42
}
43
44
function ffmpegPath ()
45
{
46
return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
47
}
48
49
function ffprobePath ()
50
{
51
return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe';
52
}
53
54
function pruneExpiredSessions ()
55
{
56
const now = Date.now();
57
for (const [sessionId, session] of sessions)
58
{
59
if (session.expiresAt > now) continue;
60
try
61
{
62
if (session.process) session.process.kill('SIGTERM');
63
} catch
64
{
65
// Ignore process cleanup failures.
66
}
67
sessions.delete(sessionId);
68
fs.rmSync(session.outputDir, { recursive: true, force: true });
69
}
70
}
71
72
function refreshSession (session)
73
{
74
session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;
75
}
76
77
function runCommand (command, args)
78
{
79
return new Promise((resolve, reject) =>
80
{
81
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
82
let stdout = '';
83
let stderr = '';
84
85
child.stdout.on('data', (chunk) =>
86
{
87
stdout += chunk.toString();
88
});
89
90
child.stderr.on('data', (chunk) =>
91
{
92
stderr += chunk.toString();
93
});
94
95
child.on('error', (err) =>
96
{
97
if (err && err.code === 'ENOENT')
98
{
99
reject(makeHttpError(503, `${command} is not installed or not available in PATH.`));
100
return;
101
}
102
reject(err);
103
});
104
105
child.on('close', (code) =>
106
{
107
if (code === 0)
108
{
109
resolve({ stdout, stderr });
110
return;
111
}
112
reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`));
113
});
114
});
115
}
116
117
async function probeInput (sourcePath)
118
{
119
const { stdout } = await runCommand(ffprobePath(), [
120
'-v', 'error',
121
'-print_format', 'json',
122
'-show_streams',
123
'-show_format',
124
sourcePath,
125
]);
126
127
let payload;
128
try
129
{
130
payload = JSON.parse(stdout || '{}');
131
} catch
132
{
133
throw makeHttpError(500, 'ffprobe returned invalid stream metadata.');
134
}
135
136
const typedIndexes = { video: 0, audio: 0, subtitle: 0 };
137
const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) =>
138
{
139
const codecType = String(stream.codec_type || '').toLowerCase();
140
const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType)
141
? typedIndexes[codecType]++
142
: null;
143
return {
144
...stream,
145
codecType,
146
relativeIndex,
147
tags: stream.tags || {},
148
disposition: stream.disposition || {},
149
};
150
}) : [];
151
152
return {
153
raw: payload,
154
video: streams.filter((stream) => stream.codecType === 'video'),
155
audio: streams.filter((stream) => stream.codecType === 'audio'),
156
subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
157
};
158
}
159
160
function sanitiseTrackValue (value, fallback)
161
{
162
const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
163
return cleaned || fallback;
164
}
165
166
function trackLanguage (stream)
167
{
168
return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8);
169
}
170
171
function trackLabel (stream, fallback)
172
{
173
const title = String(stream.tags.title || stream.tags.handler_name || '').trim();
174
if (title) return title;
175
const language = trackLanguage(stream);
176
if (language && language !== 'und') return `${fallback} (${language})`;
177
return fallback;
178
}
179
180
async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams)
181
{
182
const extractedTracks = [];
183
let skippedCount = 0;
184
let trackNumber = 0;
185
186
for (const stream of subtitleStreams)
187
{
188
const fileName = `subtitle-${trackNumber}.vtt`;
189
const targetPath = path.join(outputDir, fileName);
190
191
try
192
{
193
await runCommand(ffmpegPath(), [
194
'-hide_banner',
195
'-loglevel', 'error',
196
'-nostdin',
197
'-y',
198
'-i', sourcePath,
199
'-map', `0:s:${stream.relativeIndex}`,
200
'-c:s', 'webvtt',
201
targetPath,
202
]);
203
} catch
204
{
205
skippedCount += 1;
206
continue;
207
}
208
209
extractedTracks.push({
210
fileName,
211
label: trackLabel(stream, `Subtitle ${trackNumber + 1}`),
212
language: trackLanguage(stream),
213
isDefault: !!stream.disposition.default,
214
});
215
trackNumber += 1;
216
}
217
218
return {
219
tracks: extractedTracks,
220
skippedCount,
221
};
222
}
223
224
function buildHlsArgs (sourcePath, outputDir, streamInfo)
225
{
226
const args = [
227
'-hide_banner',
228
'-loglevel', 'error',
229
'-nostdin',
230
'-y',
231
'-i', sourcePath,
232
'-map', '0:v:0',
233
];
234
235
for (const audioStream of streamInfo.audio)
236
{
237
args.push('-map', `0:a:${audioStream.relativeIndex}`);
238
}
239
240
args.push(
241
'-c:v', 'libx264',
242
'-preset', 'veryfast',
243
'-crf', '23',
244
'-pix_fmt', 'yuv420p',
245
'-g', '48',
246
'-sc_threshold', '0',
247
);
248
249
if (streamInfo.audio.length)
250
{
251
args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2');
252
} else
253
{
254
args.push('-an');
255
}
256
257
const variantMap = [];
258
if (streamInfo.audio.length)
259
{
260
variantMap.push('v:0,agroup:audio,name:video');
261
streamInfo.audio.forEach((audioStream, index) =>
262
{
263
let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`;
264
if (audioStream.disposition.default) entry += ',default:yes';
265
variantMap.push(entry);
266
});
267
} else
268
{
269
variantMap.push('v:0,name:video');
270
}
271
272
args.push(
273
'-f', 'hls',
274
'-hls_time', '4',
275
'-hls_list_size', '0',
276
'-hls_flags', 'independent_segments+temp_file',
277
'-master_pl_name', 'master.m3u8',
278
'-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'),
279
'-var_stream_map', variantMap.join(' '),
280
path.join(outputDir, 'stream_%v.m3u8'),
281
);
282
283
return args;
284
}
285
286
function startHlsTranscode (session, streamInfo)
287
{
288
const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo);
289
const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] });
290
let stderr = '';
291
292
child.stderr.on('data', (chunk) =>
293
{
294
stderr += chunk.toString();
295
if (stderr.length > 16000) stderr = stderr.slice(-16000);
296
});
297
298
child.on('error', (err) =>
299
{
300
if (err && err.code === 'ENOENT')
301
{
302
session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.');
303
return;
304
}
305
session.error = err;
306
});
307
308
child.on('close', (code) =>
309
{
310
session.process = null;
311
if (code === 0 || session.error) return;
312
session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`);
313
});
314
315
session.process = child;
316
}
317
318
function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS)
319
{
320
const startedAt = Date.now();
321
322
return new Promise((resolve, reject) =>
323
{
324
const check = () =>
325
{
326
if (fs.existsSync(targetPath))
327
{
328
resolve();
329
return;
330
}
331
332
if (session.error)
333
{
334
reject(session.error);
335
return;
336
}
337
338
if (Date.now() - startedAt >= timeoutMs)
339
{
340
reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
341
return;
342
}
343
344
setTimeout(check, 120);
345
};
346
347
check();
348
});
349
}
350
351
function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS)
352
{
353
const startedAt = Date.now();
354
355
return new Promise((resolve, reject) =>
356
{
357
const check = () =>
358
{
359
if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasAnyFiles(session.outputDir))
360
{
361
resolve();
362
return;
363
}
364
365
if (session.error)
366
{
367
reject(session.error);
368
return;
369
}
370
371
if (!session.process)
372
{
373
reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.'));
374
return;
375
}
376
377
if (Date.now() - startedAt >= timeoutMs)
378
{
379
reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
380
return;
381
}
382
383
setTimeout(check, 120);
384
};
385
386
check();
387
});
388
}
389
390
async function initialiseSession (session)
391
{
392
const streamInfo = await probeInput(session.sourcePath);
393
if (!streamInfo.video.length)
394
{
395
throw makeHttpError(400, 'File does not contain a video stream.');
396
}
397
398
const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles);
399
session.subtitleTracks = subtitleResult.tracks;
400
session.subtitleSummary = {
401
total: streamInfo.subtitles.length,
402
converted: subtitleResult.tracks.length,
403
skipped: subtitleResult.skippedCount,
404
};
405
startHlsTranscode(session, streamInfo);
406
await waitForStreamStart(session);
407
}
408
409
async function createVideoStreamSession (sourcePath)
410
{
411
pruneExpiredSessions();
412
ensureStreamRootDir();
413
414
const sessionId = crypto.randomBytes(18).toString('hex');
415
const outputDir = path.join(STREAM_ROOT_DIR, sessionId);
416
fs.mkdirSync(outputDir, { recursive: true });
417
418
const session = {
419
id: sessionId,
420
sourcePath,
421
outputDir,
422
expiresAt: Date.now() + STREAM_SESSION_TTL_MS,
423
process: null,
424
error: null,
425
subtitleTracks: [],
426
subtitleSummary: { total: 0, converted: 0, skipped: 0 },
427
readyPromise: null,
428
};
429
430
session.readyPromise = initialiseSession(session).catch((err) =>
431
{
432
session.error = err;
433
throw err;
434
});
435
436
sessions.set(sessionId, session);
437
await session.readyPromise;
438
439
return {
440
sessionId,
441
subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
442
subtitleSummary: {
443
total: Number(session.subtitleSummary.total || 0),
444
converted: Number(session.subtitleSummary.converted || 0),
445
skipped: Number(session.subtitleSummary.skipped || 0),
446
},
447
};
448
}
449
450
function contentTypeForAsset (assetPath)
451
{
452
const ext = path.extname(assetPath).toLowerCase();
453
if (ext === '.m3u8') return 'application/vnd.apple.mpegurl';
454
if (ext === '.ts') return 'video/mp2t';
455
if (ext === '.vtt') return 'text/vtt; charset=utf-8';
456
if (ext === '.aac') return 'audio/aac';
457
if (ext === '.mp4' || ext === '.m4s') return 'video/mp4';
458
return 'application/octet-stream';
459
}
460
461
async function sendVideoStreamAsset (sessionId, assetPath, res)
462
{
463
pruneExpiredSessions();
464
const session = sessions.get(sessionId);
465
if (!session) throw makeHttpError(404, 'Video stream session not found.');
466
467
refreshSession(session);
468
await session.readyPromise;
469
470
const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');
471
const resolvedPath = path.resolve(session.outputDir, relativeAssetPath);
472
const resolvedRoot = path.resolve(session.outputDir);
473
if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep))
474
{
475
throw makeHttpError(404, 'Stream asset not found.');
476
}
477
478
await waitForFile(resolvedPath, session);
479
res.set('Cache-Control', 'private, no-store');
480
res.type(contentTypeForAsset(resolvedPath));
481
res.sendFile(resolvedPath);
482
}
483
484
module.exports = {
485
STREAM_ROOT_DIR,
486
STREAM_SESSION_TTL_MS,
487
createVideoStreamSession,
488
sendVideoStreamAsset,
489
};
@@ -0,0 +1,489 @@1
'use strict';2
3
const { spawn } = require('child_process');4
const crypto = require('crypto');5
const fs = require('fs');6
const os = require('os');7
const path = require('path');8
9
const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');10
const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;11
const STREAM_READY_TIMEOUT_MS = 20 * 1000;12
const sessions = new Map();13
14
function hasAnyFiles (dirPath)15
{16
try17
{18
const entries = fs.readdirSync(dirPath, { withFileTypes: true });19
for (const entry of entries)20
{21
const fullPath = path.join(dirPath, entry.name);22
if (entry.isFile()) return true;23
if (entry.isDirectory() && hasAnyFiles(fullPath)) return true;24
}25
return false;26
} catch27
{28
return false;29
}30
}31
32
function makeHttpError (status, message)33
{34
const err = new Error(message);35
err.status = status;36
return err;37
}38
39
function ensureStreamRootDir ()40
{41
fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true });42
}43
44
function ffmpegPath ()45
{46
return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';47
}48
49
function ffprobePath ()50
{51
return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe';52
}53
54
function pruneExpiredSessions ()55
{56
const now = Date.now();57
for (const [sessionId, session] of sessions)58
{59
if (session.expiresAt > now) continue;60
try61
{62
if (session.process) session.process.kill('SIGTERM');63
} catch64
{65
// Ignore process cleanup failures.66
}67
sessions.delete(sessionId);68
fs.rmSync(session.outputDir, { recursive: true, force: true });69
}70
}71
72
function refreshSession (session)73
{74
session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;75
}76
77
function runCommand (command, args)78
{79
return new Promise((resolve, reject) =>80
{81
const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });82
let stdout = '';83
let stderr = '';84
85
child.stdout.on('data', (chunk) =>86
{87
stdout += chunk.toString();88
});89
90
child.stderr.on('data', (chunk) =>91
{92
stderr += chunk.toString();93
});94
95
child.on('error', (err) =>96
{97
if (err && err.code === 'ENOENT')98
{99
reject(makeHttpError(503, `${command} is not installed or not available in PATH.`));100
return;101
}102
reject(err);103
});104
105
child.on('close', (code) =>106
{107
if (code === 0)108
{109
resolve({ stdout, stderr });110
return;111
}112
reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`));113
});114
});115
}116
117
async function probeInput (sourcePath)118
{119
const { stdout } = await runCommand(ffprobePath(), [120
'-v', 'error',121
'-print_format', 'json',122
'-show_streams',123
'-show_format',124
sourcePath,125
]);126
127
let payload;128
try129
{130
payload = JSON.parse(stdout || '{}');131
} catch132
{133
throw makeHttpError(500, 'ffprobe returned invalid stream metadata.');134
}135
136
const typedIndexes = { video: 0, audio: 0, subtitle: 0 };137
const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) =>138
{139
const codecType = String(stream.codec_type || '').toLowerCase();140
const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType)141
? typedIndexes[codecType]++142
: null;143
return {144
...stream,145
codecType,146
relativeIndex,147
tags: stream.tags || {},148
disposition: stream.disposition || {},149
};150
}) : [];151
152
return {153
raw: payload,154
video: streams.filter((stream) => stream.codecType === 'video'),155
audio: streams.filter((stream) => stream.codecType === 'audio'),156
subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),157
};158
}159
160
function sanitiseTrackValue (value, fallback)161
{162
const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');163
return cleaned || fallback;164
}165
166
function trackLanguage (stream)167
{168
return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8);169
}170
171
function trackLabel (stream, fallback)172
{173
const title = String(stream.tags.title || stream.tags.handler_name || '').trim();174
if (title) return title;175
const language = trackLanguage(stream);176
if (language && language !== 'und') return `${fallback} (${language})`;177
return fallback;178
}179
180
async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams)181
{182
const extractedTracks = [];183
let skippedCount = 0;184
let trackNumber = 0;185
186
for (const stream of subtitleStreams)187
{188
const fileName = `subtitle-${trackNumber}.vtt`;189
const targetPath = path.join(outputDir, fileName);190
191
try192
{193
await runCommand(ffmpegPath(), [194
'-hide_banner',195
'-loglevel', 'error',196
'-nostdin',197
'-y',198
'-i', sourcePath,199
'-map', `0:s:${stream.relativeIndex}`,200
'-c:s', 'webvtt',201
targetPath,202
]);203
} catch204
{205
skippedCount += 1;206
continue;207
}208
209
extractedTracks.push({210
fileName,211
label: trackLabel(stream, `Subtitle ${trackNumber + 1}`),212
language: trackLanguage(stream),213
isDefault: !!stream.disposition.default,214
});215
trackNumber += 1;216
}217
218
return {219
tracks: extractedTracks,220
skippedCount,221
};222
}223
224
function buildHlsArgs (sourcePath, outputDir, streamInfo)225
{226
const args = [227
'-hide_banner',228
'-loglevel', 'error',229
'-nostdin',230
'-y',231
'-i', sourcePath,232
'-map', '0:v:0',233
];234
235
for (const audioStream of streamInfo.audio)236
{237
args.push('-map', `0:a:${audioStream.relativeIndex}`);238
}239
240
args.push(241
'-c:v', 'libx264',242
'-preset', 'veryfast',243
'-crf', '23',244
'-pix_fmt', 'yuv420p',245
'-g', '48',246
'-sc_threshold', '0',247
);248
249
if (streamInfo.audio.length)250
{251
args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2');252
} else253
{254
args.push('-an');255
}256
257
const variantMap = [];258
if (streamInfo.audio.length)259
{260
variantMap.push('v:0,agroup:audio,name:video');261
streamInfo.audio.forEach((audioStream, index) =>262
{263
let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`;264
if (audioStream.disposition.default) entry += ',default:yes';265
variantMap.push(entry);266
});267
} else268
{269
variantMap.push('v:0,name:video');270
}271
272
args.push(273
'-f', 'hls',274
'-hls_time', '4',275
'-hls_list_size', '0',276
'-hls_flags', 'independent_segments+temp_file',277
'-master_pl_name', 'master.m3u8',278
'-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'),279
'-var_stream_map', variantMap.join(' '),280
path.join(outputDir, 'stream_%v.m3u8'),281
);282
283
return args;284
}285
286
function startHlsTranscode (session, streamInfo)287
{288
const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo);289
const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] });290
let stderr = '';291
292
child.stderr.on('data', (chunk) =>293
{294
stderr += chunk.toString();295
if (stderr.length > 16000) stderr = stderr.slice(-16000);296
});297
298
child.on('error', (err) =>299
{300
if (err && err.code === 'ENOENT')301
{302
session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.');303
return;304
}305
session.error = err;306
});307
308
child.on('close', (code) =>309
{310
session.process = null;311
if (code === 0 || session.error) return;312
session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`);313
});314
315
session.process = child;316
}317
318
function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS)319
{320
const startedAt = Date.now();321
322
return new Promise((resolve, reject) =>323
{324
const check = () =>325
{326
if (fs.existsSync(targetPath))327
{328
resolve();329
return;330
}331
332
if (session.error)333
{334
reject(session.error);335
return;336
}337
338
if (Date.now() - startedAt >= timeoutMs)339
{340
reject(makeHttpError(504, 'Timed out while preparing the video stream.'));341
return;342
}343
344
setTimeout(check, 120);345
};346
347
check();348
});349
}350
351
function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS)352
{353
const startedAt = Date.now();354
355
return new Promise((resolve, reject) =>356
{357
const check = () =>358
{359
if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasAnyFiles(session.outputDir))360
{361
resolve();362
return;363
}364
365
if (session.error)366
{367
reject(session.error);368
return;369
}370
371
if (!session.process)372
{373
reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.'));374
return;375
}376
377
if (Date.now() - startedAt >= timeoutMs)378
{379
reject(makeHttpError(504, 'Timed out while preparing the video stream.'));380
return;381
}382
383
setTimeout(check, 120);384
};385
386
check();387
});388
}389
390
async function initialiseSession (session)391
{392
const streamInfo = await probeInput(session.sourcePath);393
if (!streamInfo.video.length)394
{395
throw makeHttpError(400, 'File does not contain a video stream.');396
}397
398
const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles);399
session.subtitleTracks = subtitleResult.tracks;400
session.subtitleSummary = {401
total: streamInfo.subtitles.length,402
converted: subtitleResult.tracks.length,403
skipped: subtitleResult.skippedCount,404
};405
startHlsTranscode(session, streamInfo);406
await waitForStreamStart(session);407
}408
409
async function createVideoStreamSession (sourcePath)410
{411
pruneExpiredSessions();412
ensureStreamRootDir();413
414
const sessionId = crypto.randomBytes(18).toString('hex');415
const outputDir = path.join(STREAM_ROOT_DIR, sessionId);416
fs.mkdirSync(outputDir, { recursive: true });417
418
const session = {419
id: sessionId,420
sourcePath,421
outputDir,422
expiresAt: Date.now() + STREAM_SESSION_TTL_MS,423
process: null,424
error: null,425
subtitleTracks: [],426
subtitleSummary: { total: 0, converted: 0, skipped: 0 },427
readyPromise: null,428
};429
430
session.readyPromise = initialiseSession(session).catch((err) =>431
{432
session.error = err;433
throw err;434
});435
436
sessions.set(sessionId, session);437
await session.readyPromise;438
439
return {440
sessionId,441
subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),442
subtitleSummary: {443
total: Number(session.subtitleSummary.total || 0),444
converted: Number(session.subtitleSummary.converted || 0),445
skipped: Number(session.subtitleSummary.skipped || 0),446
},447
};448
}449
450
function contentTypeForAsset (assetPath)451
{452
const ext = path.extname(assetPath).toLowerCase();453
if (ext === '.m3u8') return 'application/vnd.apple.mpegurl';454
if (ext === '.ts') return 'video/mp2t';455
if (ext === '.vtt') return 'text/vtt; charset=utf-8';456
if (ext === '.aac') return 'audio/aac';457
if (ext === '.mp4' || ext === '.m4s') return 'video/mp4';458
return 'application/octet-stream';459
}460
461
async function sendVideoStreamAsset (sessionId, assetPath, res)462
{463
pruneExpiredSessions();464
const session = sessions.get(sessionId);465
if (!session) throw makeHttpError(404, 'Video stream session not found.');466
467
refreshSession(session);468
await session.readyPromise;469
470
const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');471
const resolvedPath = path.resolve(session.outputDir, relativeAssetPath);472
const resolvedRoot = path.resolve(session.outputDir);473
if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep))474
{475
throw makeHttpError(404, 'Stream asset not found.');476
}477
478
await waitForFile(resolvedPath, session);479
res.set('Cache-Control', 'private, no-store');480
res.type(contentTypeForAsset(resolvedPath));481
res.sendFile(resolvedPath);482
}483
484
module.exports = {485
STREAM_ROOT_DIR,486
STREAM_SESSION_TTL_MS,487
createVideoStreamSession,488
sendVideoStreamAsset,489
};@@ -14,6 +14,8 @@ let mockThumbPath = null;
14
14
let mockFolderImages = [];
15
15
let mockFolderIconFile = null;
16
16
let lastFolderIconAssignment = undefined;
17
let mockVideoStreamSession = null;
18
let mockVideoStreamAsset = null;
17
19
18
20
jest.mock('../server/db', () =>
19
21
{
@@ -82,6 +84,23 @@ jest.mock('../server/thumbnail-cache', () => ({
82
84
},
83
85
}));
84
86
87
jest.mock('../server/video-stream', () => ({
88
createVideoStreamSession: jest.fn(async () =>
89
{
90
if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
91
return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
92
}),
93
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, res) =>
94
{
95
if (typeof mockVideoStreamAsset === 'function')
96
{
97
await mockVideoStreamAsset(sessionId, assetPath, res);
98
return;
99
}
100
res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
101
}),
102
}));
103
85
104
const filesRoutes = require('../server/routes/files');
86
105
const { getDb } = require('../server/db');
87
106
@@ -124,6 +143,8 @@ beforeEach(() =>
124
143
mockFolderImages = [];
125
144
mockFolderIconFile = null;
126
145
lastFolderIconAssignment = undefined;
146
mockVideoStreamSession = null;
147
mockVideoStreamAsset = null;
127
148
const db = getDb();
128
149
db.prepare('DELETE FROM file_meta').run([]);
129
150
db.prepare('DELETE FROM users').run([]);
@@ -665,3 +686,43 @@ describe('GET /api/files/download-zip', () =>
665
686
expect(status).toBe(403);
666
687
});
667
688
});
689
690
describe('video streaming routes', () =>
691
{
692
test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
693
{
694
const filePath = path.join(rootDir, 'clip.mkv');
695
fs.writeFileSync(filePath, 'video');
696
mockVideoStreamSession = {
697
sessionId: 'sess-123',
698
subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
699
};
700
701
const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
702
703
expect(status).toBe(200);
704
expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
705
expect(body.subtitleTracks).toEqual([
706
{
707
label: 'English',
708
language: 'eng',
709
default: true,
710
src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
711
},
712
]);
713
});
714
715
test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
716
{
717
mockVideoStreamAsset = async (_sessionId, _assetPath, res) =>
718
{
719
res.type('text/vtt').send('WEBVTT\n');
720
};
721
722
const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
723
724
expect(status).toBe(200);
725
expect(headers['content-type']).toMatch(/text\/vtt/);
726
expect(body.toString()).toBe('WEBVTT\n');
727
});
728
});
@@ -14,6 +14,8 @@ let mockThumbPath = null;14
let mockFolderImages = [];14
let mockFolderImages = [];15
let mockFolderIconFile = null;15
let mockFolderIconFile = null;16
let lastFolderIconAssignment = undefined;16
let lastFolderIconAssignment = undefined;17
let mockVideoStreamSession = null;18
let mockVideoStreamAsset = null;17
19
18
jest.mock('../server/db', () =>20
jest.mock('../server/db', () =>19
{21
{@@ -82,6 +84,23 @@ jest.mock('../server/thumbnail-cache', () => ({82
},84
},83
}));85
}));84
86
87
jest.mock('../server/video-stream', () => ({88
createVideoStreamSession: jest.fn(async () =>89
{90
if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;91
return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };92
}),93
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, res) =>94
{95
if (typeof mockVideoStreamAsset === 'function')96
{97
await mockVideoStreamAsset(sessionId, assetPath, res);98
return;99
}100
res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');101
}),102
}));103
85
const filesRoutes = require('../server/routes/files');104
const filesRoutes = require('../server/routes/files');86
const { getDb } = require('../server/db');105
const { getDb } = require('../server/db');87
106
@@ -124,6 +143,8 @@ beforeEach(() =>124
mockFolderImages = [];143
mockFolderImages = [];125
mockFolderIconFile = null;144
mockFolderIconFile = null;126
lastFolderIconAssignment = undefined;145
lastFolderIconAssignment = undefined;146
mockVideoStreamSession = null;147
mockVideoStreamAsset = null;127
const db = getDb();148
const db = getDb();128
db.prepare('DELETE FROM file_meta').run([]);149
db.prepare('DELETE FROM file_meta').run([]);129
db.prepare('DELETE FROM users').run([]);150
db.prepare('DELETE FROM users').run([]);@@ -665,3 +686,43 @@ describe('GET /api/files/download-zip', () =>665
expect(status).toBe(403);686
expect(status).toBe(403);666
});687
});667
});688
});689
690
describe('video streaming routes', () =>691
{692
test('POST /api/files/video-stream creates a short-lived playlist session', async () =>693
{694
const filePath = path.join(rootDir, 'clip.mkv');695
fs.writeFileSync(filePath, 'video');696
mockVideoStreamSession = {697
sessionId: 'sess-123',698
subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],699
};700
701
const { status, body } = await req('POST', '/api/files/video-stream', { filePath });702
703
expect(status).toBe(200);704
expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');705
expect(body.subtitleTracks).toEqual([706
{707
label: 'English',708
language: 'eng',709
default: true,710
src: '/api/files/video-stream/sess-123/subtitle-0.vtt',711
},712
]);713
});714
715
test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>716
{717
mockVideoStreamAsset = async (_sessionId, _assetPath, res) =>718
{719
res.type('text/vtt').send('WEBVTT\n');720
};721
722
const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');723
724
expect(status).toBe(200);725
expect(headers['content-type']).toMatch(/text\/vtt/);726
expect(body.toString()).toBe('WEBVTT\n');727
});728
});@@ -22,6 +22,8 @@ describe('page load smoke test', () =>
22
22
let adminUsersFixture;
23
23
let adminConfigFixture;
24
24
let downloadFixture;
25
let videoStreamFixture;
26
let setupNeededFixture;
25
27
const openDoms = [];
26
28
27
29
beforeEach(() =>
@@ -48,6 +50,8 @@ describe('page load smoke test', () =>
48
50
adminUsersFixture = { users: [] };
49
51
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
50
52
downloadFixture = {};
53
videoStreamFixture = {};
54
setupNeededFixture = false;
51
55
});
52
56
53
57
beforeAll(async () =>
@@ -61,7 +65,7 @@ describe('page load smoke test', () =>
61
65
app.use(express.static(publicDir));
62
66
63
67
app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
64
app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
68
app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: setupNeededFixture }));
65
69
app.get('/api/auth/me', (req, res) => res.json(meFixture));
66
70
app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
67
71
app.get('/api/files/list', (req, res) =>
@@ -95,6 +99,16 @@ describe('page load smoke test', () =>
95
99
}
96
100
res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
97
101
});
102
app.post('/api/files/video-stream', (req, res) =>
103
{
104
const filePath = String(req.body?.filePath || '');
105
const payload = videoStreamFixture[filePath];
106
if (!payload)
107
{
108
return res.status(404).json({ error: 'Stream not found.' });
109
}
110
res.json(payload);
111
});
98
112
app.get('/api/files/root-access', (req, res) =>
99
113
{
100
114
const rootPath = String(req.query.rootPath || '');
@@ -162,6 +176,14 @@ describe('page load smoke test', () =>
162
176
let blobCounter = 0;
163
177
window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
164
178
window.URL.revokeObjectURL = () => { };
179
window.__lastVideoJsOptions = null;
180
window.videojs = (element, options) =>
181
{
182
window.__lastVideoJsOptions = options;
183
return {
184
dispose () { },
185
};
186
};
165
187
166
188
const defaultSaved = {
167
189
token: 'saved-token',
@@ -233,6 +255,34 @@ describe('page load smoke test', () =>
233
255
dom.window.close();
234
256
});
235
257
258
test('login overlay uses username and current-password autocomplete tokens', async () =>
259
{
260
const { dom, runtimeErrors } = await bootClient({ savedSession: null });
261
262
expect(runtimeErrors).toEqual([]);
263
264
const username = dom.window.document.getElementById('auth-username');
265
const password = dom.window.document.getElementById('auth-password');
266
expect(username.getAttribute('autocomplete')).toBe('username');
267
expect(password.getAttribute('autocomplete')).toBe('current-password');
268
269
dom.window.close();
270
});
271
272
test('first-run setup uses new-password autocomplete token', async () =>
273
{
274
setupNeededFixture = true;
275
276
const { dom, runtimeErrors } = await bootClient({ savedSession: null });
277
278
expect(runtimeErrors).toEqual([]);
279
280
const password = dom.window.document.getElementById('auth-password');
281
expect(password.getAttribute('autocomplete')).toBe('new-password');
282
283
dom.window.close();
284
});
285
236
286
test('keeps sidebar folded on initial mobile boot', async () =>
237
287
{
238
288
const { dom, runtimeErrors } = await bootClient({ mobile: true });
@@ -543,10 +593,57 @@ describe('page load smoke test', () =>
543
593
544
594
const shareBtn = dom.window.document.querySelector('.preview-expand-share');
545
595
const downloadBtn = dom.window.document.querySelector('.preview-expand-download');
596
const actions = dom.window.document.querySelector('.preview-expand-actions');
546
597
expect(shareBtn).toBeTruthy();
547
598
expect(downloadBtn).toBeTruthy();
599
expect(actions).toBeTruthy();
600
expect(actions.contains(shareBtn)).toBe(true);
601
expect(actions.contains(downloadBtn)).toBe(true);
548
602
expect(shareBtn.textContent).toBe('Share');
549
603
550
604
dom.window.close();
551
605
});
606
607
test('expanded video preview uses a stream session and video.js', async () =>
608
{
609
listFixture['/data'] = [
610
{
611
name: 'clip.mkv',
612
path: '/data/clip.mkv',
613
isDir: false,
614
size: 64,
615
mtime: Date.now(),
616
},
617
];
618
videoStreamFixture['/data/clip.mkv'] = {
619
sessionId: 'video-session',
620
playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
621
subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
622
};
623
624
const { dom, runtimeErrors } = await bootClient();
625
expect(runtimeErrors).toEqual([]);
626
627
await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
628
629
const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
630
expect(fileTile).toBeTruthy();
631
632
fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
633
await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
634
635
expect(dom.window.__lastVideoJsOptions).toBeTruthy();
636
expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
637
expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
638
{
639
kind: 'subtitles',
640
src: '/api/files/video-stream/video-session/subtitle-0.vtt',
641
srclang: 'eng',
642
label: 'English',
643
default: true,
644
},
645
]);
646
647
dom.window.close();
648
});
552
649
});
@@ -22,6 +22,8 @@ describe('page load smoke test', () =>22
let adminUsersFixture;
22
let adminUsersFixture;
23
let adminConfigFixture;
23
let adminConfigFixture;
24
let downloadFixture;
24
let downloadFixture;
25
let videoStreamFixture;
26
let setupNeededFixture;
25
const openDoms = [];
27
const openDoms = [];
26
28
27
beforeEach(() =>
29
beforeEach(() =>
@@ -48,6 +50,8 @@ describe('page load smoke test', () =>48
adminUsersFixture = { users: [] };
50
adminUsersFixture = { users: [] };
49
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
51
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
50
downloadFixture = {};
52
downloadFixture = {};
53
videoStreamFixture = {};
54
setupNeededFixture = false;
51
});
55
});
52
56
53
beforeAll(async () =>
57
beforeAll(async () =>
@@ -61,7 +65,7 @@ describe('page load smoke test', () =>61
app.use(express.static(publicDir));
65
app.use(express.static(publicDir));
62
66
63
app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
67
app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
64
app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
68
app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: setupNeededFixture }));
65
app.get('/api/auth/me', (req, res) => res.json(meFixture));
69
app.get('/api/auth/me', (req, res) => res.json(meFixture));
66
app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
70
app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
67
app.get('/api/files/list', (req, res) =>
71
app.get('/api/files/list', (req, res) =>
@@ -95,6 +99,16 @@ describe('page load smoke test', () =>95
}
99
}
96
res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
100
res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
97
});
101
});
102
app.post('/api/files/video-stream', (req, res) =>
103
{
104
const filePath = String(req.body?.filePath || '');
105
const payload = videoStreamFixture[filePath];
106
if (!payload)
107
{
108
return res.status(404).json({ error: 'Stream not found.' });
109
}
110
res.json(payload);
111
});
98
app.get('/api/files/root-access', (req, res) =>
112
app.get('/api/files/root-access', (req, res) =>
99
{
113
{
100
const rootPath = String(req.query.rootPath || '');
114
const rootPath = String(req.query.rootPath || '');
@@ -162,6 +176,14 @@ describe('page load smoke test', () =>162
let blobCounter = 0;
176
let blobCounter = 0;
163
window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
177
window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
164
window.URL.revokeObjectURL = () => { };
178
window.URL.revokeObjectURL = () => { };
179
window.__lastVideoJsOptions = null;
180
window.videojs = (element, options) =>
181
{
182
window.__lastVideoJsOptions = options;
183
return {
184
dispose () { },
185
};
186
};
165
187
166
const defaultSaved = {
188
const defaultSaved = {
167
token: 'saved-token',
189
token: 'saved-token',
@@ -233,6 +255,34 @@ describe('page load smoke test', () =>233
dom.window.close();
255
dom.window.close();
234
});
256
});
235
257
258
test('login overlay uses username and current-password autocomplete tokens', async () =>
259
{
260
const { dom, runtimeErrors } = await bootClient({ savedSession: null });
261
262
expect(runtimeErrors).toEqual([]);
263
264
const username = dom.window.document.getElementById('auth-username');
265
const password = dom.window.document.getElementById('auth-password');
266
expect(username.getAttribute('autocomplete')).toBe('username');
267
expect(password.getAttribute('autocomplete')).toBe('current-password');
268
269
dom.window.close();
270
});
271
272
test('first-run setup uses new-password autocomplete token', async () =>
273
{
274
setupNeededFixture = true;
275
276
const { dom, runtimeErrors } = await bootClient({ savedSession: null });
277
278
expect(runtimeErrors).toEqual([]);
279
280
const password = dom.window.document.getElementById('auth-password');
281
expect(password.getAttribute('autocomplete')).toBe('new-password');
282
283
dom.window.close();
284
});
285
236
test('keeps sidebar folded on initial mobile boot', async () =>
286
test('keeps sidebar folded on initial mobile boot', async () =>
237
{
287
{
238
const { dom, runtimeErrors } = await bootClient({ mobile: true });
288
const { dom, runtimeErrors } = await bootClient({ mobile: true });
@@ -543,10 +593,57 @@ describe('page load smoke test', () =>543
593
544
const shareBtn = dom.window.document.querySelector('.preview-expand-share');
594
const shareBtn = dom.window.document.querySelector('.preview-expand-share');
545
const downloadBtn = dom.window.document.querySelector('.preview-expand-download');
595
const downloadBtn = dom.window.document.querySelector('.preview-expand-download');
596
const actions = dom.window.document.querySelector('.preview-expand-actions');
546
expect(shareBtn).toBeTruthy();
597
expect(shareBtn).toBeTruthy();
547
expect(downloadBtn).toBeTruthy();
598
expect(downloadBtn).toBeTruthy();
599
expect(actions).toBeTruthy();
600
expect(actions.contains(shareBtn)).toBe(true);
601
expect(actions.contains(downloadBtn)).toBe(true);
548
expect(shareBtn.textContent).toBe('Share');
602
expect(shareBtn.textContent).toBe('Share');
549
603
550
dom.window.close();
604
dom.window.close();
551
});
605
});
606
607
test('expanded video preview uses a stream session and video.js', async () =>
608
{
609
listFixture['/data'] = [
610
{
611
name: 'clip.mkv',
612
path: '/data/clip.mkv',
613
isDir: false,
614
size: 64,
615
mtime: Date.now(),
616
},
617
];
618
videoStreamFixture['/data/clip.mkv'] = {
619
sessionId: 'video-session',
620
playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
621
subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
622
};
623
624
const { dom, runtimeErrors } = await bootClient();
625
expect(runtimeErrors).toEqual([]);
626
627
await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
628
629
const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
630
expect(fileTile).toBeTruthy();
631
632
fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
633
await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
634
635
expect(dom.window.__lastVideoJsOptions).toBeTruthy();
636
expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
637
expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
638
{
639
kind: 'subtitles',
640
src: '/api/files/video-stream/video-session/subtitle-0.vtt',
641
srclang: 'eng',
642
label: 'English',
643
default: true,
644
},
645
]);
646
647
dom.window.close();
648
});
552
});
649
});
@@ -0,0 +1,198 @@
1
'use strict';
2
3
const { EventEmitter } = require('events');
4
const fs = require('fs');
5
const os = require('os');
6
const path = require('path');
7
8
jest.mock('child_process', () => ({
9
spawn: jest.fn(),
10
}));
11
12
function makeChildProcess ()
13
{
14
const child = new EventEmitter();
15
child.stdout = new EventEmitter();
16
child.stderr = new EventEmitter();
17
child.kill = jest.fn();
18
return child;
19
}
20
21
describe('video stream bootstrap', () =>
22
{
23
let mockSpawn;
24
let sourceFile;
25
26
beforeEach(() =>
27
{
28
jest.resetModules();
29
mockSpawn = require('child_process').spawn;
30
mockSpawn.mockReset();
31
32
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-'));
33
sourceFile = path.join(tmpDir, 'clip.mkv');
34
fs.writeFileSync(sourceFile, 'video');
35
});
36
37
test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () =>
38
{
39
mockSpawn.mockImplementation((command, args) =>
40
{
41
const child = makeChildProcess();
42
const exeName = path.basename(String(command || '')).toLowerCase();
43
44
if (exeName.includes('ffprobe'))
45
{
46
process.nextTick(() =>
47
{
48
child.stdout.emit('data', Buffer.from(JSON.stringify({
49
streams: [
50
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
51
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
52
],
53
})));
54
child.emit('close', 0);
55
});
56
return child;
57
}
58
59
expect(exeName.includes('ffmpeg')).toBe(true);
60
61
const outputPattern = String(args[args.length - 1] || '');
62
const outputDir = path.dirname(outputPattern);
63
64
process.nextTick(() =>
65
{
66
fs.mkdirSync(outputDir, { recursive: true });
67
setTimeout(() =>
68
{
69
fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n');
70
}, 40);
71
});
72
73
return child;
74
});
75
76
const { createVideoStreamSession } = require('../server/video-stream');
77
const session = await createVideoStreamSession(sourceFile);
78
79
expect(session).toEqual({
80
sessionId: expect.any(String),
81
subtitleTracks: [],
82
subtitleSummary: {
83
total: 0,
84
converted: 0,
85
skipped: 0,
86
},
87
});
88
});
89
90
test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>
91
{
92
mockSpawn.mockImplementation((command, args) =>
93
{
94
const child = makeChildProcess();
95
const exeName = path.basename(String(command || '')).toLowerCase();
96
97
if (exeName.includes('ffprobe'))
98
{
99
process.nextTick(() =>
100
{
101
child.stdout.emit('data', Buffer.from(JSON.stringify({
102
streams: [
103
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
104
{ codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },
105
],
106
})));
107
child.emit('close', 0);
108
});
109
return child;
110
}
111
112
const segmentArgIndex = args.indexOf('-hls_segment_filename');
113
expect(segmentArgIndex).toBeGreaterThan(-1);
114
expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
115
116
const playlistPath = String(args[args.length - 1] || '');
117
const outputDir = path.dirname(playlistPath);
118
process.nextTick(() =>
119
{
120
fs.mkdirSync(outputDir, { recursive: true });
121
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
122
});
123
124
return child;
125
});
126
127
const { createVideoStreamSession } = require('../server/video-stream');
128
await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
129
sessionId: expect.any(String),
130
subtitleTracks: [],
131
subtitleSummary: {
132
total: 0,
133
converted: 0,
134
skipped: 0,
135
},
136
});
137
});
138
139
test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>
140
{
141
mockSpawn.mockImplementation((command, args) =>
142
{
143
const child = makeChildProcess();
144
const exeName = path.basename(String(command || '')).toLowerCase();
145
146
if (exeName.includes('ffprobe'))
147
{
148
process.nextTick(() =>
149
{
150
child.stdout.emit('data', Buffer.from(JSON.stringify({
151
streams: [
152
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
153
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
154
{ codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },
155
],
156
})));
157
child.emit('close', 0);
158
});
159
return child;
160
}
161
162
const mapIndex = args.indexOf('-map');
163
const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
164
165
// Fail subtitle extraction but keep HLS transcoding path successful.
166
if (mappedValue.startsWith('0:s:'))
167
{
168
process.nextTick(() =>
169
{
170
child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));
171
child.emit('close', 1);
172
});
173
return child;
174
}
175
176
const playlistPath = String(args[args.length - 1] || '');
177
const outputDir = path.dirname(playlistPath);
178
process.nextTick(() =>
179
{
180
fs.mkdirSync(outputDir, { recursive: true });
181
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
182
});
183
184
return child;
185
});
186
187
const { createVideoStreamSession } = require('../server/video-stream');
188
await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
189
sessionId: expect.any(String),
190
subtitleTracks: [],
191
subtitleSummary: {
192
total: 1,
193
converted: 0,
194
skipped: 1,
195
},
196
});
197
});
198
});
@@ -0,0 +1,198 @@1
'use strict';2
3
const { EventEmitter } = require('events');4
const fs = require('fs');5
const os = require('os');6
const path = require('path');7
8
jest.mock('child_process', () => ({9
spawn: jest.fn(),10
}));11
12
function makeChildProcess ()13
{14
const child = new EventEmitter();15
child.stdout = new EventEmitter();16
child.stderr = new EventEmitter();17
child.kill = jest.fn();18
return child;19
}20
21
describe('video stream bootstrap', () =>22
{23
let mockSpawn;24
let sourceFile;25
26
beforeEach(() =>27
{28
jest.resetModules();29
mockSpawn = require('child_process').spawn;30
mockSpawn.mockReset();31
32
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-'));33
sourceFile = path.join(tmpDir, 'clip.mkv');34
fs.writeFileSync(sourceFile, 'video');35
});36
37
test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () =>38
{39
mockSpawn.mockImplementation((command, args) =>40
{41
const child = makeChildProcess();42
const exeName = path.basename(String(command || '')).toLowerCase();43
44
if (exeName.includes('ffprobe'))45
{46
process.nextTick(() =>47
{48
child.stdout.emit('data', Buffer.from(JSON.stringify({49
streams: [50
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },51
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },52
],53
})));54
child.emit('close', 0);55
});56
return child;57
}58
59
expect(exeName.includes('ffmpeg')).toBe(true);60
61
const outputPattern = String(args[args.length - 1] || '');62
const outputDir = path.dirname(outputPattern);63
64
process.nextTick(() =>65
{66
fs.mkdirSync(outputDir, { recursive: true });67
setTimeout(() =>68
{69
fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n');70
}, 40);71
});72
73
return child;74
});75
76
const { createVideoStreamSession } = require('../server/video-stream');77
const session = await createVideoStreamSession(sourceFile);78
79
expect(session).toEqual({80
sessionId: expect.any(String),81
subtitleTracks: [],82
subtitleSummary: {83
total: 0,84
converted: 0,85
skipped: 0,86
},87
});88
});89
90
test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>91
{92
mockSpawn.mockImplementation((command, args) =>93
{94
const child = makeChildProcess();95
const exeName = path.basename(String(command || '')).toLowerCase();96
97
if (exeName.includes('ffprobe'))98
{99
process.nextTick(() =>100
{101
child.stdout.emit('data', Buffer.from(JSON.stringify({102
streams: [103
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },104
{ codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },105
],106
})));107
child.emit('close', 0);108
});109
return child;110
}111
112
const segmentArgIndex = args.indexOf('-hls_segment_filename');113
expect(segmentArgIndex).toBeGreaterThan(-1);114
expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');115
116
const playlistPath = String(args[args.length - 1] || '');117
const outputDir = path.dirname(playlistPath);118
process.nextTick(() =>119
{120
fs.mkdirSync(outputDir, { recursive: true });121
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');122
});123
124
return child;125
});126
127
const { createVideoStreamSession } = require('../server/video-stream');128
await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({129
sessionId: expect.any(String),130
subtitleTracks: [],131
subtitleSummary: {132
total: 0,133
converted: 0,134
skipped: 0,135
},136
});137
});138
139
test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>140
{141
mockSpawn.mockImplementation((command, args) =>142
{143
const child = makeChildProcess();144
const exeName = path.basename(String(command || '')).toLowerCase();145
146
if (exeName.includes('ffprobe'))147
{148
process.nextTick(() =>149
{150
child.stdout.emit('data', Buffer.from(JSON.stringify({151
streams: [152
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },153
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },154
{ codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },155
],156
})));157
child.emit('close', 0);158
});159
return child;160
}161
162
const mapIndex = args.indexOf('-map');163
const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';164
165
// Fail subtitle extraction but keep HLS transcoding path successful.166
if (mappedValue.startsWith('0:s:'))167
{168
process.nextTick(() =>169
{170
child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));171
child.emit('close', 1);172
});173
return child;174
}175
176
const playlistPath = String(args[args.length - 1] || '');177
const outputDir = path.dirname(playlistPath);178
process.nextTick(() =>179
{180
fs.mkdirSync(outputDir, { recursive: true });181
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');182
});183
184
return child;185
});186
187
const { createVideoStreamSession } = require('../server/video-stream');188
await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({189
sessionId: expect.any(String),190
subtitleTracks: [],191
subtitleSummary: {192
total: 1,193
converted: 0,194
skipped: 1,195
},196
});197
});198
});