BlueGit

timfa filemanager

Files

filemanager / public / share.html

share.html

dl video fix
timfa Tim Falken · pushed by timfa · 5 months ago
a0162cfc History
share.html 23.1 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_INITIAL_PREFETCH_SECONDS = 60;
254 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS = 40;
255 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_NEAR = 3;
256 const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_FAR = 10;
257 const SHARE_VIDEO_PREFS_KEY = 'filemanager.share-video-prefs.v1';
258 let expiresAt = null;
259 let timerInterval = null;
260 let shareVideoPlayer = null;
261 let shareTrackPrefs = null;
262 let shareImageSubtitleController = null;
263 let shareVideoSessionId = null;
264 let shareStreamAheadPrefetch = null;
265 let shareStreamAheadSeekMarker = null;
266
267 function sharedVideoPlayer ()
268 {
269 return window.FilemanagerSharedVideoPlayer || null;
270 }
271
272 function loadShareVideoPrefs ()
273 {
274 try
275 {
276 const raw = localStorage.getItem(SHARE_VIDEO_PREFS_KEY);
277 const parsed = raw ? JSON.parse(raw) : {};
278 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
279 return parsed;
280 } catch
281 {
282 return {};
283 }
284 }
285
286 function saveShareVideoPrefs (patch)
287 {
288 try
289 {
290 const current = loadShareVideoPrefs();
291 localStorage.setItem(SHARE_VIDEO_PREFS_KEY, JSON.stringify({ ...current, ...(patch || {}) }));
292 } catch
293 {
294 // Ignore localStorage failures.
295 }
296 }
297
298 function applyShareVideoTextTrackPrefs ()
299 {
300 const shared = sharedVideoPlayer();
301 if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return;
302 shared.applyDefaultTextTrackPrefs();
303 }
304
305 function bindShareVideoTrackPrefs (player, prefs)
306 {
307 const shared = sharedVideoPlayer();
308 if (!shared || typeof shared.bindTrackPrefs !== 'function')
309 {
310 return {
311 applySavedTracks: () => { },
312 captureSelectedTracks: () => { },
313 detach: () => { },
314 };
315 }
316 return shared.bindTrackPrefs(player, prefs, saveShareVideoPrefs);
317 }
318
319 function releaseShareVideoSession (sessionId, opts = {})
320 {
321 const id = String(sessionId || '').trim();
322 if (!id) return Promise.resolve();
323
324 return fetch(`/api/share/video-stream/session/${encodeURIComponent(id)}`, {
325 method: 'DELETE',
326 credentials: 'same-origin',
327 keepalive: !!opts.keepalive,
328 }).catch(() => null);
329 }
330
331 function cleanupShareVideoPlayer ()
332 {
333 const sessionId = shareVideoSessionId;
334 shareVideoSessionId = null;
335 const playlistUrl = shareVideoPlayer && typeof shareVideoPlayer.currentSrc === 'function'
336 ? String(shareVideoPlayer.currentSrc() || '').trim()
337 : null;
338
339 try { shareImageSubtitleController && shareImageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
340 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
341 try { shareTrackPrefs && shareTrackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
342 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
343 try { shareStreamAheadSeekMarker && shareStreamAheadSeekMarker.detach(); } catch { /* ignore */ }
344 try { shareStreamAheadPrefetch && shareStreamAheadPrefetch.stop(); } catch { /* ignore */ }
345 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
346
347 void clearVideoStreamClientCache(playlistUrl);
348 if (sessionId) void releaseShareVideoSession(sessionId, { keepalive: true });
349
350 shareVideoPlayer = null;
351 shareTrackPrefs = null;
352 shareImageSubtitleController = null;
353 shareStreamAheadSeekMarker = null;
354 shareStreamAheadPrefetch = null;
355 }
356
357 function configureVideoJsBuffering ()
358 {
359 const shared = sharedVideoPlayer();
360 if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return;
361 shared.configureVideoJsBuffering(window.videojs, { seconds: VIDEO_FORWARD_BUFFER_SECONDS });
362 }
363
364 function enableVideoStreamClientCache ()
365 {
366 const shared = sharedVideoPlayer();
367 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
368 return shared.enableVideoStreamClientCache();
369 }
370
371 function clearVideoStreamClientCache (playlistUrl)
372 {
373 const shared = sharedVideoPlayer();
374 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
375 return shared.clearVideoStreamClientCache(playlistUrl);
376 }
377
378 function bindStreamAheadPrefetch (playlistUrl)
379 {
380 const shared = sharedVideoPlayer();
381 if (!shared || typeof shared.bindStreamAheadPrefetch !== 'function') return null;
382 return shared.bindStreamAheadPrefetch({
383 playlistUrl,
384 credentials: 'same-origin',
385 });
386 }
387
388 function bindStreamAheadSeekMarker (player, streamAheadPrefetch)
389 {
390 const shared = sharedVideoPlayer();
391 if (!shared || typeof shared.bindStreamAheadSeekMarker !== 'function') return null;
392 return shared.bindStreamAheadSeekMarker(player, streamAheadPrefetch);
393 }
394
395 // ── Timer ───────────────────────────────────────────────────────────────
396 function startTimer ()
397 {
398 const bar = document.getElementById('timer-bar');
399 const clock = document.getElementById('timer-clock');
400 bar.style.display = '';
401
402 function tick ()
403 {
404 const remaining = expiresAt - Date.now();
405 if (remaining <= 0)
406 {
407 clock.textContent = '00:00:00';
408 bar.classList.add('expired');
409 bar.querySelector('span').textContent = 'Expired —';
410 const dlBtn = document.getElementById('btn-download');
411 if (dlBtn) dlBtn.setAttribute('disabled', 'disabled');
412 clearInterval(timerInterval);
413 return;
414 }
415 const totalSecs = Math.floor(remaining / 1000);
416 const hh = String(Math.floor(totalSecs / 3600)).padStart(2, '0');
417 const mm = String(Math.floor((totalSecs % 3600) / 60)).padStart(2, '0');
418 const ss = String(totalSecs % 60).padStart(2, '0');
419 clock.textContent = `${hh}:${mm}:${ss}`;
420 }
421
422 tick();
423 timerInterval = setInterval(tick, 1000);
424 }
425
426 // ── Preview ──────────────────────────────────────────────────────────────
427 function normaliseVideoDuration (player, durationSeconds)
428 {
429 const shared = sharedVideoPlayer();
430 if (!shared || typeof shared.normaliseVideoDuration !== 'function') return;
431 shared.normaliseVideoDuration(player, durationSeconds);
432 }
433
434 function ensureVideoPlaybackUi (player, durationSeconds)
435 {
436 const shared = sharedVideoPlayer();
437 if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return;
438 shared.ensureVideoPlaybackUi(player, durationSeconds);
439 }
440
441 function tryPreview (name, isDir)
442 {
443 if (isDir) return; // no preview for folders
444
445 const wrap = document.getElementById('preview-wrap');
446 const ext = name.split('.').pop().toLowerCase();
447
448 const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico', 'heif', 'heic'];
449 const videoExts = ['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv'];
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'];
452
453 const previewUrl = `/api/share/preview/${token}`;
454 let el;
455
456 if (imageExts.includes(ext))
457 {
458 el = document.createElement('img');
459 el.src = previewUrl;
460 el.alt = name;
461 } else if (videoExts.includes(ext))
462 {
463 enableVideoStreamClientCache().catch(() => false);
464 fetch(`/api/share/video-stream/${token}`)
465 .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
466 .then(({ ok, data }) =>
467 {
468 if (!ok) throw new Error(data.error || 'Streaming failed');
469 configureVideoJsBuffering();
470 applyShareVideoTextTrackPrefs();
471 const prefs = loadShareVideoPrefs();
472
473 const video = document.createElement('video');
474 video.className = 'video-js vjs-big-play-centered';
475 video.controls = true;
476 video.preload = 'auto';
477 video.playsInline = true;
478
479 wrap.innerHTML = '';
480 wrap.appendChild(video);
481
482 cleanupShareVideoPlayer();
483 shareVideoSessionId = String(data.sessionId || '').trim() || null;
484 shareStreamAheadPrefetch = bindStreamAheadPrefetch(data.playlistUrl);
485
486 shareVideoPlayer = window.videojs(video, {
487 controls: true,
488 fluid: true,
489 responsive: true,
490 preload: 'auto',
491 controlBar: {
492 currentTimeDisplay: true,
493 timeDivider: true,
494 durationDisplay: true,
495 remainingTimeDisplay: false,
496 },
497 sources: [{ src: data.playlistUrl, type: 'application/x-mpegURL' }],
498 tracks: (data.subtitleTracks || []).map(track => ({
499 kind: 'subtitles',
500 src: track.src,
501 srclang: track.language || 'und',
502 label: track.label,
503 default: !!track.default,
504 })),
505 });
506
507 shareTrackPrefs = bindShareVideoTrackPrefs(shareVideoPlayer, prefs);
508 const shared = sharedVideoPlayer();
509 shareImageSubtitleController = shared && typeof shared.bindImageSubtitleOverlay === 'function'
510 ? shared.bindImageSubtitleOverlay(shareVideoPlayer, window.videojs, prefs, data, {
511 savePrefs: saveShareVideoPrefs,
512 currentFetchEnabled: false,
513 lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
514 initialPrefetchSeconds: IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS,
515 prefetchRequestIntervalMs: IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS,
516 prefetchAdaptiveStepEnabled: true,
517 prefetchAdaptivePacingEnabled: true,
518 prefetchStepSecondsMin: IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_NEAR,
519 prefetchStepSecondsMax: IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_FAR,
520 buildPrefetchRequest: ({ currentTime, endTime, streamIndex, session }) => ({
521 url: `/api/share/video-stream-subtitle-range/${encodeURIComponent(token)}?streamIndex=${streamIndex}&startTimeSeconds=${encodeURIComponent(String(currentTime))}&endTimeSeconds=${encodeURIComponent(String(endTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`,
522 credentials: 'same-origin',
523 }),
524 sendSubtitleLogBatch: (entries) =>
525 {
526 if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
527 return fetch(`/api/share/video-stream-subtitle-log/${encodeURIComponent(token)}`, {
528 method: 'POST',
529 credentials: 'same-origin',
530 keepalive: true,
531 headers: {
532 'Content-Type': 'application/json',
533 },
534 body: JSON.stringify({
535 sessionId: data.sessionId || null,
536 entries,
537 }),
538 }).catch(() => null);
539 },
540 buildFrameRequest: ({ currentTime, streamIndex, session }) => ({
541 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 || ''))}`,
542 credentials: 'same-origin',
543 }),
544 })
545 : null;
546 shareStreamAheadSeekMarker = bindStreamAheadSeekMarker(shareVideoPlayer, shareStreamAheadPrefetch);
547 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
548
549 shareVideoPlayer.ready(() =>
550 {
551 const volume = Number(prefs.volume);
552 if (Number.isFinite(volume))
553 {
554 shareVideoPlayer.volume(Math.max(0, Math.min(1, volume)));
555 }
556 shareTrackPrefs.applySavedTracks();
557 if (shareImageSubtitleController && typeof shareImageSubtitleController.applySavedTracks === 'function')
558 {
559 shareImageSubtitleController.applySavedTracks();
560 }
561 });
562
563 shareVideoPlayer.on('loadedmetadata', shareTrackPrefs.applySavedTracks);
564 shareVideoPlayer.on('loadedplaylist', shareTrackPrefs.applySavedTracks);
565 shareVideoPlayer.on('volumechange', () =>
566 {
567 const v = Number(shareVideoPlayer.volume());
568 if (Number.isFinite(v)) saveShareVideoPrefs({ volume: v });
569 });
570
571 wrap.style.display = '';
572 })
573 .catch(() =>
574 {
575 wrap.innerHTML = '<div class="no-preview">No preview available.</div>';
576 wrap.style.display = '';
577 });
578 return;
579 } else if (audioExts.includes(ext))
580 {
581 el = document.createElement('audio');
582 el.src = previewUrl;
583 el.controls = true;
584 } else if (textExts.includes(ext))
585 {
586 fetch(previewUrl)
587 .then(r =>
588 {
589 if (!r.ok) throw new Error('preview failed');
590 return r.text();
591 })
592 .then(text =>
593 {
594 const pre = document.createElement('pre');
595 pre.textContent = text;
596 wrap.innerHTML = '';
597 wrap.appendChild(pre);
598 wrap.style.display = '';
599 })
600 .catch(() => { /* no preview available */ });
601 return;
602 } else
603 {
604 return; // no preview
605 }
606
607 el.addEventListener('error', () => { wrap.innerHTML = '<div class="no-preview">No preview available.</div>'; wrap.style.display = ''; });
608 wrap.innerHTML = '';
609 wrap.appendChild(el);
610 wrap.style.display = '';
611 }
612
613 // ── Boot ─────────────────────────────────────────────────────────────────
614 function showError (title, msg)
615 {
616 document.getElementById('loading').style.display = 'none';
617 document.getElementById('content').style.display = 'none';
618 document.getElementById('error-title').textContent = title;
619 document.getElementById('error-msg').textContent = msg;
620 document.getElementById('error-state').style.display = '';
621 }
622
623 function formatBytes (bytes)
624 {
625 if (bytes == null) return '';
626 if (bytes < 1024) return bytes + ' B';
627 if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
628 if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
629 return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
630 }
631
632 fetch(`/api/share/info/${token}`)
633 .then(r => r.json().then(d => ({ ok: r.ok, status: r.status, data: d })))
634 .then(({ ok, status, data }) =>
635 {
636 document.getElementById('loading').style.display = 'none';
637
638 if (status === 410)
639 {
640 showError('Link expired', 'This share link is no longer valid.');
641 return;
642 }
643 if (!ok)
644 {
645 showError('Not found', data.error || 'This link does not exist.');
646 return;
647 }
648
649 expiresAt = data.expiresAt;
650 startTimer();
651
652 document.getElementById('file-name').textContent = data.name;
653 const metaLine = data.isDir ? 'Folder (download as .zip)' : 'File';
654 document.getElementById('file-meta').textContent = metaLine;
655
656 const dlBtn = document.getElementById('btn-download');
657 dlBtn.href = `/api/share/download/${token}`;
658 if (data.isDir)
659 {
660 document.getElementById('btn-download-label').textContent = 'Download as .zip';
661 dlBtn.download = data.name + '.zip';
662 } else
663 {
664 document.getElementById('btn-download-label').textContent = 'Download';
665 dlBtn.download = data.name;
666 }
667
668 document.getElementById('content').style.display = '';
669
670 tryPreview(data.name, data.isDir);
671 })
672 .catch(() =>
673 {
674 showError('Error', 'Could not reach the server.');
675 });
676
677 window.addEventListener('pagehide', cleanupShareVideoPlayer);
678 window.addEventListener('beforeunload', cleanupShareVideoPlayer);
679 }());
680 </script>
681 <script src="/vendor/video.js/video.min.js"></script>
682</body>
683
684</html>