BlueGit

timfa filemanager

dl video fix

timfa Tim Falken · pushed by timfa

Authored 2026-06-05 · 5 months ago

Hash
a0162cfc5fb82782ec18c1d6d40b6057c99fb02e
Parent
fd5ad945
10 files changed +375 −26
.github/technical-reference.md +2 −0
@@ -4,6 +4,8 @@
4 4 - bool_is_true(value) - Parses common truthy string values used for installer feature flags.
5 5 - confirm_root_service_mode() - Interactive installer prompt (`[y/N]`) that decides whether the service should run as root when no env override is provided.
6 6 - FILEMANAGER_SERVICE_RUN_AS_ROOT - Optional installer env override for non-interactive installs; when truthy, writes a root-running systemd unit (omits User=) and enables FILEMANAGER_LIST_ACCESS_CHMOD in the unit environment.
7 - required_packages_for(pm) - Returns distro-specific package names for node/npm/git/ffmpeg plus libvips and libheif (apt: `libvips42`, `libheif1`, `libvips-tools`; pacman/dnf/apk: `vips`, `libheif`) so Sharp can decode HEIF/HEIC on Linux.
8 - REQUIRED_COMMANDS - Includes `vips` so missing image libraries trigger the optional dependency install prompt alongside node/ffmpeg.
7 9
8 10 ## server/index.js
9 11 - start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
@@ -4,6 +4,8 @@
4- bool_is_true(value) - Parses common truthy string values used for installer feature flags.
4- bool_is_true(value) - Parses common truthy string values used for installer feature flags.
5- confirm_root_service_mode() - Interactive installer prompt (`[y/N]`) that decides whether the service should run as root when no env override is provided.
5- confirm_root_service_mode() - Interactive installer prompt (`[y/N]`) that decides whether the service should run as root when no env override is provided.
6- FILEMANAGER_SERVICE_RUN_AS_ROOT - Optional installer env override for non-interactive installs; when truthy, writes a root-running systemd unit (omits User=) and enables FILEMANAGER_LIST_ACCESS_CHMOD in the unit environment.
6- FILEMANAGER_SERVICE_RUN_AS_ROOT - Optional installer env override for non-interactive installs; when truthy, writes a root-running systemd unit (omits User=) and enables FILEMANAGER_LIST_ACCESS_CHMOD in the unit environment.
7- required_packages_for(pm) - Returns distro-specific package names for node/npm/git/ffmpeg plus libvips and libheif (apt: `libvips42`, `libheif1`, `libvips-tools`; pacman/dnf/apk: `vips`, `libheif`) so Sharp can decode HEIF/HEIC on Linux.
8- REQUIRED_COMMANDS - Includes `vips` so missing image libraries trigger the optional dependency install prompt alongside node/ffmpeg.
7
9
8## server/index.js
10## server/index.js
9- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
11- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
installsystemdservice.sh +50 −11
@@ -12,10 +12,13 @@ fi
12 12 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13 13 SERVICE_NAME="filemanager"
14 14 SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
15 REQUIRED_PACKAGES=(nodejs npm git ffmpeg)
16 REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe)
15 REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe vips)
17 16 KNOWN_PACKAGE_MANAGERS=(apt-get apt dnf yum pacman zypper apk)
18 17
18 # Base packages plus libvips + libheif for Sharp HEIF/HEIC thumbnails and previews.
19 # Names differ per distro; see required_packages_for().
20 REQUIRED_PACKAGES_HINT="nodejs npm git ffmpeg + libvips + libheif (package names vary by distro)"
21
19 22 # Resolve the user who owns the project directory (i.e. the user who cloned it,
20 23 # not root). Falls back to the SUDO_USER env var, then 'pi'.
21 24 RUN_AS="${SUDO_USER:-pi}"
@@ -109,30 +112,66 @@ confirm_dependency_install() {
109 112 esac
110 113 }
111 114
115 required_packages_for() {
116 local pm="$1"
117 local packages=(nodejs npm git ffmpeg)
118
119 case "$pm" in
120 apt-get|apt)
121 # libvips-tools provides the `vips` CLI; libheif1 enables HEIF in Sharp on Linux.
122 packages+=(libvips42 libheif1 libvips-tools)
123 ;;
124 dnf|yum)
125 packages+=(vips libheif)
126 ;;
127 pacman)
128 packages+=(vips libheif)
129 ;;
130 zypper)
131 packages+=(vips libheif)
132 ;;
133 apk)
134 packages+=(vips libheif)
135 ;;
136 *)
137 return 1
138 ;;
139 esac
140
141 printf '%s\n' "${packages[@]}"
142 }
143
112 144 install_with_package_manager() {
113 145 local pm="$1"
146 local -a packages=()
147
148 mapfile -t packages < <(required_packages_for "$pm")
149 if [[ "${#packages[@]}" -eq 0 ]]; then
150 log_warn "Unsupported package manager: $pm"
151 return 1
152 fi
114 153
115 154 case "$pm" in
116 155 apt-get)
117 apt-get update && apt-get install -y "${REQUIRED_PACKAGES[@]}"
156 apt-get update && apt-get install -y "${packages[@]}"
118 157 ;;
119 158 apt)
120 apt update && apt install -y "${REQUIRED_PACKAGES[@]}"
159 apt update && apt install -y "${packages[@]}"
121 160 ;;
122 161 dnf)
123 dnf install -y "${REQUIRED_PACKAGES[@]}"
162 dnf install -y "${packages[@]}"
124 163 ;;
125 164 yum)
126 yum install -y "${REQUIRED_PACKAGES[@]}"
165 yum install -y "${packages[@]}"
127 166 ;;
128 167 pacman)
129 pacman -Sy --noconfirm "${REQUIRED_PACKAGES[@]}"
168 pacman -Sy --noconfirm "${packages[@]}"
130 169 ;;
131 170 zypper)
132 zypper --non-interactive install --no-confirm "${REQUIRED_PACKAGES[@]}"
171 zypper --non-interactive install --no-confirm "${packages[@]}"
133 172 ;;
134 173 apk)
135 apk add --no-cache "${REQUIRED_PACKAGES[@]}"
174 apk add --no-cache "${packages[@]}"
136 175 ;;
137 176 *)
138 177 log_warn "Unsupported package manager: $pm"
@@ -166,7 +205,7 @@ maybe_install_system_dependencies() {
166 205 done
167 206
168 207 if [[ "${#available_package_managers[@]}" -eq 0 ]]; then
169 log_warn "Could not find a supported package manager. Install dependencies manually: ${REQUIRED_PACKAGES[*]} (commands needed: ${REQUIRED_COMMANDS[*]})."
208 log_warn "Could not find a supported package manager. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
170 209 return 0
171 210 fi
172 211
@@ -179,7 +218,7 @@ maybe_install_system_dependencies() {
179 218 log_warn "Dependency installation via '$pm' failed."
180 219 done
181 220
182 log_warn "All package manager installation attempts failed. Install dependencies manually: ${REQUIRED_PACKAGES[*]} (commands needed: ${REQUIRED_COMMANDS[*]})."
221 log_warn "All package manager installation attempts failed. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
183 222 }
184 223
185 224 maybe_install_system_dependencies
@@ -12,10 +12,13 @@ fi
12SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
12SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13SERVICE_NAME="filemanager"
13SERVICE_NAME="filemanager"
14SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
14SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
15REQUIRED_PACKAGES=(nodejs npm git ffmpeg)
15REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe vips)
16REQUIRED_COMMANDS=(node npm git ffmpeg ffprobe)
17KNOWN_PACKAGE_MANAGERS=(apt-get apt dnf yum pacman zypper apk)
16KNOWN_PACKAGE_MANAGERS=(apt-get apt dnf yum pacman zypper apk)
18
17
18# Base packages plus libvips + libheif for Sharp HEIF/HEIC thumbnails and previews.
19# Names differ per distro; see required_packages_for().
20REQUIRED_PACKAGES_HINT="nodejs npm git ffmpeg + libvips + libheif (package names vary by distro)"
21
19# Resolve the user who owns the project directory (i.e. the user who cloned it,
22# Resolve the user who owns the project directory (i.e. the user who cloned it,
20# not root). Falls back to the SUDO_USER env var, then 'pi'.
23# not root). Falls back to the SUDO_USER env var, then 'pi'.
21RUN_AS="${SUDO_USER:-pi}"
24RUN_AS="${SUDO_USER:-pi}"
@@ -109,30 +112,66 @@ confirm_dependency_install() {
109 esac
112 esac
110}
113}
111
114
115required_packages_for() {
116 local pm="$1"
117 local packages=(nodejs npm git ffmpeg)
118
119 case "$pm" in
120 apt-get|apt)
121 # libvips-tools provides the `vips` CLI; libheif1 enables HEIF in Sharp on Linux.
122 packages+=(libvips42 libheif1 libvips-tools)
123 ;;
124 dnf|yum)
125 packages+=(vips libheif)
126 ;;
127 pacman)
128 packages+=(vips libheif)
129 ;;
130 zypper)
131 packages+=(vips libheif)
132 ;;
133 apk)
134 packages+=(vips libheif)
135 ;;
136 *)
137 return 1
138 ;;
139 esac
140
141 printf '%s\n' "${packages[@]}"
142}
143
112install_with_package_manager() {
144install_with_package_manager() {
113 local pm="$1"
145 local pm="$1"
146 local -a packages=()
147
148 mapfile -t packages < <(required_packages_for "$pm")
149 if [[ "${#packages[@]}" -eq 0 ]]; then
150 log_warn "Unsupported package manager: $pm"
151 return 1
152 fi
114
153
115 case "$pm" in
154 case "$pm" in
116 apt-get)
155 apt-get)
117 apt-get update && apt-get install -y "${REQUIRED_PACKAGES[@]}"
156 apt-get update && apt-get install -y "${packages[@]}"
118 ;;
157 ;;
119 apt)
158 apt)
120 apt update && apt install -y "${REQUIRED_PACKAGES[@]}"
159 apt update && apt install -y "${packages[@]}"
121 ;;
160 ;;
122 dnf)
161 dnf)
123 dnf install -y "${REQUIRED_PACKAGES[@]}"
162 dnf install -y "${packages[@]}"
124 ;;
163 ;;
125 yum)
164 yum)
126 yum install -y "${REQUIRED_PACKAGES[@]}"
165 yum install -y "${packages[@]}"
127 ;;
166 ;;
128 pacman)
167 pacman)
129 pacman -Sy --noconfirm "${REQUIRED_PACKAGES[@]}"
168 pacman -Sy --noconfirm "${packages[@]}"
130 ;;
169 ;;
131 zypper)
170 zypper)
132 zypper --non-interactive install --no-confirm "${REQUIRED_PACKAGES[@]}"
171 zypper --non-interactive install --no-confirm "${packages[@]}"
133 ;;
172 ;;
134 apk)
173 apk)
135 apk add --no-cache "${REQUIRED_PACKAGES[@]}"
174 apk add --no-cache "${packages[@]}"
136 ;;
175 ;;
137 *)
176 *)
138 log_warn "Unsupported package manager: $pm"
177 log_warn "Unsupported package manager: $pm"
@@ -166,7 +205,7 @@ maybe_install_system_dependencies() {
166 done
205 done
167
206
168 if [[ "${#available_package_managers[@]}" -eq 0 ]]; then
207 if [[ "${#available_package_managers[@]}" -eq 0 ]]; then
169 log_warn "Could not find a supported package manager. Install dependencies manually: ${REQUIRED_PACKAGES[*]} (commands needed: ${REQUIRED_COMMANDS[*]})."
208 log_warn "Could not find a supported package manager. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
170 return 0
209 return 0
171 fi
210 fi
172
211
@@ -179,7 +218,7 @@ maybe_install_system_dependencies() {
179 log_warn "Dependency installation via '$pm' failed."
218 log_warn "Dependency installation via '$pm' failed."
180 done
219 done
181
220
182 log_warn "All package manager installation attempts failed. Install dependencies manually: ${REQUIRED_PACKAGES[*]} (commands needed: ${REQUIRED_COMMANDS[*]})."
221 log_warn "All package manager installation attempts failed. Install dependencies manually: ${REQUIRED_PACKAGES_HINT} (commands needed: ${REQUIRED_COMMANDS[*]})."
183}
222}
184
223
185maybe_install_system_dependencies
224maybe_install_system_dependencies
public/app.js +89 −13
@@ -53,7 +53,6 @@ const STATE = {
53 53 // Preview overlay state
54 54 previewObjectUrl: null,
55 55 previewCleanup: null,
56 previewDownloadAction: null,
57 56 previewVideoStreamSessionId: null,
58 57 previewStreamInitToken: 0,
59 58 previewSourceEl: null, // SVG element that triggered the preview
@@ -4020,7 +4019,6 @@ function clearPreviewObjectUrl ()
4020 4019 try { STATE.previewCleanup(); } catch { /* ignore */ }
4021 4020 }
4022 4021 STATE.previewCleanup = null;
4023 STATE.previewDownloadAction = null;
4024 4022 if (!STATE.previewObjectUrl) return;
4025 4023 if (String(STATE.previewObjectUrl).startsWith('blob:'))
4026 4024 {
@@ -4122,17 +4120,63 @@ function releaseActivePreviewVideoStreamSession (opts = {})
4122 4120 void releaseVideoStreamSession(sessionId, opts);
4123 4121 }
4124 4122
4125 async function preparePreviewDownload (item)
4123 const SERVER_PREVIEW_IMAGE_EXTS = new Set(['heif', 'heic']);
4124
4125 function needsServerPreviewImage (name)
4126 {
4127 return SERVER_PREVIEW_IMAGE_EXTS.has(extOf(name || ''));
4128 }
4129
4130 function previewObjectUrlIsDownloadableOriginal (item)
4131 {
4132 if (!STATE.previewObjectUrl || !item) return false;
4133 return !needsServerPreviewImage(item.name);
4134 }
4135
4136 async function fetchPreviewImageBlob (item)
4137 {
4138 const url = `/api/files/preview-image?file=${encodeURIComponent(item.path)}`;
4139 try
4140 {
4141 const res = await fetch(url, {
4142 headers: {
4143 Authorization: 'Bearer ' + STATE.token,
4144 'X-Fp': getFingerprint(),
4145 },
4146 });
4147 if (!res.ok) throw new Error('Preview failed.');
4148 return await res.blob();
4149 } catch
4150 {
4151 return null;
4152 }
4153 }
4154
4155 async function downloadFileItem (item, opts = {})
4126 4156 {
4127 4157 const blob = await fetchFileBlob(item);
4128 4158 if (!blob)
4129 4159 {
4160 if (opts.popup)
4161 {
4162 try { opts.popup.close(); } catch { /* ignore */ }
4163 }
4130 4164 toast('Download failed.', 'err');
4131 4165 return;
4132 4166 }
4133 4167
4134 4168 const objectUrl = URL.createObjectURL(blob);
4135 triggerDownload(item.name, objectUrl);
4169 if (opts.popup)
4170 {
4171 opts.popup.location.href = objectUrl;
4172 setTimeout(() =>
4173 {
4174 try { opts.popup.close(); } catch { /* ignore */ }
4175 }, 250);
4176 } else
4177 {
4178 triggerDownload(item.name, objectUrl);
4179 }
4136 4180 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
4137 4181 }
4138 4182
@@ -4174,8 +4218,6 @@ async function renderStreamedVideoPreview (item, targetEl)
4174 4218 toast('Some subtitle tracks could not be converted for web playback.', 'err');
4175 4219 }
4176 4220
4177 STATE.previewDownloadAction = () => preparePreviewDownload(item);
4178
4179 4221 const video = document.createElement('video');
4180 4222 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
4181 4223 video.controls = true;
@@ -4436,20 +4478,49 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
4436 4478 dlBtn.className = 'preview-expand-download';
4437 4479 dlBtn.type = 'button';
4438 4480 dlBtn.textContent = 'Download';
4439 dlBtn.addEventListener('click', async (e) =>
4481 dlBtn.addEventListener('click', (e) =>
4440 4482 {
4441 4483 e.stopPropagation();
4442 if (STATE.previewDownloadAction)
4484 const previewItem = STATE.previewExpandState && STATE.previewExpandState.item;
4485 if (!previewItem)
4443 4486 {
4444 await STATE.previewDownloadAction();
4487 toast('Preview unavailable.', 'err');
4445 4488 return;
4446 4489 }
4447 if (!STATE.previewObjectUrl)
4490
4491 const needsAsyncDownload = !previewObjectUrlIsDownloadableOriginal(previewItem);
4492 const popup = needsAsyncDownload ? window.open('', '_blank') : null;
4493 if (popup)
4448 4494 {
4495 try
4496 {
4497 popup.document.title = previewItem.name;
4498 popup.document.body.textContent = 'Preparing download…';
4499 }
4500 catch { /* ignore */ }
4501 }
4502
4503 if (previewObjectUrlIsDownloadableOriginal(previewItem))
4504 {
4505 if (popup)
4506 {
4507 try { popup.close(); } catch { /* ignore */ }
4508 }
4509 triggerDownload(previewItem.name, STATE.previewObjectUrl);
4510 return;
4511 }
4512
4513 if (!needsAsyncDownload)
4514 {
4515 if (popup)
4516 {
4517 try { popup.close(); } catch { /* ignore */ }
4518 }
4449 4519 toast('Preview still loading.', 'err');
4450 4520 return;
4451 4521 }
4452 triggerDownload(item.name, STATE.previewObjectUrl);
4522
4523 void downloadFileItem(previewItem, { popup });
4453 4524 });
4454 4525
4455 4526 const shareBtn = document.createElement('button');
@@ -4639,7 +4710,10 @@ function triggerDownload (filename, objectUrl)
4639 4710 const a = document.createElement('a');
4640 4711 a.href = objectUrl;
4641 4712 a.download = filename;
4713 a.style.display = 'none';
4714 document.body.appendChild(a);
4642 4715 a.click();
4716 document.body.removeChild(a);
4643 4717 }
4644 4718
4645 4719 function modelPreviewType (name)
@@ -4989,7 +5063,9 @@ async function downloadOrView (item, sourceSvgEl = null)
4989 5063 return;
4990 5064 }
4991 5065
4992 const blob = await fetchFileBlob(item);
5066 const blob = needsServerPreviewImage(item.name)
5067 ? await fetchPreviewImageBlob(item)
5068 : await fetchFileBlob(item);
4993 5069 if (!blob) throw new Error('Download failed');
4994 5070
4995 5071 clearPreviewObjectUrl();
@@ -6563,7 +6639,7 @@ function openUserModal (user, paths)
6563 6639 // SVG ICONS
6564 6640 // ───────────────────────────────────────────────────────────────────────────
6565 6641
6566 const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
6642 const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'heif', 'heic']);
6567 6643 const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
6568 6644 const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
6569 6645 const MODEL_EXTS = new Set(['stl', 'obj']);
@@ -53,7 +53,6 @@ const STATE = {
53 // Preview overlay state
53 // Preview overlay state
54 previewObjectUrl: null,
54 previewObjectUrl: null,
55 previewCleanup: null,
55 previewCleanup: null,
56 previewDownloadAction: null,
57 previewVideoStreamSessionId: null,
56 previewVideoStreamSessionId: null,
58 previewStreamInitToken: 0,
57 previewStreamInitToken: 0,
59 previewSourceEl: null, // SVG element that triggered the preview
58 previewSourceEl: null, // SVG element that triggered the preview
@@ -4020,7 +4019,6 @@ function clearPreviewObjectUrl ()
4020 try { STATE.previewCleanup(); } catch { /* ignore */ }
4019 try { STATE.previewCleanup(); } catch { /* ignore */ }
4021 }
4020 }
4022 STATE.previewCleanup = null;
4021 STATE.previewCleanup = null;
4023 STATE.previewDownloadAction = null;
4024 if (!STATE.previewObjectUrl) return;
4022 if (!STATE.previewObjectUrl) return;
4025 if (String(STATE.previewObjectUrl).startsWith('blob:'))
4023 if (String(STATE.previewObjectUrl).startsWith('blob:'))
4026 {
4024 {
@@ -4122,17 +4120,63 @@ function releaseActivePreviewVideoStreamSession (opts = {})
4122 void releaseVideoStreamSession(sessionId, opts);
4120 void releaseVideoStreamSession(sessionId, opts);
4123}
4121}
4124
4122
4125async function preparePreviewDownload (item)
4123const SERVER_PREVIEW_IMAGE_EXTS = new Set(['heif', 'heic']);
4124
4125function needsServerPreviewImage (name)
4126{
4127 return SERVER_PREVIEW_IMAGE_EXTS.has(extOf(name || ''));
4128}
4129
4130function previewObjectUrlIsDownloadableOriginal (item)
4131{
4132 if (!STATE.previewObjectUrl || !item) return false;
4133 return !needsServerPreviewImage(item.name);
4134}
4135
4136async function fetchPreviewImageBlob (item)
4137{
4138 const url = `/api/files/preview-image?file=${encodeURIComponent(item.path)}`;
4139 try
4140 {
4141 const res = await fetch(url, {
4142 headers: {
4143 Authorization: 'Bearer ' + STATE.token,
4144 'X-Fp': getFingerprint(),
4145 },
4146 });
4147 if (!res.ok) throw new Error('Preview failed.');
4148 return await res.blob();
4149 } catch
4150 {
4151 return null;
4152 }
4153}
4154
4155async function downloadFileItem (item, opts = {})
4126{
4156{
4127 const blob = await fetchFileBlob(item);
4157 const blob = await fetchFileBlob(item);
4128 if (!blob)
4158 if (!blob)
4129 {
4159 {
4160 if (opts.popup)
4161 {
4162 try { opts.popup.close(); } catch { /* ignore */ }
4163 }
4130 toast('Download failed.', 'err');
4164 toast('Download failed.', 'err');
4131 return;
4165 return;
4132 }
4166 }
4133
4167
4134 const objectUrl = URL.createObjectURL(blob);
4168 const objectUrl = URL.createObjectURL(blob);
4135 triggerDownload(item.name, objectUrl);
4169 if (opts.popup)
4170 {
4171 opts.popup.location.href = objectUrl;
4172 setTimeout(() =>
4173 {
4174 try { opts.popup.close(); } catch { /* ignore */ }
4175 }, 250);
4176 } else
4177 {
4178 triggerDownload(item.name, objectUrl);
4179 }
4136 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
4180 setTimeout(() => URL.revokeObjectURL(objectUrl), 60 * 1000);
4137}
4181}
4138
4182
@@ -4174,8 +4218,6 @@ async function renderStreamedVideoPreview (item, targetEl)
4174 toast('Some subtitle tracks could not be converted for web playback.', 'err');
4218 toast('Some subtitle tracks could not be converted for web playback.', 'err');
4175 }
4219 }
4176
4220
4177 STATE.previewDownloadAction = () => preparePreviewDownload(item);
4178
4179 const video = document.createElement('video');
4221 const video = document.createElement('video');
4180 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
4222 video.className = 'video-js vjs-big-play-centered preview-media preview-video-js';
4181 video.controls = true;
4223 video.controls = true;
@@ -4436,20 +4478,49 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
4436 dlBtn.className = 'preview-expand-download';
4478 dlBtn.className = 'preview-expand-download';
4437 dlBtn.type = 'button';
4479 dlBtn.type = 'button';
4438 dlBtn.textContent = 'Download';
4480 dlBtn.textContent = 'Download';
4439 dlBtn.addEventListener('click', async (e) =>
4481 dlBtn.addEventListener('click', (e) =>
4440 {
4482 {
4441 e.stopPropagation();
4483 e.stopPropagation();
4442 if (STATE.previewDownloadAction)
4484 const previewItem = STATE.previewExpandState && STATE.previewExpandState.item;
4485 if (!previewItem)
4443 {
4486 {
4444 await STATE.previewDownloadAction();
4487 toast('Preview unavailable.', 'err');
4445 return;
4488 return;
4446 }
4489 }
4447 if (!STATE.previewObjectUrl)
4490
4491 const needsAsyncDownload = !previewObjectUrlIsDownloadableOriginal(previewItem);
4492 const popup = needsAsyncDownload ? window.open('', '_blank') : null;
4493 if (popup)
4448 {
4494 {
4495 try
4496 {
4497 popup.document.title = previewItem.name;
4498 popup.document.body.textContent = 'Preparing download…';
4499 }
4500 catch { /* ignore */ }
4501 }
4502
4503 if (previewObjectUrlIsDownloadableOriginal(previewItem))
4504 {
4505 if (popup)
4506 {
4507 try { popup.close(); } catch { /* ignore */ }
4508 }
4509 triggerDownload(previewItem.name, STATE.previewObjectUrl);
4510 return;
4511 }
4512
4513 if (!needsAsyncDownload)
4514 {
4515 if (popup)
4516 {
4517 try { popup.close(); } catch { /* ignore */ }
4518 }
4449 toast('Preview still loading.', 'err');
4519 toast('Preview still loading.', 'err');
4450 return;
4520 return;
4451 }
4521 }
4452 triggerDownload(item.name, STATE.previewObjectUrl);
4522
4523 void downloadFileItem(previewItem, { popup });
4453 });
4524 });
4454
4525
4455 const shareBtn = document.createElement('button');
4526 const shareBtn = document.createElement('button');
@@ -4639,7 +4710,10 @@ function triggerDownload (filename, objectUrl)
4639 const a = document.createElement('a');
4710 const a = document.createElement('a');
4640 a.href = objectUrl;
4711 a.href = objectUrl;
4641 a.download = filename;
4712 a.download = filename;
4713 a.style.display = 'none';
4714 document.body.appendChild(a);
4642 a.click();
4715 a.click();
4716 document.body.removeChild(a);
4643}
4717}
4644
4718
4645function modelPreviewType (name)
4719function modelPreviewType (name)
@@ -4989,7 +5063,9 @@ async function downloadOrView (item, sourceSvgEl = null)
4989 return;
5063 return;
4990 }
5064 }
4991
5065
4992 const blob = await fetchFileBlob(item);
5066 const blob = needsServerPreviewImage(item.name)
5067 ? await fetchPreviewImageBlob(item)
5068 : await fetchFileBlob(item);
4993 if (!blob) throw new Error('Download failed');
5069 if (!blob) throw new Error('Download failed');
4994
5070
4995 clearPreviewObjectUrl();
5071 clearPreviewObjectUrl();
@@ -6563,7 +6639,7 @@ function openUserModal (user, paths)
6563// SVG ICONS
6639// SVG ICONS
6564// ───────────────────────────────────────────────────────────────────────────
6640// ───────────────────────────────────────────────────────────────────────────
6565
6641
6566const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
6642const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif', 'heif', 'heic']);
6567const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
6643const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
6568const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
6644const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
6569const MODEL_EXTS = new Set(['stl', 'obj']);
6645const MODEL_EXTS = new Set(['stl', 'obj']);
public/share.html +1 −1
@@ -445,7 +445,7 @@
445 445 const wrap = document.getElementById('preview-wrap');
446 446 const ext = name.split('.').pop().toLowerCase();
447 447
448 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico'];
448 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico', 'heif', 'heic'];
449 449 const videoExts = ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'];
450 450 const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'opus', 'm4a'];
451 451 const textExts = ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'xml', 'csv', 'yaml', 'yml', 'sh', 'log', 'ini', 'toml', 'py', 'rb', 'go', 'java', 'c', 'cpp', 'h', 'rs'];
@@ -445,7 +445,7 @@
445 const wrap = document.getElementById('preview-wrap');
445 const wrap = document.getElementById('preview-wrap');
446 const ext = name.split('.').pop().toLowerCase();
446 const ext = name.split('.').pop().toLowerCase();
447
447
448 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico'];
448 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico', 'heif', 'heic'];
449 const videoExts = ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'];
449 const videoExts = ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'];
450 const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'opus', 'm4a'];
450 const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'opus', 'm4a'];
451 const textExts = ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'xml', 'csv', 'yaml', 'yml', 'sh', 'log', 'ini', 'toml', 'py', 'rb', 'go', 'java', 'c', 'cpp', 'h', 'rs'];
451 const textExts = ['txt', 'md', 'json', 'js', 'ts', 'html', 'css', 'xml', 'csv', 'yaml', 'yml', 'sh', 'log', 'ini', 'toml', 'py', 'rb', 'go', 'java', 'c', 'cpp', 'h', 'rs'];
server/routes/files.js +51 −0
@@ -16,6 +16,9 @@ const {
16 16 getFolderIconSourceFile,
17 17 setFolderIconAssignment,
18 18 getThumbnailManifestSourcePathSet,
19 needsPreviewImageConversion,
20 streamPreviewImage,
21 MAX_PREVIEW_IMAGE_BYTES,
19 22 THUMB_HTTP_MAX_AGE_SEC,
20 23 } = require('../thumbnail-cache');
21 24 const {
@@ -371,6 +374,7 @@ function readableSearchRootsForUser (user, config, roots)
371 374
372 375 const SEARCHABLE_IMAGE_EXTS = new Set([
373 376 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
377 '.heif', '.heic',
374 378 ]);
375 379
376 380 function isSearchableImageFileName (name)
@@ -1804,6 +1808,53 @@ router.get('/download-zip', requireAuth, async (req, res) =>
1804 1808 }
1805 1809 });
1806 1810
1811 // ---------------------------------------------------------------------------
1812 // GET /api/files/preview-image?file=<absolute-path>
1813 // Converts HEIF/HEIC sources to WebP for in-browser preview.
1814 // ---------------------------------------------------------------------------
1815 router.get('/preview-image', requireAuth, async (req, res) =>
1816 {
1817 const file = req.query.file;
1818 if (!file) return res.status(400).json({ error: 'file is required.' });
1819
1820 const { config, roots } = loadConfigAndRoots();
1821 const info = resolveRootForUser(file, roots, req.user, config);
1822 if (!info || !canReadInfo(req.user, info))
1823 {
1824 return res.status(403).json({ error: 'Access denied.' });
1825 }
1826
1827 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1828 {
1829 return res.status(404).json({ error: 'File not found.' });
1830 }
1831
1832 if (!needsPreviewImageConversion(file))
1833 {
1834 return res.status(400).json({ error: 'Preview conversion is not available for this file type.' });
1835 }
1836
1837 let stat;
1838 try { stat = fs.statSync(file); } catch { return res.status(404).json({ error: 'File not found.' }); }
1839
1840 if (stat.size > MAX_PREVIEW_IMAGE_BYTES)
1841 {
1842 return res.status(413).json({ error: 'File too large for inline preview.' });
1843 }
1844
1845 try
1846 {
1847 await streamPreviewImage(file, res);
1848 } catch (err)
1849 {
1850 logError('preview-image', err);
1851 if (!res.headersSent)
1852 {
1853 res.status(500).json({ error: 'Failed to generate preview image.' });
1854 }
1855 }
1856 });
1857
1807 1858 // ---------------------------------------------------------------------------
1808 1859 // GET /api/files/thumbnail?file=<absolute-path>
1809 1860 // Returns a pre-generated cached thumbnail if present.
@@ -16,6 +16,9 @@ const {
16 getFolderIconSourceFile,
16 getFolderIconSourceFile,
17 setFolderIconAssignment,
17 setFolderIconAssignment,
18 getThumbnailManifestSourcePathSet,
18 getThumbnailManifestSourcePathSet,
19 needsPreviewImageConversion,
20 streamPreviewImage,
21 MAX_PREVIEW_IMAGE_BYTES,
19 THUMB_HTTP_MAX_AGE_SEC,
22 THUMB_HTTP_MAX_AGE_SEC,
20} = require('../thumbnail-cache');
23} = require('../thumbnail-cache');
21const {
24const {
@@ -371,6 +374,7 @@ function readableSearchRootsForUser (user, config, roots)
371
374
372const SEARCHABLE_IMAGE_EXTS = new Set([
375const SEARCHABLE_IMAGE_EXTS = new Set([
373 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
376 '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff',
377 '.heif', '.heic',
374]);
378]);
375
379
376function isSearchableImageFileName (name)
380function isSearchableImageFileName (name)
@@ -1804,6 +1808,53 @@ router.get('/download-zip', requireAuth, async (req, res) =>
1804 }
1808 }
1805});
1809});
1806
1810
1811// ---------------------------------------------------------------------------
1812// GET /api/files/preview-image?file=<absolute-path>
1813// Converts HEIF/HEIC sources to WebP for in-browser preview.
1814// ---------------------------------------------------------------------------
1815router.get('/preview-image', requireAuth, async (req, res) =>
1816{
1817 const file = req.query.file;
1818 if (!file) return res.status(400).json({ error: 'file is required.' });
1819
1820 const { config, roots } = loadConfigAndRoots();
1821 const info = resolveRootForUser(file, roots, req.user, config);
1822 if (!info || !canReadInfo(req.user, info))
1823 {
1824 return res.status(403).json({ error: 'Access denied.' });
1825 }
1826
1827 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1828 {
1829 return res.status(404).json({ error: 'File not found.' });
1830 }
1831
1832 if (!needsPreviewImageConversion(file))
1833 {
1834 return res.status(400).json({ error: 'Preview conversion is not available for this file type.' });
1835 }
1836
1837 let stat;
1838 try { stat = fs.statSync(file); } catch { return res.status(404).json({ error: 'File not found.' }); }
1839
1840 if (stat.size > MAX_PREVIEW_IMAGE_BYTES)
1841 {
1842 return res.status(413).json({ error: 'File too large for inline preview.' });
1843 }
1844
1845 try
1846 {
1847 await streamPreviewImage(file, res);
1848 } catch (err)
1849 {
1850 logError('preview-image', err);
1851 if (!res.headersSent)
1852 {
1853 res.status(500).json({ error: 'Failed to generate preview image.' });
1854 }
1855 }
1856});
1857
1807// ---------------------------------------------------------------------------
1858// ---------------------------------------------------------------------------
1808// GET /api/files/thumbnail?file=<absolute-path>
1859// GET /api/files/thumbnail?file=<absolute-path>
1809// Returns a pre-generated cached thumbnail if present.
1860// Returns a pre-generated cached thumbnail if present.
server/routes/share.js +1 −1
@@ -708,7 +708,7 @@ router.get('/download/:token', async (req, res) =>
708 708 // ---------------------------------------------------------------------------
709 709
710 710 const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
711 const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
711 const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp', 'heif', 'heic']);
712 712
713 713 function ogEsc (s)
714 714 {
@@ -708,7 +708,7 @@ router.get('/download/:token', async (req, res) =>
708// ---------------------------------------------------------------------------
708// ---------------------------------------------------------------------------
709
709
710const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
710const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
711const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
711const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp', 'heif', 'heic']);
712
712
713function ogEsc (s)
713function ogEsc (s)
714{
714{
server/thumbnail-cache.js +30 −0
@@ -17,7 +17,11 @@ const THUMB_HTTP_MAX_AGE_SEC = toPositiveInt(process.env.THUMBNAIL_HTTP_MAX_AGE_
17 17
18 18 const IMAGE_EXTS = new Set([
19 19 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'svg', 'ico',
20 'heif', 'heic',
20 21 ]);
22 const PREVIEW_CONVERT_EXTS = new Set(['heif', 'heic']);
23 const MAX_PREVIEW_IMAGE_BYTES = 50 * 1024 * 1024;
24 const PREVIEW_IMAGE_MAX_DIMENSION = 4096;
21 25 const VIDEO_EXTS = new Set([
22 26 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
23 27 ]);
@@ -362,6 +366,29 @@ async function generateImageThumb (sourceFile, thumbPath)
362 366 .toFile(thumbPath);
363 367 }
364 368
369 function needsPreviewImageConversion (filePath)
370 {
371 const ext = path.extname(filePath).slice(1).toLowerCase();
372 return PREVIEW_CONVERT_EXTS.has(ext);
373 }
374
375 async function streamPreviewImage (sourceFile, res)
376 {
377 const pipeline = sharp(sourceFile)
378 .rotate()
379 .resize({
380 width: PREVIEW_IMAGE_MAX_DIMENSION,
381 height: PREVIEW_IMAGE_MAX_DIMENSION,
382 fit: 'inside',
383 withoutEnlargement: true,
384 })
385 .webp({ quality: 85 });
386
387 res.type('image/webp');
388 res.set('Cache-Control', 'private, no-store');
389 await pipeline.toBuffer().then((buf) => res.send(buf));
390 }
391
365 392 async function generateVideoThumb (sourceFile, thumbPath)
366 393 {
367 394 await ensureDir(path.dirname(thumbPath));
@@ -979,5 +1006,8 @@ module.exports = {
979 1006 startThumbnailCacheLoop,
980 1007 stopThumbnailCacheLoop,
981 1008 syncThumbnailCacheOnce,
1009 needsPreviewImageConversion,
1010 streamPreviewImage,
1011 MAX_PREVIEW_IMAGE_BYTES,
982 1012 THUMB_HTTP_MAX_AGE_SEC,
983 1013 };
@@ -17,7 +17,11 @@ const THUMB_HTTP_MAX_AGE_SEC = toPositiveInt(process.env.THUMBNAIL_HTTP_MAX_AGE_
17
17
18const IMAGE_EXTS = new Set([
18const IMAGE_EXTS = new Set([
19 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'svg', 'ico',
19 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'svg', 'ico',
20 'heif', 'heic',
20]);
21]);
22const PREVIEW_CONVERT_EXTS = new Set(['heif', 'heic']);
23const MAX_PREVIEW_IMAGE_BYTES = 50 * 1024 * 1024;
24const PREVIEW_IMAGE_MAX_DIMENSION = 4096;
21const VIDEO_EXTS = new Set([
25const VIDEO_EXTS = new Set([
22 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
26 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
23]);
27]);
@@ -362,6 +366,29 @@ async function generateImageThumb (sourceFile, thumbPath)
362 .toFile(thumbPath);
366 .toFile(thumbPath);
363}
367}
364
368
369function needsPreviewImageConversion (filePath)
370{
371 const ext = path.extname(filePath).slice(1).toLowerCase();
372 return PREVIEW_CONVERT_EXTS.has(ext);
373}
374
375async function streamPreviewImage (sourceFile, res)
376{
377 const pipeline = sharp(sourceFile)
378 .rotate()
379 .resize({
380 width: PREVIEW_IMAGE_MAX_DIMENSION,
381 height: PREVIEW_IMAGE_MAX_DIMENSION,
382 fit: 'inside',
383 withoutEnlargement: true,
384 })
385 .webp({ quality: 85 });
386
387 res.type('image/webp');
388 res.set('Cache-Control', 'private, no-store');
389 await pipeline.toBuffer().then((buf) => res.send(buf));
390}
391
365async function generateVideoThumb (sourceFile, thumbPath)
392async function generateVideoThumb (sourceFile, thumbPath)
366{
393{
367 await ensureDir(path.dirname(thumbPath));
394 await ensureDir(path.dirname(thumbPath));
@@ -979,5 +1006,8 @@ module.exports = {
979 startThumbnailCacheLoop,
1006 startThumbnailCacheLoop,
980 stopThumbnailCacheLoop,
1007 stopThumbnailCacheLoop,
981 syncThumbnailCacheOnce,
1008 syncThumbnailCacheOnce,
1009 needsPreviewImageConversion,
1010 streamPreviewImage,
1011 MAX_PREVIEW_IMAGE_BYTES,
982 THUMB_HTTP_MAX_AGE_SEC,
1012 THUMB_HTTP_MAX_AGE_SEC,
983};
1013};
start.sh +0 −0
tests/files.routes.test.js +34 −0
@@ -124,6 +124,16 @@ jest.mock('../server/thumbnail-cache', () => ({
124 124 {
125 125 lastFolderIconAssignment = { folderPath, imagePath };
126 126 },
127 needsPreviewImageConversion: (filePath) =>
128 {
129 const ext = String(filePath || '').split('.').pop().toLowerCase();
130 return ext === 'heif' || ext === 'heic';
131 },
132 streamPreviewImage: async (_sourceFile, res) =>
133 {
134 res.type('image/webp').send(Buffer.from('preview-webp'));
135 },
136 MAX_PREVIEW_IMAGE_BYTES: 50 * 1024 * 1024,
127 137 THUMB_HTTP_MAX_AGE_SEC: 3600,
128 138 }));
129 139
@@ -673,6 +683,30 @@ describe('last visited folder persistence', () =>
673 683 });
674 684 });
675 685
686 describe('GET /api/files/preview-image', () =>
687 {
688 test('returns converted WebP for HEIC files', async () =>
689 {
690 const source = path.join(rootDir, 'photo.heic');
691 fs.writeFileSync(source, 'heic-bytes');
692
693 const response = await reqRaw('GET', `/api/files/preview-image?file=${encodeURIComponent(source)}`);
694 expect(response.status).toBe(200);
695 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
696 expect(response.body.toString('utf8')).toBe('preview-webp');
697 });
698
699 test('rejects file types that do not need conversion', async () =>
700 {
701 const source = path.join(rootDir, 'photo.jpg');
702 fs.writeFileSync(source, 'jpg-bytes');
703
704 const { status, body } = await req('GET', `/api/files/preview-image?file=${encodeURIComponent(source)}`);
705 expect(status).toBe(400);
706 expect(body.error).toMatch(/not available/i);
707 });
708 });
709
676 710 describe('GET /api/files/thumbnail', () =>
677 711 {
678 712 test('returns 404 while cached thumbnail is not ready', async () =>
@@ -124,6 +124,16 @@ jest.mock('../server/thumbnail-cache', () => ({
124 {
124 {
125 lastFolderIconAssignment = { folderPath, imagePath };
125 lastFolderIconAssignment = { folderPath, imagePath };
126 },
126 },
127 needsPreviewImageConversion: (filePath) =>
128 {
129 const ext = String(filePath || '').split('.').pop().toLowerCase();
130 return ext === 'heif' || ext === 'heic';
131 },
132 streamPreviewImage: async (_sourceFile, res) =>
133 {
134 res.type('image/webp').send(Buffer.from('preview-webp'));
135 },
136 MAX_PREVIEW_IMAGE_BYTES: 50 * 1024 * 1024,
127 THUMB_HTTP_MAX_AGE_SEC: 3600,
137 THUMB_HTTP_MAX_AGE_SEC: 3600,
128}));
138}));
129
139
@@ -673,6 +683,30 @@ describe('last visited folder persistence', () =>
673 });
683 });
674});
684});
675
685
686describe('GET /api/files/preview-image', () =>
687{
688 test('returns converted WebP for HEIC files', async () =>
689 {
690 const source = path.join(rootDir, 'photo.heic');
691 fs.writeFileSync(source, 'heic-bytes');
692
693 const response = await reqRaw('GET', `/api/files/preview-image?file=${encodeURIComponent(source)}`);
694 expect(response.status).toBe(200);
695 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
696 expect(response.body.toString('utf8')).toBe('preview-webp');
697 });
698
699 test('rejects file types that do not need conversion', async () =>
700 {
701 const source = path.join(rootDir, 'photo.jpg');
702 fs.writeFileSync(source, 'jpg-bytes');
703
704 const { status, body } = await req('GET', `/api/files/preview-image?file=${encodeURIComponent(source)}`);
705 expect(status).toBe(400);
706 expect(body.error).toMatch(/not available/i);
707 });
708});
709
676describe('GET /api/files/thumbnail', () =>
710describe('GET /api/files/thumbnail', () =>
677{
711{
678 test('returns 404 while cached thumbnail is not ready', async () =>
712 test('returns 404 while cached thumbnail is not ready', async () =>
tests/page.load.test.js +117 −0
@@ -116,6 +116,16 @@ describe('page load smoke test', () =>
116 116 }
117 117 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
118 118 });
119 app.get('/api/files/preview-image', (req, res) =>
120 {
121 const file = String(req.query.file || '');
122 const payload = downloadFixture[file];
123 if (!payload)
124 {
125 return res.status(404).json({ error: 'File not found.' });
126 }
127 res.type('image/webp').send(payload.previewBody || 'converted-preview');
128 });
119 129 app.get('/api/files/meta', (req, res) =>
120 130 {
121 131 const file = String(req.query.file || '');
@@ -1656,6 +1666,113 @@ describe('page load smoke test', () =>
1656 1666 dom.window.close();
1657 1667 });
1658 1668
1669 test('expanded video preview download fetches the original file', async () =>
1670 {
1671 listFixture['/data'] = [
1672 {
1673 name: 'clip.mkv',
1674 path: '/data/clip.mkv',
1675 isDir: false,
1676 size: 64,
1677 mtime: Date.now(),
1678 },
1679 ];
1680 downloadFixture['/data/clip.mkv'] = {
1681 type: 'video/x-matroska',
1682 body: 'video-bytes',
1683 };
1684 videoStreamFixture['/data/clip.mkv'] = {
1685 sessionId: 'video-session',
1686 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
1687 durationSeconds: 120,
1688 subtitleTracks: [],
1689 };
1690
1691 const { dom, runtimeErrors } = await bootClient();
1692 expect(runtimeErrors).toEqual([]);
1693
1694 const downloadUrls = [];
1695 let popupHref = '';
1696 const popup = {
1697 location: {},
1698 close () { },
1699 };
1700 Object.defineProperty(popup.location, 'href', {
1701 get () { return popupHref; },
1702 set (value) { popupHref = String(value || ''); },
1703 configurable: true,
1704 });
1705 const nativeFetch = dom.window.fetch.bind(dom.window);
1706 dom.window.open = () => popup;
1707 dom.window.fetch = (input, init) =>
1708 {
1709 const url = typeof input === 'string' ? input : input.url;
1710 if (url.includes('/api/files/download?'))
1711 {
1712 downloadUrls.push(url);
1713 }
1714 return nativeFetch(input, init);
1715 };
1716
1717 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
1718
1719 const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
1720 fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
1721 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
1722
1723 const downloadBtn = dom.window.document.querySelector('.preview-expand-download');
1724 downloadBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
1725
1726 await waitFor(dom, () => downloadUrls.length > 0 && popupHref.startsWith('blob:'));
1727 expect(downloadUrls[0]).toContain(encodeURIComponent('/data/clip.mkv'));
1728
1729 dom.window.close();
1730 });
1731
1732 test('expanded HEIF preview uses converted preview image endpoint', async () =>
1733 {
1734 listFixture['/data'] = [
1735 {
1736 name: 'photo.heic',
1737 path: '/data/photo.heic',
1738 isDir: false,
1739 size: 4096,
1740 mtime: Date.now(),
1741 },
1742 ];
1743 downloadFixture['/data/photo.heic'] = {
1744 type: 'image/heic',
1745 body: 'heic-bytes',
1746 previewBody: 'webp-preview',
1747 };
1748
1749 const { dom, runtimeErrors } = await bootClient();
1750 expect(runtimeErrors).toEqual([]);
1751
1752 const previewUrls = [];
1753 const nativeFetch = dom.window.fetch.bind(dom.window);
1754 dom.window.fetch = (input, init) =>
1755 {
1756 const url = typeof input === 'string' ? input : input.url;
1757 if (url.includes('/api/files/preview-image?'))
1758 {
1759 previewUrls.push(url);
1760 }
1761 return nativeFetch(input, init);
1762 };
1763
1764 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/photo.heic"]'));
1765
1766 const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/photo.heic"]');
1767 fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
1768 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-expand-content img.preview-media'));
1769
1770 expect(previewUrls.length).toBeGreaterThan(0);
1771 expect(previewUrls[0]).toContain(encodeURIComponent('/data/photo.heic'));
1772
1773 dom.window.close();
1774 });
1775
1659 1776 test('expanded video preview uses a stream session and video.js', async () =>
1660 1777 {
1661 1778 listFixture['/data'] = [
@@ -116,6 +116,16 @@ describe('page load smoke test', () =>
116 }
116 }
117 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
117 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
118 });
118 });
119 app.get('/api/files/preview-image', (req, res) =>
120 {
121 const file = String(req.query.file || '');
122 const payload = downloadFixture[file];
123 if (!payload)
124 {
125 return res.status(404).json({ error: 'File not found.' });
126 }
127 res.type('image/webp').send(payload.previewBody || 'converted-preview');
128 });
119 app.get('/api/files/meta', (req, res) =>
129 app.get('/api/files/meta', (req, res) =>
120 {
130 {
121 const file = String(req.query.file || '');
131 const file = String(req.query.file || '');
@@ -1656,6 +1666,113 @@ describe('page load smoke test', () =>
1656 dom.window.close();
1666 dom.window.close();
1657 });
1667 });
1658
1668
1669 test('expanded video preview download fetches the original file', async () =>
1670 {
1671 listFixture['/data'] = [
1672 {
1673 name: 'clip.mkv',
1674 path: '/data/clip.mkv',
1675 isDir: false,
1676 size: 64,
1677 mtime: Date.now(),
1678 },
1679 ];
1680 downloadFixture['/data/clip.mkv'] = {
1681 type: 'video/x-matroska',
1682 body: 'video-bytes',
1683 };
1684 videoStreamFixture['/data/clip.mkv'] = {
1685 sessionId: 'video-session',
1686 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
1687 durationSeconds: 120,
1688 subtitleTracks: [],
1689 };
1690
1691 const { dom, runtimeErrors } = await bootClient();
1692 expect(runtimeErrors).toEqual([]);
1693
1694 const downloadUrls = [];
1695 let popupHref = '';
1696 const popup = {
1697 location: {},
1698 close () { },
1699 };
1700 Object.defineProperty(popup.location, 'href', {
1701 get () { return popupHref; },
1702 set (value) { popupHref = String(value || ''); },
1703 configurable: true,
1704 });
1705 const nativeFetch = dom.window.fetch.bind(dom.window);
1706 dom.window.open = () => popup;
1707 dom.window.fetch = (input, init) =>
1708 {
1709 const url = typeof input === 'string' ? input : input.url;
1710 if (url.includes('/api/files/download?'))
1711 {
1712 downloadUrls.push(url);
1713 }
1714 return nativeFetch(input, init);
1715 };
1716
1717 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
1718
1719 const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
1720 fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
1721 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
1722
1723 const downloadBtn = dom.window.document.querySelector('.preview-expand-download');
1724 downloadBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
1725
1726 await waitFor(dom, () => downloadUrls.length > 0 && popupHref.startsWith('blob:'));
1727 expect(downloadUrls[0]).toContain(encodeURIComponent('/data/clip.mkv'));
1728
1729 dom.window.close();
1730 });
1731
1732 test('expanded HEIF preview uses converted preview image endpoint', async () =>
1733 {
1734 listFixture['/data'] = [
1735 {
1736 name: 'photo.heic',
1737 path: '/data/photo.heic',
1738 isDir: false,
1739 size: 4096,
1740 mtime: Date.now(),
1741 },
1742 ];
1743 downloadFixture['/data/photo.heic'] = {
1744 type: 'image/heic',
1745 body: 'heic-bytes',
1746 previewBody: 'webp-preview',
1747 };
1748
1749 const { dom, runtimeErrors } = await bootClient();
1750 expect(runtimeErrors).toEqual([]);
1751
1752 const previewUrls = [];
1753 const nativeFetch = dom.window.fetch.bind(dom.window);
1754 dom.window.fetch = (input, init) =>
1755 {
1756 const url = typeof input === 'string' ? input : input.url;
1757 if (url.includes('/api/files/preview-image?'))
1758 {
1759 previewUrls.push(url);
1760 }
1761 return nativeFetch(input, init);
1762 };
1763
1764 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/photo.heic"]'));
1765
1766 const fileTile = dom.window.document.querySelector('.file-item[data-path="/data/photo.heic"]');
1767 fileTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
1768 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-expand-content img.preview-media'));
1769
1770 expect(previewUrls.length).toBeGreaterThan(0);
1771 expect(previewUrls[0]).toContain(encodeURIComponent('/data/photo.heic'));
1772
1773 dom.window.close();
1774 });
1775
1659 test('expanded video preview uses a stream session and video.js', async () =>
1776 test('expanded video preview uses a stream session and video.js', async () =>
1660 {
1777 {
1661 listFixture['/data'] = [
1778 listFixture['/data'] = [