BlueGit

timfa filemanager

Files

filemanager / public / share.html

share.html

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