BlueGit

timfa filemanager

Files

filemanager / public / share.html

share.html

Client-side caching
timfa Tim Falken · pushed by timfa · 5 months ago
943484ae History
share.html 20.8 KiB Download Raw
1<!DOCTYPE html>
2<html lang="en-GB">
3
4<head>
5 <meta charset="UTF-8" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <title>Shared file</title>
8 <link rel="stylesheet" href="/vendor/video.js/video-js.css" />
9 <style>
10 *,
11 *::before,
12 *::after {
13 box-sizing: border-box;
14 margin: 0;
15 padding: 0;
16 }
17
18 :root {
19 --bg: #0f1117;
20 --surface: #1a1d27;
21 --surface2: #21242f;
22 --border: #2e3247;
23 --accent: #5b7fff;
24 --accent-hover: #7b9fff;
25 --text: #e8eaf0;
26 --text-muted: #7880a0;
27 --danger: #e05c6e;
28 --success: #3fcf8e;
29 --radius: 10px;
30 }
31
32 html,
33 body {
34 height: 100%;
35 font-family: system-ui, -apple-system, sans-serif;
36 }
37
38 body {
39 background: var(--bg);
40 color: var(--text);
41 min-height: 100vh;
42 }
43
44 /* ── Timer bar ── */
45 #timer-bar {
46 position: sticky;
47 top: 0;
48 z-index: 10;
49 background: var(--surface);
50 border-bottom: 1px solid var(--border);
51 display: flex;
52 align-items: center;
53 justify-content: center;
54 gap: 0.6rem;
55 padding: 0.55rem 1rem;
56 font-size: 0.9rem;
57 color: var(--text-muted);
58 }
59
60 #timer-bar .timer-clock {
61 font-variant-numeric: tabular-nums;
62 font-weight: 600;
63 color: var(--text);
64 letter-spacing: 0.05em;
65 }
66
67 #timer-bar.expired {
68 color: var(--danger);
69 }
70
71 #timer-bar.expired .timer-clock {
72 color: var(--danger);
73 }
74
75 /* ── Main card ── */
76 #main {
77 max-width: 760px;
78 margin: 3rem auto;
79 padding: 0 1rem;
80 }
81
82 .card {
83 background: var(--surface);
84 border: 1px solid var(--border);
85 border-radius: var(--radius);
86 padding: 2rem;
87 margin-bottom: 1.5rem;
88 }
89
90 .card h1 {
91 font-size: 1.3rem;
92 font-weight: 600;
93 margin-bottom: 0.3rem;
94 word-break: break-all;
95 }
96
97 .card .meta {
98 font-size: 0.85rem;
99 color: var(--text-muted);
100 margin-bottom: 1.4rem;
101 }
102
103 /* ── Download button ── */
104 .btn {
105 display: inline-flex;
106 align-items: center;
107 gap: 0.5rem;
108 padding: 0.6rem 1.2rem;
109 border-radius: 7px;
110 font-size: 0.92rem;
111 font-weight: 500;
112 cursor: pointer;
113 border: none;
114 transition: background 0.15s;
115 }
116
117 .btn-primary {
118 background: var(--accent);
119 color: #fff;
120 }
121
122 .btn-primary:hover {
123 background: var(--accent-hover);
124 }
125
126 .btn-primary:disabled {
127 opacity: 0.45;
128 cursor: not-allowed;
129 }
130
131 /* ── Preview area ── */
132 #preview-wrap {
133 background: var(--surface2);
134 border: 1px solid var(--border);
135 border-radius: var(--radius);
136 overflow: hidden;
137 margin-bottom: 1.5rem;
138 min-height: 80px;
139 display: flex;
140 align-items: center;
141 justify-content: center;
142 }
143
144 #preview-wrap img,
145 #preview-wrap video,
146 #preview-wrap audio,
147 #preview-wrap .video-js {
148 max-width: 100%;
149 max-height: 60vh;
150 display: block;
151 }
152
153 #preview-wrap .video-js {
154 width: 100%;
155 min-height: 360px;
156 background: #000;
157 }
158
159 #preview-wrap .video-js .vjs-tech {
160 object-fit: contain;
161 }
162
163 #preview-wrap audio {
164 padding: 1rem;
165 width: 100%;
166 }
167
168 #preview-wrap pre {
169 padding: 1.2rem;
170 overflow: auto;
171 max-height: 60vh;
172 width: 100%;
173 font-size: 0.82rem;
174 font-family: monospace;
175 color: var(--text);
176 white-space: pre-wrap;
177 word-break: break-word;
178 }
179
180 #preview-wrap .no-preview {
181 padding: 2rem;
182 color: var(--text-muted);
183 font-size: 0.9rem;
184 text-align: center;
185 }
186
187 /* ── Error / expired states ── */
188 #error-state {
189 text-align: center;
190 padding: 4rem 1rem;
191 }
192
193 #error-state h2 {
194 font-size: 1.4rem;
195 margin-bottom: 0.5rem;
196 }
197
198 #error-state p {
199 color: var(--text-muted);
200 }
201
202 /* ── Loading spinner ── */
203 #loading {
204 text-align: center;
205 padding: 6rem 1rem;
206 color: var(--text-muted);
207 }
208 </style>
209</head>
210
211<body>
212
213 <div id="timer-bar" style="display:none">
214 <span>Valid for</span>
215 <span id="timer-clock" class="timer-clock">--:--:--</span>
216 </div>
217
218 <div id="main">
219 <div id="loading">Loading...</div>
220 <div id="error-state" style="display:none">
221 <h2 id="error-title">Not found</h2>
222 <p id="error-msg">This link does not exist or has expired.</p>
223 </div>
224
225 <div id="content" style="display:none">
226 <div class="card">
227 <h1 id="file-name"></h1>
228 <p id="file-meta" class="meta"></p>
229 <a id="btn-download" class="btn btn-primary" href="#" download>
230 <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
231 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
232 <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
233 <polyline points="7 10 12 15 17 10" />
234 <line x1="12" y1="15" x2="12" y2="3" />
235 </svg>
236 <span id="btn-download-label">Download</span>
237 </a>
238 </div>
239
240 <div id="preview-wrap" style="display:none"></div>
241 </div>
242 </div>
243
244 <script src="/shared-video-player.js"></script>
245 <script>
246 (function ()
247 {
248 'use strict';
249
250 const token = location.pathname.split('/').pop();
251 const VIDEO_FORWARD_BUFFER_SECONDS = 60 * 60;
252 const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS = 15;
253 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
254 const SHARE_VIDEO_PREFS_KEY = 'filemanager.share-video-prefs.v1';
255 let expiresAt = null;
256 let timerInterval = null;
257 let shareVideoPlayer = null;
258 let shareTrackPrefs = null;
259 let shareImageSubtitleController = null;
260 let shareVideoSessionId = null;
261
262 function sharedVideoPlayer ()
263 {
264 return window.FilemanagerSharedVideoPlayer || null;
265 }
266
267 function loadShareVideoPrefs ()
268 {
269 try
270 {
271 const raw = localStorage.getItem(SHARE_VIDEO_PREFS_KEY);
272 const parsed = raw ? JSON.parse(raw) : {};
273 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
274 return parsed;
275 } catch
276 {
277 return {};
278 }
279 }
280
281 function saveShareVideoPrefs (patch)
282 {
283 try
284 {
285 const current = loadShareVideoPrefs();
286 localStorage.setItem(SHARE_VIDEO_PREFS_KEY, JSON.stringify({ ...current, ...(patch || {}) }));
287 } catch
288 {
289 // Ignore localStorage failures.
290 }
291 }
292
293 function applyShareVideoTextTrackPrefs ()
294 {
295 const shared = sharedVideoPlayer();
296 if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return;
297 shared.applyDefaultTextTrackPrefs();
298 }
299
300 function bindShareVideoTrackPrefs (player, prefs)
301 {
302 const shared = sharedVideoPlayer();
303 if (!shared || typeof shared.bindTrackPrefs !== 'function')
304 {
305 return {
306 applySavedTracks: () => { },
307 captureSelectedTracks: () => { },
308 detach: () => { },
309 };
310 }
311 return shared.bindTrackPrefs(player, prefs, saveShareVideoPrefs);
312 }
313
314 function releaseShareVideoSession (sessionId, opts = {})
315 {
316 const id = String(sessionId || '').trim();
317 if (!id) return Promise.resolve();
318
319 return fetch(`/api/share/video-stream/session/${encodeURIComponent(id)}`, {
320 method: 'DELETE',
321 credentials: 'same-origin',
322 keepalive: !!opts.keepalive,
323 }).catch(() => null);
324 }
325
326 function cleanupShareVideoPlayer ()
327 {
328 const sessionId = shareVideoSessionId;
329 shareVideoSessionId = null;
330 const playlistUrl = shareVideoPlayer && typeof shareVideoPlayer.currentSrc === 'function'
331 ? String(shareVideoPlayer.currentSrc() || '').trim()
332 : null;
333
334 try { shareImageSubtitleController && shareImageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
335 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
336 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
337 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
338 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
339
340 void clearVideoStreamClientCache(playlistUrl);
341 if (sessionId) void releaseShareVideoSession(sessionId, { keepalive: true });
342
343 shareVideoPlayer = null;
344 shareTrackPrefs = null;
345 shareImageSubtitleController = null;
346 }
347
348 function configureVideoJsBuffering ()
349 {
350 const shared = sharedVideoPlayer();
351 if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return;
352 shared.configureVideoJsBuffering(window.videojs, { seconds: VIDEO_FORWARD_BUFFER_SECONDS });
353 }
354
355 function enableVideoStreamClientCache ()
356 {
357 const shared = sharedVideoPlayer();
358 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
359 return shared.enableVideoStreamClientCache();
360 }
361
362 function clearVideoStreamClientCache (playlistUrl)
363 {
364 const shared = sharedVideoPlayer();
365 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
366 return shared.clearVideoStreamClientCache(playlistUrl);
367 }
368
369 // ── Timer ───────────────────────────────────────────────────────────────
370 function startTimer ()
371 {
372 const bar = document.getElementById('timer-bar');
373 const clock = document.getElementById('timer-clock');
374 bar.style.display = '';
375
376 function tick ()
377 {
378 const remaining = expiresAt - Date.now();
379 if (remaining <= 0)
380 {
381 clock.textContent = '00:00:00';
382 bar.classList.add('expired');
383 bar.querySelector('span').textContent = 'Expired —';
384 const dlBtn = document.getElementById('btn-download');
385 if (dlBtn) dlBtn.setAttribute('disabled', 'disabled');
386 clearInterval(timerInterval);
387 return;
388 }
389 const totalSecs = Math.floor(remaining / 1000);
390 const hh = String(Math.floor(totalSecs / 3600)).padStart(2, '0');
391 const mm = String(Math.floor((totalSecs % 3600) / 60)).padStart(2, '0');
392 const ss = String(totalSecs % 60).padStart(2, '0');
393 clock.textContent = `${hh}:${mm}:${ss}`;
394 }
395
396 tick();
397 timerInterval = setInterval(tick, 1000);
398 }
399
400 // ── Preview ──────────────────────────────────────────────────────────────
401 function normaliseVideoDuration (player, durationSeconds)
402 {
403 const shared = sharedVideoPlayer();
404 if (!shared || typeof shared.normaliseVideoDuration !== 'function') return;
405 shared.normaliseVideoDuration(player, durationSeconds);
406 }
407
408 function ensureVideoPlaybackUi (player, durationSeconds)
409 {
410 const shared = sharedVideoPlayer();
411 if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return;
412 shared.ensureVideoPlaybackUi(player, durationSeconds);
413 }
414
415 function tryPreview (name, isDir)
416 {
417 if (isDir) return; // no preview for folders
418
419 const wrap = document.getElementById('preview-wrap');
420 const ext = name.split('.').pop().toLowerCase();
421
422 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico'];
423 const videoExts = ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'];
424 const audioExts = ['mp3', 'wav', 'ogg', 'flac', 'aac', 'opus', 'm4a'];
425 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'];
426
427 const previewUrl = `/api/share/preview/${token}`;
428 let el;
429
430 if (imageExts.includes(ext))
431 {
432 el = document.createElement('img');
433 el.src = previewUrl;
434 el.alt = name;
435 } else if (videoExts.includes(ext))
436 {
437 enableVideoStreamClientCache().catch(() => false);
438 fetch(`/api/share/video-stream/${token}`)
439 .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
440 .then(({ ok, data }) =>
441 {
442 if (!ok) throw new Error(data.error || 'Streaming failed');
443 configureVideoJsBuffering();
444 applyShareVideoTextTrackPrefs();
445 const prefs = loadShareVideoPrefs();
446
447 const video = document.createElement('video');
448 video.className = 'video-js vjs-big-play-centered';
449 video.controls = true;
450 video.preload = 'auto';
451 video.playsInline = true;
452
453 wrap.innerHTML = '';
454 wrap.appendChild(video);
455
456 cleanupShareVideoPlayer();
457 shareVideoSessionId = String(data.sessionId || '').trim() || null;
458
459 shareVideoPlayer = window.videojs(video, {
460 controls: true,
461 fluid: true,
462 responsive: true,
463 preload: 'auto',
464 controlBar: {
465 currentTimeDisplay: true,
466 timeDivider: true,
467 durationDisplay: true,
468 remainingTimeDisplay: false,
469 },
470 sources: [{ src: data.playlistUrl, type: 'application/x-mpegURL' }],
471 tracks: (data.subtitleTracks || []).map(track => ({
472 kind: 'subtitles',
473 src: track.src,
474 srclang: track.language || 'und',
475 label: track.label,
476 default: !!track.default,
477 })),
478 });
479
480 shareTrackPrefs = bindShareVideoTrackPrefs(shareVideoPlayer, prefs);
481 const shared = sharedVideoPlayer();
482 shareImageSubtitleController = shared && typeof shared.bindImageSubtitleOverlay === 'function'
483 ? shared.bindImageSubtitleOverlay(shareVideoPlayer, window.videojs, prefs, data, {
484 savePrefs: saveShareVideoPrefs,
485 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
486 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
487 sendSubtitleLogBatch: (entries) =>
488 {
489 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
490 return fetch(`/api/share/video-stream-subtitle-log/${encodeURIComponent(token)}`, {
491 method: 'POST',
492 credentials: 'same-origin',
493 keepalive: true,
494 headers: {
495 'Content-Type': 'application/json',
496 },
497 body: JSON.stringify({
498 sessionId: data.sessionId || null,
499 entries,
500 }),
501 }).catch(() => null);
502 },
503 buildFrameRequest: ({ currentTime, streamIndex, session }) => ({
504 url: `/api/share/video-stream-subtitle-frame/${encodeURIComponent(token)}?streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`,
505 credentials: 'same-origin',
506 }),
507 })
508 : null;
509 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
510
511 shareVideoPlayer.ready(() =>
512 {
513 const volume = Number(prefs.volume);
514 if (Number.isFinite(volume))
515 {
516 shareVideoPlayer.volume(Math.max(0, Math.min(1, volume)));
517 }
518 shareTrackPrefs.applySavedTracks();
519 if (shareImageSubtitleController && typeof shareImageSubtitleController.applySavedTracks === 'function')
520 {
521 shareImageSubtitleController.applySavedTracks();
522 }
523 });
524
525 shareVideoPlayer.on('loadedmetadata', shareTrackPrefs.applySavedTracks);
526 shareVideoPlayer.on('loadedplaylist', shareTrackPrefs.applySavedTracks);
527 shareVideoPlayer.on('volumechange', () =>
528 {
529 const v = Number(shareVideoPlayer.volume());
530 if (Number.isFinite(v)) saveShareVideoPrefs({ volume: v });
531 });
532
533 wrap.style.display = '';
534 })
535 .catch(() =>
536 {
537 wrap.innerHTML = '<div class="no-preview">No preview available.</div>';
538 wrap.style.display = '';
539 });
540 return;
541 } else if (audioExts.includes(ext))
542 {
543 el = document.createElement('audio');
544 el.src = previewUrl;
545 el.controls = true;
546 } else if (textExts.includes(ext))
547 {
548 fetch(previewUrl)
549 .then(r =>
550 {
551 if (!r.ok) throw new Error('preview failed');
552 return r.text();
553 })
554 .then(text =>
555 {
556 const pre = document.createElement('pre');
557 pre.textContent = text;
558 wrap.innerHTML = '';
559 wrap.appendChild(pre);
560 wrap.style.display = '';
561 })
562 .catch(() => { /* no preview available */ });
563 return;
564 } else
565 {
566 return; // no preview
567 }
568
569 el.addEventListener('error', () => { wrap.innerHTML = '<div class="no-preview">No preview available.</div>'; wrap.style.display = ''; });
570 wrap.innerHTML = '';
571 wrap.appendChild(el);
572 wrap.style.display = '';
573 }
574
575 // ── Boot ─────────────────────────────────────────────────────────────────
576 function showError (title, msg)
577 {
578 document.getElementById('loading').style.display = 'none';
579 document.getElementById('content').style.display = 'none';
580 document.getElementById('error-title').textContent = title;
581 document.getElementById('error-msg').textContent = msg;
582 document.getElementById('error-state').style.display = '';
583 }
584
585 function formatBytes (bytes)
586 {
587 if (bytes == null) return '';
588 if (bytes < 1024) return bytes + ' B';
589 if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
590 if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
591 return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
592 }
593
594 fetch(`/api/share/info/${token}`)
595 .then(r => r.json().then(d => ({ ok: r.ok, status: r.status, data: d })))
596 .then(({ ok, status, data }) =>
597 {
598 document.getElementById('loading').style.display = 'none';
599
600 if (status === 410)
601 {
602 showError('Link expired', 'This share link is no longer valid.');
603 return;
604 }
605 if (!ok)
606 {
607 showError('Not found', data.error || 'This link does not exist.');
608 return;
609 }
610
611 expiresAt = data.expiresAt;
612 startTimer();
613
614 document.getElementById('file-name').textContent = data.name;
615 const metaLine = data.isDir ? 'Folder (download as .zip)' : 'File';
616 document.getElementById('file-meta').textContent = metaLine;
617
618 const dlBtn = document.getElementById('btn-download');
619 dlBtn.href = `/api/share/download/${token}`;
620 if (data.isDir)
621 {
622 document.getElementById('btn-download-label').textContent = 'Download as .zip';
623 dlBtn.download = data.name + '.zip';
624 } else
625 {
626 document.getElementById('btn-download-label').textContent = 'Download';
627 dlBtn.download = data.name;
628 }
629
630 document.getElementById('content').style.display = '';
631
632 tryPreview(data.name, data.isDir);
633 })
634 .catch(() =>
635 {
636 showError('Error', 'Could not reach the server.');
637 });
638
639 window.addEventListener('pagehide', cleanupShareVideoPlayer);
640 window.addEventListener('beforeunload', cleanupShareVideoPlayer);
641 }());
642 </script>
643 <script src="/vendor/video.js/video.min.js"></script>
644</body>
645
646</html>