Compare commits
20 Commits
a251b274db
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6b17b1f52 | ||
|
|
7207e36510 | ||
|
|
5d739bec12 | ||
|
|
2e6e74b959 | ||
|
|
1d0b435e87 | ||
|
|
138c3224de | ||
|
|
382a637b95 | ||
|
|
455e5cf8d8 | ||
|
|
b931765c06 | ||
|
|
e3eeaacc53 | ||
|
|
48a15759fc | ||
|
|
9fe7511b4d | ||
|
|
17f3161d55 | ||
|
|
5aa95e90d4 | ||
|
|
f5bb33521e | ||
|
|
b9ff61244c | ||
|
|
55828c9726 | ||
|
|
d6865d7c35 | ||
|
|
80476a8a42 | ||
|
|
785b991d01 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@
|
||||
*/__pycache__/*
|
||||
.tmp
|
||||
frontend/dist/*
|
||||
.playwright-mcp/*
|
||||
|
||||
245
backend/main.py
245
backend/main.py
@@ -11,6 +11,8 @@ from yt_dlp.networking.impersonate import ImpersonateTarget
|
||||
from curl_cffi import requests as impersonate_requests
|
||||
import threading
|
||||
import io
|
||||
import time
|
||||
import hashlib
|
||||
from urllib.parse import urljoin
|
||||
|
||||
# Browser to impersonate at the TLS/HTTP layer. Some origins (e.g. the
|
||||
@@ -32,10 +34,19 @@ def get_impersonate_session():
|
||||
return sess
|
||||
|
||||
# Stream params that have dedicated meaning and must never be treated as headers.
|
||||
STREAM_RESERVED_PARAMS = {'url'}
|
||||
# `referer` is mapped to a real Referer header by collect_passthrough_headers, but
|
||||
# `live` is purely a playback hint and must not leak upstream as a header.
|
||||
STREAM_RESERVED_PARAMS = {'url', 'live'}
|
||||
# Headers that affect the transport layer rather than the resource itself; allowing
|
||||
# these to be forwarded could enable request smuggling or vhost-routing abuse.
|
||||
STREAM_DISALLOWED_HEADER_NAMES = {'host', 'content-length', 'transfer-encoding', 'connection', 'expect'}
|
||||
# Headers curl_cffi sets coherently for the impersonated browser. Forwarding the
|
||||
# client's (or extractor's) own values for these would contradict the spoofed TLS
|
||||
# fingerprint and defeat impersonation, so they are never relayed upstream.
|
||||
STREAM_IMPERSONATION_MANAGED_HEADERS = {
|
||||
'user-agent', 'accept', 'accept-encoding', 'accept-language',
|
||||
'sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform',
|
||||
}
|
||||
# RFC 7230 token charset for header field-names.
|
||||
HEADER_NAME_RE = re.compile(r"^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$")
|
||||
# Reject control characters (CR/LF/NUL etc.) that could be used for header injection.
|
||||
@@ -163,6 +174,135 @@ def videos_proxy():
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
|
||||
# Cache of yt-dlp metadata resolutions so the on-demand probe endpoint doesn't
|
||||
# re-extract the same video on every hover/scroll. Signed media URLs expire, so
|
||||
# entries are intentionally short-lived.
|
||||
RESOLVE_CACHE_TTL = 300
|
||||
_resolve_cache = {}
|
||||
_resolve_cache_lock = threading.Lock()
|
||||
|
||||
# Per-format fields the frontend needs to rank formats and build stream/probe
|
||||
# URLs (see resolveStreamSources/rankFormats in videos.js). Everything else in a
|
||||
# yt-dlp format dict is dropped to keep the payload small.
|
||||
_RESOLVE_FORMAT_FIELDS = ('url', 'http_headers', 'height', 'width', 'tbr',
|
||||
'fps', 'vcodec', 'acodec', 'ext', 'video_ext', 'quality')
|
||||
|
||||
# Some channels surface pages that yt-dlp can't extract because the video is
|
||||
# embedded in a third-party JS player iframe (e.g. the xtremestream family used
|
||||
# by tube.perverzija.com). The player page declares its HLS playlist URL as
|
||||
# `m3u8_loader_url + video_id`, so we scrape the page for the embed iframe, then
|
||||
# read those two variables out of the player to reconstruct the stream URL.
|
||||
_EMBED_IFRAME_RE = re.compile(r'''<iframe[^>]+src=["']([^"']+)''', re.I)
|
||||
_EMBED_LOADER_RE = re.compile(r'''m3u8_loader_url\s*=\s*[`'"]([^`'"]+)[`'"]''')
|
||||
_EMBED_VIDEOID_RE = re.compile(r'''video_id\s*=\s*[`'"]([^`'"]+)[`'"]''')
|
||||
|
||||
def resolve_unsupported_embed(page_url):
|
||||
"""Best-effort resolver for iframe-embedded JS players yt-dlp can't handle.
|
||||
Returns an info-like dict ({'url','formats','http_headers','is_live'}) whose
|
||||
single format is the embed's HLS playlist, or None if nothing was found."""
|
||||
try:
|
||||
sess = get_impersonate_session()
|
||||
page = sess.get(page_url, headers={'Referer': page_url}, timeout=15)
|
||||
embed_url = None
|
||||
for src in _EMBED_IFRAME_RE.findall(page.text):
|
||||
candidate = urljoin(page_url, src)
|
||||
if '/player/' in candidate or 'index.php?data=' in candidate:
|
||||
embed_url = candidate
|
||||
break
|
||||
if not embed_url:
|
||||
return None
|
||||
|
||||
player = sess.get(embed_url, headers={'Referer': page_url}, timeout=15)
|
||||
loader = _EMBED_LOADER_RE.search(player.text)
|
||||
video_id = _EMBED_VIDEOID_RE.search(player.text)
|
||||
if not (loader and video_id):
|
||||
return None
|
||||
stream_url = loader.group(1) + video_id.group(1)
|
||||
|
||||
parsed = urllib.parse.urlparse(embed_url)
|
||||
referer = f"{parsed.scheme}://{parsed.netloc}/"
|
||||
headers = {'Referer': referer}
|
||||
return {
|
||||
'url': stream_url,
|
||||
'is_live': False,
|
||||
'http_headers': headers,
|
||||
'formats': [{'url': stream_url, 'ext': 'm3u8', 'protocol': 'm3u8', 'http_headers': headers}],
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@app.route('/api/resolve', methods=['POST', 'GET'])
|
||||
def resolve_video():
|
||||
"""Resolve a page URL to its playable formats via yt-dlp and return them as
|
||||
JSON. The frontend calls this on demand (when a card is hovered or scrolled
|
||||
into view) to learn the real media URLs so it can background-probe them for
|
||||
direct, proxy-free playability."""
|
||||
if request.method == 'POST':
|
||||
source = request.json or {}
|
||||
video_url = source.get('url')
|
||||
else:
|
||||
source = request.args
|
||||
video_url = request.args.get('url')
|
||||
|
||||
if not video_url:
|
||||
return jsonify({"error": "No URL provided"}), 400
|
||||
|
||||
now = time.time()
|
||||
with _resolve_cache_lock:
|
||||
cached = _resolve_cache.get(video_url)
|
||||
if cached and cached[0] > now:
|
||||
return jsonify(cached[1])
|
||||
|
||||
ydl_opts = {
|
||||
'quiet': True,
|
||||
'no_warnings': True,
|
||||
'skip_download': True,
|
||||
# Match /api/stream so the resolved formats reflect what playback will
|
||||
# actually fetch from fingerprinting origins.
|
||||
'impersonate': ImpersonateTarget.from_str(IMPERSONATE_TARGET),
|
||||
}
|
||||
passthrough_headers = collect_passthrough_headers(source)
|
||||
if passthrough_headers:
|
||||
ydl_opts['http_headers'] = passthrough_headers
|
||||
|
||||
try:
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
info = ydl.extract_info(video_url, download=False)
|
||||
except Exception as e:
|
||||
# Many channels point at sites yt-dlp can't extract ("Unsupported URL").
|
||||
# That's not fatal here -- the embed fallback below may still find a
|
||||
# stream, and otherwise we return empty formats so playback falls back to
|
||||
# the proxy.
|
||||
app.logger.info("[resolve] yt-dlp could not extract %s: %s", video_url, e)
|
||||
info = None
|
||||
|
||||
# Fall back to scraping iframe-embedded JS players yt-dlp doesn't support.
|
||||
if not (info and (info.get('formats') or info.get('url'))):
|
||||
embed = resolve_unsupported_embed(video_url)
|
||||
if embed:
|
||||
info = embed
|
||||
|
||||
formats = []
|
||||
for fmt in ((info.get('formats') if info else None) or []):
|
||||
if not fmt.get('url'):
|
||||
continue
|
||||
formats.append({k: fmt.get(k) for k in _RESOLVE_FORMAT_FIELDS if fmt.get(k) is not None})
|
||||
|
||||
result = {
|
||||
'url': info.get('url') if info else None,
|
||||
'http_headers': (info.get('http_headers') if info else None) or {},
|
||||
'isLive': bool(info.get('is_live')) if info else False,
|
||||
'formats': formats,
|
||||
}
|
||||
|
||||
with _resolve_cache_lock:
|
||||
# Drop expired entries so the cache doesn't grow without bound.
|
||||
for key in [k for k, v in _resolve_cache.items() if v[0] <= now]:
|
||||
_resolve_cache.pop(key, None)
|
||||
_resolve_cache[video_url] = (now + RESOLVE_CACHE_TTL, result)
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@app.route('/api/image', methods=['GET', 'HEAD'])
|
||||
def image_proxy():
|
||||
image_url = request.args.get('url')
|
||||
@@ -216,6 +356,63 @@ def index():
|
||||
def favicon():
|
||||
return send_from_directory(app.static_folder, 'favicon.ico')
|
||||
|
||||
# --- Frontend asset version tracking -------------------------------------
|
||||
# The client polls /api/version and, when a tracked file's content hash
|
||||
# changes, hot-swaps CSS in place or reloads the page. This lets a deploy
|
||||
# reach already-open tabs without a manual refresh.
|
||||
_FRONTEND_DIR = os.path.abspath(app.static_folder)
|
||||
_VERSION_EXTS = ('.html', '.css', '.js')
|
||||
_version_cache = {'mtime': None, 'payload': None}
|
||||
_version_lock = threading.Lock()
|
||||
|
||||
|
||||
def _scan_frontend_files():
|
||||
"""Map served relative paths -> absolute paths for tracked frontend files."""
|
||||
files = {}
|
||||
for root, _dirs, names in os.walk(_FRONTEND_DIR):
|
||||
for name in names:
|
||||
if os.path.splitext(name)[1].lower() not in _VERSION_EXTS:
|
||||
continue
|
||||
path = os.path.join(root, name)
|
||||
rel = os.path.relpath(path, _FRONTEND_DIR).replace(os.sep, '/')
|
||||
files[rel] = path
|
||||
return files
|
||||
|
||||
|
||||
def _compute_version_payload(files):
|
||||
"""Hash each tracked file's contents plus a combined version fingerprint."""
|
||||
file_hashes = {}
|
||||
combined = hashlib.md5()
|
||||
for rel in sorted(files):
|
||||
try:
|
||||
with open(files[rel], 'rb') as fh:
|
||||
digest = hashlib.md5(fh.read()).hexdigest()
|
||||
except OSError:
|
||||
continue
|
||||
file_hashes[rel] = digest
|
||||
combined.update(rel.encode('utf-8'))
|
||||
combined.update(digest.encode('utf-8'))
|
||||
return {'version': combined.hexdigest(), 'files': file_hashes}
|
||||
|
||||
|
||||
@app.route('/api/version', methods=['GET'])
|
||||
def frontend_version():
|
||||
files = _scan_frontend_files()
|
||||
# Use the newest mtime across tracked files as a cheap cache key so frequent
|
||||
# polls only re-hash contents when something on disk actually changed.
|
||||
try:
|
||||
latest_mtime = max((os.path.getmtime(p) for p in files.values()), default=0)
|
||||
except OSError:
|
||||
latest_mtime = 0
|
||||
with _version_lock:
|
||||
if _version_cache['mtime'] != latest_mtime or _version_cache['payload'] is None:
|
||||
_version_cache['payload'] = _compute_version_payload(files)
|
||||
_version_cache['mtime'] = latest_mtime
|
||||
payload = _version_cache['payload']
|
||||
resp = jsonify(payload)
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
return resp
|
||||
|
||||
@app.route('/api/stream', methods=['POST', 'GET', 'HEAD'])
|
||||
def stream_video():
|
||||
# Note: <video> tags perform GET. To support your POST requirement,
|
||||
@@ -300,6 +497,17 @@ def stream_video():
|
||||
headers['Cookie'] = request.headers['Cookie']
|
||||
dbg("forwarding cookies")
|
||||
|
||||
# Relay the per-format headers (e.g. Cookie) the frontend forwarded as
|
||||
# query params so cookie/token-authorized origins serve the media.
|
||||
# Referer is already set above, and impersonation-managed headers are left
|
||||
# to curl_cffi to keep the request coherent with the spoofed fingerprint.
|
||||
for key, value in collect_passthrough_headers(request.args).items():
|
||||
lower = key.lower()
|
||||
if lower == 'referer' or lower in STREAM_IMPERSONATION_MANAGED_HEADERS:
|
||||
continue
|
||||
if value:
|
||||
headers[key] = value
|
||||
|
||||
# Remove keys with None values
|
||||
return {k: v for k, v in headers.items() if v}
|
||||
|
||||
@@ -426,10 +634,27 @@ def stream_video():
|
||||
except LookupError:
|
||||
return body_bytes.decode("utf-8", errors="replace")
|
||||
|
||||
def passthrough_param_suffix():
|
||||
# The relayed headers (e.g. Cookie) the upstream needs for authorization,
|
||||
# encoded as &Name=value so they ride along on every proxied child URL
|
||||
# (variant playlists, segments). Referer is appended separately by each
|
||||
# rewriter; impersonation-managed headers stay with curl_cffi.
|
||||
parts = []
|
||||
for key, value in collect_passthrough_headers(request.args).items():
|
||||
lower = key.lower()
|
||||
if lower == 'referer' or lower in STREAM_IMPERSONATION_MANAGED_HEADERS:
|
||||
continue
|
||||
if not value:
|
||||
continue
|
||||
parts.append(f"&{urllib.parse.quote(key)}={urllib.parse.quote(str(value))}")
|
||||
return ''.join(parts)
|
||||
|
||||
def rewrite_hls_playlist(body_text, base_url, referer):
|
||||
extra = passthrough_param_suffix()
|
||||
|
||||
def proxied_url(target):
|
||||
absolute = urljoin(base_url, target)
|
||||
return f"/api/stream?url={urllib.parse.quote(absolute, safe='')}&referer={urllib.parse.quote(referer, safe='')}"
|
||||
return f"/api/stream?url={urllib.parse.quote(absolute, safe='')}&referer={urllib.parse.quote(referer, safe='')}{extra}"
|
||||
|
||||
lines = body_text.splitlines()
|
||||
rewritten = []
|
||||
@@ -590,9 +815,11 @@ def stream_video():
|
||||
if not video_fmts:
|
||||
return None
|
||||
|
||||
extra = passthrough_param_suffix()
|
||||
|
||||
def proxied(url):
|
||||
return (f"/api/stream?url={urllib.parse.quote(url, safe='')}"
|
||||
f"&referer={urllib.parse.quote(referer, safe='')}")
|
||||
f"&referer={urllib.parse.quote(referer, safe='')}{extra}")
|
||||
|
||||
lines = ['#EXTM3U', '#EXT-X-VERSION:3']
|
||||
|
||||
@@ -664,7 +891,19 @@ def stream_video():
|
||||
|
||||
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
||||
# Extract the info
|
||||
try:
|
||||
info = ydl.extract_info(video_url, download=False)
|
||||
except Exception as ydl_err:
|
||||
# yt-dlp can't extract iframe-embedded JS players; scrape the
|
||||
# embed for its HLS playlist and proxy that directly instead.
|
||||
embed = resolve_unsupported_embed(video_url)
|
||||
if not embed:
|
||||
raise
|
||||
dbg(f"embed fallback resolved {video_url} -> {embed['url']}")
|
||||
if request.method == 'HEAD':
|
||||
return Response("", status=200, content_type='application/vnd.apple.mpegurl')
|
||||
return proxy_hls_playlist(embed['url'], embed['http_headers'].get('Referer'),
|
||||
upstream_headers=embed['http_headers'])
|
||||
dbg(f"yt_dlp extractor={info.get('extractor')} protocol={info.get('protocol')}")
|
||||
|
||||
# Try to get the URL from the info dict (works for progressive downloads)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,10 +7,11 @@
|
||||
<link rel="icon" href="/favicon.ico" type="image/x-icon">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Lobster&family=Space+Grotesk:wght@500;600&family=Sora:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;1,9..144,400&family=Sora:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="static/css/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="scroll-progress" class="scroll-progress" aria-hidden="true"></div>
|
||||
<header class="top-bar">
|
||||
<div class="logo">Jacuzzi</div>
|
||||
<div class="search-container">
|
||||
@@ -90,6 +91,28 @@
|
||||
<option value="360">360p</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="density-select">Grid Density</label>
|
||||
<select id="density-select">
|
||||
<option value="comfortable">Comfortable</option>
|
||||
<option value="compact">Compact</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="card-size-range">Card Size</label>
|
||||
<input type="range" id="card-size-range" min="0.7" max="1.5" step="0.1" value="1">
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="text-size-range">Text Size</label>
|
||||
<input type="range" id="text-size-range" min="0.8" max="1.4" step="0.1" value="1">
|
||||
</div>
|
||||
<div class="setting-item">
|
||||
<label for="feed-end-select">Reels: On Video End</label>
|
||||
<select id="feed-end-select">
|
||||
<option value="loop">Loop</option>
|
||||
<option value="scroll">Scroll to Next</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="setting-item setting-toggle">
|
||||
<div class="setting-label-row">
|
||||
<label for="favorites-toggle">Favorites Bar</label>
|
||||
@@ -119,12 +142,7 @@
|
||||
<img class="icon-svg" src="https://cdn.jsdelivr.net/npm/heroicons@2.0.13/24/outline/chevron-down.svg" alt="Load More">
|
||||
</button>
|
||||
|
||||
<div id="video-modal" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close" onclick="closePlayer()">×</span>
|
||||
<video id="player" controls autoplay playsinline webkit-playsinline></video>
|
||||
</div>
|
||||
</div>
|
||||
<div id="custom-player" class="custom-player" aria-hidden="true"></div>
|
||||
|
||||
<button id="mode-toggle-btn" class="mode-toggle-btn" type="button" title="Switch to Reels view" aria-pressed="false">
|
||||
<img class="icon-svg" id="mode-toggle-icon" src="https://cdn.jsdelivr.net/npm/heroicons@2.0.13/24/outline/device-phone-mobile.svg" alt="Switch to Reels view">
|
||||
@@ -154,13 +172,30 @@
|
||||
<button id="error-toast-close" type="button" aria-label="Close">✕</button>
|
||||
</div>
|
||||
|
||||
<div id="update-banner" class="update-banner" role="status" aria-live="polite">
|
||||
<span>A new version is available.</span>
|
||||
<button id="update-banner-btn" type="button">Refresh</button>
|
||||
</div>
|
||||
|
||||
<button id="back-to-top" class="back-to-top" type="button" title="Back to top" aria-label="Back to top">↑</button>
|
||||
|
||||
<div id="command-palette" class="command-palette" aria-hidden="true">
|
||||
<div class="cmdk-box" role="dialog" aria-modal="true" aria-label="Command palette">
|
||||
<input id="cmdk-input" class="cmdk-input" type="text" placeholder="Type a command or search… (⌘K)" autocomplete="off" spellcheck="false">
|
||||
<div id="cmdk-list" class="cmdk-list" role="listbox"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="static/js/state.js"></script>
|
||||
<script src="static/js/storage.js"></script>
|
||||
<script src="static/js/customPlayer.js"></script>
|
||||
<script src="static/js/player.js"></script>
|
||||
<script src="static/js/favorites.js"></script>
|
||||
<script src="static/js/videos.js"></script>
|
||||
<script src="static/js/feed.js"></script>
|
||||
<script src="static/js/ui.js"></script>
|
||||
<script src="static/js/version.js"></script>
|
||||
<script src="static/js/enhance.js"></script>
|
||||
<script src="static/js/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
302
frontend/js/customPlayer.js
Normal file
302
frontend/js/customPlayer.js
Normal file
@@ -0,0 +1,302 @@
|
||||
window.App = window.App || {};
|
||||
App.customPlayer = App.customPlayer || {};
|
||||
|
||||
// Shared building blocks for the custom video player HUD, reused by the
|
||||
// standalone fullscreen player (player.js) and the reels feed (feed.js) so
|
||||
// both present identical skip/format/gesture/PiP behavior.
|
||||
(function() {
|
||||
// -----------------------------------------------------------------
|
||||
// Skip escalation: tapping skip-forward/back repeatedly ramps the skip
|
||||
// duration up (5 -> 10 -> 20 -> 40 -> 60s), independently per direction,
|
||||
// so mashing forward doesn't also ramp up backward. A tap lands as
|
||||
// "rapid" (and escalates further) only if it arrives within
|
||||
// RAPID_WINDOW_MS of the previous same-direction tap. After GRACE_MS of
|
||||
// silence the level steps back down by one every DECAY_STEP_MS.
|
||||
// -----------------------------------------------------------------
|
||||
const LEVELS = [5, 10, 20, 40, 60];
|
||||
const RAPID_WINDOW_MS = 1500;
|
||||
const GRACE_MS = 2000;
|
||||
const DECAY_STEP_MS = 1000;
|
||||
|
||||
App.customPlayer.createSkipEscalator = function() {
|
||||
const dirs = {
|
||||
back: { levelIndex: 0, lastTapAt: 0, decayTimer: null },
|
||||
forward: { levelIndex: 0, lastTapAt: 0, decayTimer: null }
|
||||
};
|
||||
|
||||
const clearDecay = (d) => {
|
||||
if (d.decayTimer) {
|
||||
clearTimeout(d.decayTimer);
|
||||
d.decayTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleDecay = (d) => {
|
||||
clearDecay(d);
|
||||
d.decayTimer = setTimeout(function tick() {
|
||||
d.decayTimer = null;
|
||||
if (d.levelIndex > 0) {
|
||||
d.levelIndex -= 1;
|
||||
d.decayTimer = setTimeout(tick, DECAY_STEP_MS);
|
||||
}
|
||||
}, GRACE_MS);
|
||||
};
|
||||
|
||||
// Advances the state for a tap in `direction` and returns the number
|
||||
// of seconds that tap should skip.
|
||||
const trigger = function(direction) {
|
||||
const d = dirs[direction];
|
||||
if (!d) return LEVELS[0];
|
||||
const now = Date.now();
|
||||
if (now - d.lastTapAt <= RAPID_WINDOW_MS && d.levelIndex < LEVELS.length - 1) {
|
||||
d.levelIndex += 1;
|
||||
}
|
||||
d.lastTapAt = now;
|
||||
scheduleDecay(d);
|
||||
return LEVELS[d.levelIndex];
|
||||
};
|
||||
|
||||
const destroy = function() {
|
||||
clearDecay(dirs.back);
|
||||
clearDecay(dirs.forward);
|
||||
};
|
||||
|
||||
return { trigger, destroy };
|
||||
};
|
||||
|
||||
// Applies one skip tap to `video` using `escalator`, clamped to the
|
||||
// media's bounds. Returns the number of seconds skipped (for HUD flash
|
||||
// feedback), or 0 if the video has no usable duration yet.
|
||||
App.customPlayer.skip = function(video, direction, escalator) {
|
||||
if (!video) return 0;
|
||||
const amount = escalator.trigger(direction);
|
||||
const delta = direction === 'forward' ? amount : -amount;
|
||||
let target = video.currentTime + delta;
|
||||
if (isFinite(video.duration) && video.duration > 0) {
|
||||
target = Math.min(target, Math.max(0, video.duration - 0.1));
|
||||
}
|
||||
video.currentTime = Math.max(0, target);
|
||||
return amount;
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Format switching: builds a labeled, ranked list of a video's playable
|
||||
// formats (quality/codec/container variants) for a picker menu. Reuses
|
||||
// App.videos.rankFormats (same ranking as automatic selection) with no
|
||||
// preferred-height ceiling, since a manual pick overrides that entirely.
|
||||
// -----------------------------------------------------------------
|
||||
App.customPlayer.formatLabel = function(fmt) {
|
||||
if (!fmt) return 'Auto';
|
||||
const parts = [];
|
||||
const height = App.videos.coerceNumber(fmt.height);
|
||||
const fps = App.videos.coerceNumber(fmt.fps);
|
||||
if (height) parts.push(`${height}p${fps > 30 ? Math.round(fps) : ''}`);
|
||||
const ext = (fmt.ext || fmt.video_ext || '').toString();
|
||||
if (ext) parts.push(ext);
|
||||
if (!parts.length) {
|
||||
const vcodec = (fmt.vcodec || '').toString();
|
||||
parts.push(vcodec && vcodec !== 'none' ? vcodec : 'Auto');
|
||||
}
|
||||
return parts.join(' ');
|
||||
};
|
||||
|
||||
// Returns [] when there's nothing to pick from (no formats, or only one
|
||||
// usable variant) so callers know to hide the format-switch button.
|
||||
App.customPlayer.buildFormatOptions = function(video) {
|
||||
const meta = video && (video.meta || video);
|
||||
if (!meta || !Array.isArray(meta.formats) || meta.formats.length < 2) return [];
|
||||
const ranked = App.videos.rankFormats(meta.formats, null);
|
||||
if (ranked.length < 2) return [];
|
||||
return ranked.map((fmt) => ({ fmt, label: App.customPlayer.formatLabel(fmt) }));
|
||||
};
|
||||
|
||||
// Wires a format-switch button + its dropdown menu against `videoData`,
|
||||
// calling onSelect(fmt) when the user picks one. Hides the button when
|
||||
// there's nothing to pick from. Shared by the standalone player and the
|
||||
// reels feed so both present an identical menu. Returns a destroy() fn.
|
||||
App.customPlayer.bindFormatMenu = function(btn, menu, videoData, onSelect) {
|
||||
if (!btn || !menu) return function destroy() {};
|
||||
const options = App.customPlayer.buildFormatOptions(videoData);
|
||||
if (!options.length) {
|
||||
btn.hidden = true;
|
||||
menu.hidden = true;
|
||||
menu.innerHTML = '';
|
||||
return function destroy() {};
|
||||
}
|
||||
btn.hidden = false;
|
||||
menu.hidden = true;
|
||||
menu.innerHTML = options.map((opt, i) =>
|
||||
`<button class="cp-format-option" type="button" data-index="${i}">${opt.label}</button>`
|
||||
).join('');
|
||||
const cleanups = [];
|
||||
menu.querySelectorAll('.cp-format-option').forEach((optBtn) => {
|
||||
const onClick = (event) => {
|
||||
event.stopPropagation();
|
||||
const idx = parseInt(optBtn.dataset.index, 10);
|
||||
const opt = options[idx];
|
||||
menu.hidden = true;
|
||||
menu.querySelectorAll('.cp-format-option').forEach((b) => b.classList.remove('is-active'));
|
||||
optBtn.classList.add('is-active');
|
||||
if (opt) onSelect(opt.fmt);
|
||||
};
|
||||
optBtn.addEventListener('click', onClick);
|
||||
cleanups.push(() => optBtn.removeEventListener('click', onClick));
|
||||
});
|
||||
const onBtnClick = (event) => {
|
||||
event.stopPropagation();
|
||||
menu.hidden = !menu.hidden;
|
||||
};
|
||||
btn.addEventListener('click', onBtnClick);
|
||||
cleanups.push(() => btn.removeEventListener('click', onBtnClick));
|
||||
return function destroy() {
|
||||
cleanups.forEach((fn) => fn());
|
||||
};
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Picture-in-Picture: a manual toggle plus best-effort auto-PiP when the
|
||||
// tab/app is backgrounded while a video is playing (Safari does this
|
||||
// natively for inline video; Chrome/Android need an explicit call).
|
||||
// -----------------------------------------------------------------
|
||||
App.customPlayer.supportsPiP = function() {
|
||||
return !!(document.pictureInPictureEnabled);
|
||||
};
|
||||
|
||||
App.customPlayer.togglePiP = async function(video) {
|
||||
if (!video || !document.pictureInPictureEnabled || video.disablePictureInPicture) return false;
|
||||
try {
|
||||
if (document.pictureInPictureElement === video) {
|
||||
await document.exitPictureInPicture();
|
||||
} else {
|
||||
await video.requestPictureInPicture();
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
App.customPlayer.bindAutoPiP = function(video) {
|
||||
if (!video) return function destroy() {};
|
||||
const trigger = () => {
|
||||
if (document.visibilityState !== 'hidden') return;
|
||||
if (!document.pictureInPictureEnabled || video.disablePictureInPicture) return;
|
||||
if (document.pictureInPictureElement) return;
|
||||
if (video.paused || video.ended) return;
|
||||
video.requestPictureInPicture().catch(() => {});
|
||||
};
|
||||
document.addEventListener('visibilitychange', trigger);
|
||||
window.addEventListener('pagehide', trigger);
|
||||
return function destroy() {
|
||||
document.removeEventListener('visibilitychange', trigger);
|
||||
window.removeEventListener('pagehide', trigger);
|
||||
};
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Unified pointer-gesture recognizer for the video surface: a single
|
||||
// pointer stream is classified into exactly one of tap / double-tap /
|
||||
// volume-drag (right column) / dismiss-drag (top strip), so the gestures
|
||||
// never fight each other over the same touch.
|
||||
// -----------------------------------------------------------------
|
||||
App.customPlayer.attachGestures = function(surfaceEl, handlers) {
|
||||
handlers = handlers || {};
|
||||
const TAP_MAX_MOVE = 10;
|
||||
const DOUBLE_TAP_MS = 300;
|
||||
const DISMISS_ZONE_FRACTION = 0.2; // top strip that owns swipe-to-dismiss
|
||||
const VOLUME_ZONE_START = 0.66; // right column that owns volume swipe
|
||||
const SKIP_ZONE_LEFT_END = 0.34;
|
||||
const SKIP_ZONE_RIGHT_START = 0.66;
|
||||
|
||||
let pointerId = null;
|
||||
let startX = 0, startY = 0, lastY = 0;
|
||||
let moved = false;
|
||||
let mode = null; // 'dismiss-candidate' | 'dismiss' | 'volume-candidate' | 'volume' | 'ignore'
|
||||
let volumeStartValue = 0;
|
||||
let lastTapTime = 0;
|
||||
let lastTapSide = null;
|
||||
|
||||
const rectOf = () => surfaceEl.getBoundingClientRect();
|
||||
|
||||
const ignoreSelector = handlers.ignoreSelector || 'button, input, a, .cp-format-menu';
|
||||
|
||||
const onPointerDown = (e) => {
|
||||
if (pointerId != null || e.button != null && e.button !== 0) return;
|
||||
if (e.target && e.target.closest && e.target.closest(ignoreSelector)) return;
|
||||
pointerId = e.pointerId;
|
||||
startX = e.clientX;
|
||||
startY = lastY = e.clientY;
|
||||
moved = false;
|
||||
mode = null;
|
||||
const rect = rectOf();
|
||||
const relX = rect.width ? (e.clientX - rect.left) / rect.width : 0;
|
||||
const relY = rect.height ? (e.clientY - rect.top) / rect.height : 0;
|
||||
if (relY <= DISMISS_ZONE_FRACTION && handlers.onDismissDrag) {
|
||||
mode = 'dismiss-candidate';
|
||||
} else if (relX >= VOLUME_ZONE_START && handlers.onVolumeDrag) {
|
||||
mode = 'volume-candidate';
|
||||
volumeStartValue = handlers.onVolumeStart ? handlers.onVolumeStart() : 0;
|
||||
}
|
||||
try { surfaceEl.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||||
};
|
||||
|
||||
const onPointerMove = (e) => {
|
||||
if (e.pointerId !== pointerId) return;
|
||||
const dx = e.clientX - startX;
|
||||
const dy = e.clientY - startY;
|
||||
if (!moved && Math.hypot(dx, dy) > TAP_MAX_MOVE) moved = true;
|
||||
if (moved) {
|
||||
if (mode === 'dismiss-candidate') mode = 'dismiss';
|
||||
else if (mode === 'volume-candidate') mode = 'volume';
|
||||
else if (mode === null) mode = 'ignore';
|
||||
|
||||
if (mode === 'dismiss') {
|
||||
handlers.onDismissDrag(dy, rectOf());
|
||||
} else if (mode === 'volume') {
|
||||
const rect = rectOf();
|
||||
const deltaRatio = rect.height ? (startY - e.clientY) / rect.height : 0;
|
||||
handlers.onVolumeDrag(Math.min(1, Math.max(0, volumeStartValue + deltaRatio)));
|
||||
}
|
||||
}
|
||||
lastY = e.clientY;
|
||||
};
|
||||
|
||||
const endGesture = (e) => {
|
||||
if (e.pointerId !== pointerId) return;
|
||||
try { surfaceEl.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||||
if (moved) {
|
||||
if (mode === 'dismiss' && handlers.onDismissEnd) handlers.onDismissEnd(lastY - startY);
|
||||
else if (mode === 'volume' && handlers.onVolumeEnd) handlers.onVolumeEnd();
|
||||
} else {
|
||||
if (handlers.onSingleTap) handlers.onSingleTap();
|
||||
const rect = rectOf();
|
||||
const relX = rect.width ? (startX - rect.left) / rect.width : 0.5;
|
||||
const side = relX <= SKIP_ZONE_LEFT_END ? 'left' : (relX >= SKIP_ZONE_RIGHT_START ? 'right' : 'center');
|
||||
const now = Date.now();
|
||||
if (side !== 'center' && lastTapSide === side && (now - lastTapTime) <= DOUBLE_TAP_MS) {
|
||||
lastTapTime = 0;
|
||||
lastTapSide = null;
|
||||
if (side === 'left' && handlers.onDoubleTapLeft) handlers.onDoubleTapLeft();
|
||||
if (side === 'right' && handlers.onDoubleTapRight) handlers.onDoubleTapRight();
|
||||
} else {
|
||||
lastTapTime = now;
|
||||
lastTapSide = side;
|
||||
}
|
||||
}
|
||||
pointerId = null;
|
||||
mode = null;
|
||||
};
|
||||
|
||||
surfaceEl.addEventListener('pointerdown', onPointerDown);
|
||||
surfaceEl.addEventListener('pointermove', onPointerMove);
|
||||
surfaceEl.addEventListener('pointerup', endGesture);
|
||||
surfaceEl.addEventListener('pointercancel', endGesture);
|
||||
|
||||
return function destroy() {
|
||||
surfaceEl.removeEventListener('pointerdown', onPointerDown);
|
||||
surfaceEl.removeEventListener('pointermove', onPointerMove);
|
||||
surfaceEl.removeEventListener('pointerup', endGesture);
|
||||
surfaceEl.removeEventListener('pointercancel', endGesture);
|
||||
};
|
||||
};
|
||||
})();
|
||||
252
frontend/js/enhance.js
Normal file
252
frontend/js/enhance.js
Normal file
@@ -0,0 +1,252 @@
|
||||
window.App = window.App || {};
|
||||
App.enhance = App.enhance || {};
|
||||
|
||||
// Progressive UI enhancements layered on top of the core app. Everything here
|
||||
// is non-essential polish: cursor-tracking card spotlight, a scroll-progress
|
||||
// bar, a back-to-top button, a ⌘K command palette, and hover video previews.
|
||||
// None of it is required for the app to function, so each piece fails soft.
|
||||
(function() {
|
||||
const fineHover = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
const reduceMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
// ---- Cursor-tracking spotlight border on grid cards ----------------------
|
||||
// One delegated listener keeps per-card vars (--mx/--my) updated; the brass
|
||||
// border gradient that reads them lives in CSS (.video-card::after).
|
||||
function initSpotlight() {
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (!grid || !fineHover) return;
|
||||
grid.addEventListener('pointermove', (e) => {
|
||||
const card = e.target.closest('.video-card');
|
||||
if (!card) return;
|
||||
const r = card.getBoundingClientRect();
|
||||
card.style.setProperty('--mx', (e.clientX - r.left) + 'px');
|
||||
card.style.setProperty('--my', (e.clientY - r.top) + 'px');
|
||||
}, { passive: true });
|
||||
}
|
||||
|
||||
// ---- Scroll progress bar + back-to-top FAB -------------------------------
|
||||
function initScrollAffordances() {
|
||||
const bar = document.getElementById('scroll-progress');
|
||||
const fab = document.getElementById('back-to-top');
|
||||
let ticking = false;
|
||||
const onScroll = () => {
|
||||
if (ticking) return;
|
||||
ticking = true;
|
||||
requestAnimationFrame(() => {
|
||||
ticking = false;
|
||||
const doc = document.documentElement;
|
||||
const max = doc.scrollHeight - window.innerHeight;
|
||||
const pct = max > 0 ? (window.scrollY / max) * 100 : 0;
|
||||
if (bar) bar.style.width = pct.toFixed(2) + '%';
|
||||
if (fab) fab.classList.toggle('is-visible', window.scrollY > 700);
|
||||
});
|
||||
};
|
||||
window.addEventListener('scroll', onScroll, { passive: true });
|
||||
onScroll();
|
||||
if (fab) {
|
||||
fab.addEventListener('click', () => {
|
||||
window.scrollTo({ top: 0, behavior: reduceMotion() ? 'auto' : 'smooth' });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Hover video preview --------------------------------------------------
|
||||
// After a short dwell over a card, play a muted inline clip in place of the
|
||||
// poster — but only if the video's real formats are already resolved (the
|
||||
// grid resolves them lazily on hover/scroll anyway), so we never block or
|
||||
// hammer the backend just to preview.
|
||||
function initHoverPreview() {
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (!grid || !fineHover) return;
|
||||
let dwellTimer = null;
|
||||
let activeCard = null;
|
||||
|
||||
const clearPreview = () => {
|
||||
if (dwellTimer) { clearTimeout(dwellTimer); dwellTimer = null; }
|
||||
if (activeCard) {
|
||||
const vid = activeCard.querySelector('.card-preview');
|
||||
if (vid) { try { vid.pause(); } catch (e) {} vid.remove(); }
|
||||
activeCard.classList.remove('is-previewing');
|
||||
activeCard = null;
|
||||
}
|
||||
};
|
||||
|
||||
const startPreview = (card) => {
|
||||
if (!App.videos || typeof App.videos.getVideoForCard !== 'function') return;
|
||||
const v = App.videos.getVideoForCard(card);
|
||||
if (!v) return;
|
||||
const meta = v.meta;
|
||||
const ready = meta && Array.isArray(meta.formats) && meta.formats.length;
|
||||
if (!ready) {
|
||||
// Not resolved yet: kick it off so the *next* hover can preview.
|
||||
if (typeof App.videos.resolveAndProbe === 'function') App.videos.resolveAndProbe(v);
|
||||
return;
|
||||
}
|
||||
let url = '';
|
||||
try { url = App.videos.buildStreamUrl(v); } catch (e) { return; }
|
||||
if (!url) return;
|
||||
const img = card.querySelector('img');
|
||||
const vid = document.createElement('video');
|
||||
vid.className = 'card-preview';
|
||||
vid.muted = true;
|
||||
vid.loop = true;
|
||||
vid.playsInline = true;
|
||||
vid.setAttribute('playsinline', '');
|
||||
vid.setAttribute('webkit-playsinline', '');
|
||||
vid.preload = 'auto';
|
||||
if (img) vid.style.height = img.getBoundingClientRect().height + 'px';
|
||||
vid.src = url;
|
||||
vid.addEventListener('error', () => { if (vid.isConnected) vid.remove(); }, { once: true });
|
||||
card.appendChild(vid);
|
||||
card.classList.add('is-previewing');
|
||||
const p = vid.play();
|
||||
if (p && p.catch) p.catch(() => {});
|
||||
};
|
||||
|
||||
grid.addEventListener('pointerover', (e) => {
|
||||
const card = e.target.closest('.video-card');
|
||||
if (!card || card === activeCard) return;
|
||||
clearPreview();
|
||||
activeCard = card;
|
||||
dwellTimer = setTimeout(() => { dwellTimer = null; if (activeCard === card) startPreview(card); }, 600);
|
||||
});
|
||||
grid.addEventListener('pointerout', (e) => {
|
||||
const card = e.target.closest('.video-card');
|
||||
if (!card) return;
|
||||
const to = e.relatedTarget;
|
||||
if (to && card.contains(to)) return; // still inside the same card
|
||||
if (card === activeCard) clearPreview();
|
||||
});
|
||||
window.addEventListener('scroll', clearPreview, { passive: true });
|
||||
}
|
||||
|
||||
// ---- Command palette (⌘K / Ctrl+K) ---------------------------------------
|
||||
function initCommandPalette() {
|
||||
const palette = document.getElementById('command-palette');
|
||||
const input = document.getElementById('cmdk-input');
|
||||
const list = document.getElementById('cmdk-list');
|
||||
if (!palette || !input || !list) return;
|
||||
|
||||
let actions = [];
|
||||
let filtered = [];
|
||||
let activeIndex = 0;
|
||||
|
||||
const fireChange = (el) => el && el.dispatchEvent(new Event('change'));
|
||||
|
||||
const buildActions = () => {
|
||||
const out = [];
|
||||
out.push({ label: 'Search videos', hint: 'Focus the search box', run: () => {
|
||||
const s = document.getElementById('search-input'); if (s) { s.focus(); s.select(); }
|
||||
}});
|
||||
const theme = (localStorage.getItem('theme') || 'dark');
|
||||
out.push({ label: `Switch to ${theme === 'light' ? 'dark' : 'light'} theme`, hint: 'Appearance', run: () => {
|
||||
localStorage.setItem('theme', theme === 'light' ? 'dark' : 'light');
|
||||
if (App.ui && App.ui.applyTheme) App.ui.applyTheme();
|
||||
}});
|
||||
const density = (App.storage && App.storage.getDensity) ? App.storage.getDensity() : 'comfortable';
|
||||
out.push({ label: `Grid density: ${density === 'compact' ? 'comfortable' : 'compact'}`, hint: 'Layout', run: () => {
|
||||
if (!App.storage) return;
|
||||
App.storage.setDensity(density === 'compact' ? 'comfortable' : 'compact');
|
||||
if (App.ui && App.ui.applyDensity) App.ui.applyDensity();
|
||||
if (App.virtualGrid && App.virtualGrid.relayout) App.virtualGrid.relayout();
|
||||
}});
|
||||
out.push({ label: 'Toggle Reels view', hint: 'Playback', run: () => { if (App.feed) App.feed.toggle(); } });
|
||||
out.push({ label: 'Reload channel', hint: 'Refresh the current feed', run: () => { if (App.videos) App.videos.resetAndReload(); } });
|
||||
out.push({ label: 'Open Menu', hint: 'Source · channel · filters', run: () => { if (App.ui) App.ui.toggleDrawer('menu'); } });
|
||||
out.push({ label: 'Open Settings', hint: 'Preferences', run: () => { if (App.ui) App.ui.toggleDrawer('settings'); } });
|
||||
|
||||
const sourceSelect = document.getElementById('source-select');
|
||||
if (sourceSelect) {
|
||||
Array.from(sourceSelect.options).forEach((opt) => {
|
||||
if (opt.value === sourceSelect.value) return;
|
||||
out.push({ label: opt.textContent, hint: 'Source', run: () => { sourceSelect.value = opt.value; fireChange(sourceSelect); } });
|
||||
});
|
||||
}
|
||||
const channelSelect = document.getElementById('channel-select');
|
||||
if (channelSelect) {
|
||||
Array.from(channelSelect.options).forEach((opt) => {
|
||||
if (opt.value === channelSelect.value) return;
|
||||
out.push({ label: opt.textContent, hint: 'Channel', run: () => { channelSelect.value = opt.value; fireChange(channelSelect); } });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const render = () => {
|
||||
list.innerHTML = '';
|
||||
filtered.forEach((a, i) => {
|
||||
const li = document.createElement('button');
|
||||
li.type = 'button';
|
||||
li.className = 'cmdk-item' + (i === activeIndex ? ' is-active' : '');
|
||||
li.innerHTML = `<span class="cmdk-label"></span><span class="cmdk-hint"></span>`;
|
||||
li.querySelector('.cmdk-label').textContent = a.label;
|
||||
li.querySelector('.cmdk-hint').textContent = a.hint || '';
|
||||
li.addEventListener('click', () => choose(i));
|
||||
li.addEventListener('pointermove', () => { if (activeIndex !== i) { activeIndex = i; render(); } });
|
||||
list.appendChild(li);
|
||||
});
|
||||
};
|
||||
|
||||
const applyFilter = () => {
|
||||
const q = input.value.trim().toLowerCase();
|
||||
filtered = q
|
||||
? actions.filter((a) => (a.label + ' ' + (a.hint || '')).toLowerCase().includes(q))
|
||||
: actions.slice();
|
||||
activeIndex = 0;
|
||||
render();
|
||||
};
|
||||
|
||||
const choose = (i) => {
|
||||
const a = filtered[i];
|
||||
close();
|
||||
if (a && a.run) a.run();
|
||||
};
|
||||
|
||||
const open = () => {
|
||||
actions = buildActions();
|
||||
input.value = '';
|
||||
applyFilter();
|
||||
palette.classList.add('open');
|
||||
palette.setAttribute('aria-hidden', 'false');
|
||||
requestAnimationFrame(() => input.focus());
|
||||
};
|
||||
const close = () => {
|
||||
palette.classList.remove('open');
|
||||
palette.setAttribute('aria-hidden', 'true');
|
||||
};
|
||||
App.enhance.openPalette = open;
|
||||
|
||||
input.addEventListener('input', applyFilter);
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'ArrowDown') { e.preventDefault(); activeIndex = Math.min(activeIndex + 1, filtered.length - 1); render(); scrollActive(); }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); activeIndex = Math.max(activeIndex - 1, 0); render(); scrollActive(); }
|
||||
else if (e.key === 'Enter') { e.preventDefault(); choose(activeIndex); }
|
||||
else if (e.key === 'Escape') { e.preventDefault(); close(); }
|
||||
});
|
||||
const scrollActive = () => {
|
||||
const el = list.children[activeIndex];
|
||||
if (el) el.scrollIntoView({ block: 'nearest' });
|
||||
};
|
||||
palette.addEventListener('click', (e) => { if (e.target === palette) close(); });
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
|
||||
e.preventDefault();
|
||||
if (palette.classList.contains('open')) close(); else open();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
initSpotlight();
|
||||
initScrollAffordances();
|
||||
initHoverPreview();
|
||||
initCommandPalette();
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
@@ -77,6 +77,7 @@ App.favorites = App.favorites || {};
|
||||
if (!key) return;
|
||||
const favorites = App.favorites.getAll();
|
||||
const existingIndex = favorites.findIndex((item) => item.key === key);
|
||||
const becameFavorite = existingIndex < 0;
|
||||
if (existingIndex >= 0) {
|
||||
favorites.splice(existingIndex, 1);
|
||||
} else {
|
||||
@@ -86,6 +87,15 @@ App.favorites = App.favorites || {};
|
||||
App.favorites.setAll(favorites);
|
||||
App.favorites.renderBar();
|
||||
App.favorites.syncButtons();
|
||||
// Celebrate an add with a brass pop + ring on every button for this key.
|
||||
if (becameFavorite) {
|
||||
document.querySelectorAll(`.favorite-btn[data-fav-key="${(window.CSS && CSS.escape) ? CSS.escape(key) : key}"]`).forEach((btn) => {
|
||||
btn.classList.remove('just-favorited');
|
||||
void btn.offsetWidth; // restart the animation
|
||||
btn.classList.add('just-favorited');
|
||||
btn.addEventListener('animationend', () => btn.classList.remove('just-favorited'), { once: true });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
App.favorites.renderBar = function() {
|
||||
@@ -104,6 +114,9 @@ App.favorites = App.favorites || {};
|
||||
card.className = 'favorite-card';
|
||||
card.dataset.favKey = item.key;
|
||||
const uploaderText = item.uploader || '';
|
||||
const durationText = (!item.isLive && App.videos && typeof App.videos.formatDuration === 'function')
|
||||
? App.videos.formatDuration(item.duration)
|
||||
: '';
|
||||
const liveBadge = item.isLive ? '<span class="live-badge">● LIVE</span>' : '';
|
||||
card.innerHTML = `
|
||||
${liveBadge}
|
||||
@@ -113,13 +126,16 @@ App.favorites = App.favorites || {};
|
||||
<button class="video-menu-item" type="button" data-action="info" role="menuitem">Show info</button>
|
||||
<button class="video-menu-item" type="button" data-action="download" role="menuitem">Download</button>
|
||||
</div>
|
||||
<div class="video-thumb">
|
||||
<img src="${item.thumb}" alt="${item.title}" loading="lazy" decoding="async">
|
||||
<div class="video-loading" aria-hidden="true">
|
||||
<div class="video-loading-spinner"></div>
|
||||
</div>
|
||||
${uploaderText ? `<button class="video-uploader uploader-link" type="button" data-uploader="${uploaderText}">${uploaderText}</button>` : ''}
|
||||
${durationText ? `<span class="video-duration">${durationText}</span>` : ''}
|
||||
</div>
|
||||
<div class="favorite-info">
|
||||
<h4>${item.title}</h4>
|
||||
${uploaderText ? `<p><button class="uploader-link" type="button" data-uploader="${uploaderText}">${uploaderText}</button></p>` : ''}
|
||||
</div>
|
||||
`;
|
||||
const thumb = card.querySelector('img');
|
||||
|
||||
@@ -32,6 +32,35 @@ App.feed = App.feed || {};
|
||||
let scrollBound = false;
|
||||
let scrollRaf = null;
|
||||
|
||||
// While true, scroll events are ignored. A viewport change (e.g. an
|
||||
// orientation switch) makes the scroll-snap container re-snap and fire
|
||||
// scroll events with positions that no longer map to the active slide;
|
||||
// onResize sets this for the brief realign window so those events don't
|
||||
// flip the active video -- rotating the device must never change which
|
||||
// slide is playing. Normal swipes (no resize in flight) are unaffected.
|
||||
let suppressScroll = false;
|
||||
let resizeSettleRaf = null;
|
||||
|
||||
// HUD auto-hide: the reels HUD fades out after this much inactivity and
|
||||
// reappears on any pointer movement / tap / scroll. Buttons keep their
|
||||
// pointer-events while hidden, so they stay clickable even when invisible.
|
||||
const HUD_IDLE_MS = 1000;
|
||||
let hudIdleTimer = null;
|
||||
let hudActivityBound = false;
|
||||
|
||||
const scheduleHudHide = function() {
|
||||
if (hudIdleTimer) clearTimeout(hudIdleTimer);
|
||||
hudIdleTimer = setTimeout(() => {
|
||||
hudIdleTimer = null;
|
||||
if (state.feedOpen) document.body.classList.add('feed-hud-idle');
|
||||
}, HUD_IDLE_MS);
|
||||
};
|
||||
|
||||
const wakeHud = function() {
|
||||
document.body.classList.remove('feed-hud-idle');
|
||||
if (state.feedOpen) scheduleHudHide();
|
||||
};
|
||||
|
||||
const getScroller = () => document.getElementById('feed-scroll');
|
||||
const getSentinel = () => document.getElementById('feed-sentinel');
|
||||
const getTopSpacer = () => document.getElementById('feed-top-spacer');
|
||||
@@ -47,9 +76,67 @@ App.feed = App.feed || {};
|
||||
return Math.min(total - 1, Math.max(0, index));
|
||||
};
|
||||
|
||||
// True when the user wants a finished clip to replay; false when it should
|
||||
// auto-advance to the next video. Defaults to looping (see storage).
|
||||
const shouldLoop = function() {
|
||||
return App.storage.getFeedEndBehavior() !== 'scroll';
|
||||
};
|
||||
|
||||
// Smoothly scrolls to the slide after `fromIndex`; the scroll-snap container
|
||||
// fires onScroll, which promotes the new slide to active. No-ops at the end
|
||||
// of the list so the final clip simply stops on its last frame.
|
||||
const advanceToNext = function(fromIndex) {
|
||||
const next = clampIndex(fromIndex + 1);
|
||||
if (next < 0 || next === fromIndex) return;
|
||||
const scroller = getScroller();
|
||||
if (scroller) scroller.scrollTo({ top: next * slideHeight(), behavior: 'smooth' });
|
||||
};
|
||||
|
||||
// Remembers playback position per video id so scrolling away and back
|
||||
// resumes where the user left off. Slides kept in the window are merely
|
||||
// paused (instant resume); slides whose <video> is torn down to free
|
||||
// resources still have their position restored on reload via applyResume.
|
||||
const KEEP_BEHIND = 2; // slides behind the active one kept loaded & paused
|
||||
const resumeTimes = new Map();
|
||||
|
||||
const slideVideoId = (slide) => (slide && slide._videoData ? slide._videoData.id : null);
|
||||
|
||||
const rememberTime = function(slide, video) {
|
||||
if (!slide || !video || slide.classList.contains('is-live')) return;
|
||||
const id = slideVideoId(slide);
|
||||
if (id == null) return;
|
||||
const t = video.currentTime;
|
||||
if (isFinite(t) && t > 0.5) resumeTimes.set(id, t);
|
||||
};
|
||||
|
||||
const applyResume = function(video, videoId, isLive) {
|
||||
if (!video || isLive || videoId == null) return;
|
||||
const t = resumeTimes.get(videoId);
|
||||
if (t == null || t <= 0) return;
|
||||
const seek = () => {
|
||||
let target = t;
|
||||
if (isFinite(video.duration) && video.duration > 0) {
|
||||
target = Math.min(t, video.duration - 0.25);
|
||||
}
|
||||
try { video.currentTime = Math.max(0, target); } catch (err) { /* ignore */ }
|
||||
};
|
||||
if (video.readyState >= 1) seek();
|
||||
else video.addEventListener('loadedmetadata', seek, { once: true });
|
||||
};
|
||||
|
||||
// Pauses a slide but keeps its <video> loaded so returning to it resumes
|
||||
// instantly from the exact frame it was paused on.
|
||||
const pauseSlide = function(slide) {
|
||||
const video = slide.querySelector('.feed-video');
|
||||
slide.classList.remove('is-active');
|
||||
if (video && !video.paused) video.pause();
|
||||
rememberTime(slide, video);
|
||||
};
|
||||
|
||||
const destroySlidePlayback = function(slide) {
|
||||
const video = slide.querySelector('.feed-video');
|
||||
slide.classList.remove('is-active');
|
||||
rememberTime(slide, video);
|
||||
const fill = slide.querySelector('.feed-timeline-fill');
|
||||
if (fill) fill.style.width = '0%';
|
||||
const handle = slide.querySelector('.feed-timeline-handle');
|
||||
@@ -59,12 +146,37 @@ App.feed = App.feed || {};
|
||||
video._hlsPlayer.destroy();
|
||||
video._hlsPlayer = null;
|
||||
}
|
||||
// Clearing the src below makes the element fire a spurious `error` event;
|
||||
// flag the teardown so the failure handler ignores it (see markSlideFailed).
|
||||
video._tearingDown = true;
|
||||
video.pause();
|
||||
video.removeAttribute('src');
|
||||
video.load();
|
||||
slide.classList.remove('is-loaded');
|
||||
};
|
||||
|
||||
// Single-line feed title that scrolls horizontally when it overflows.
|
||||
// Driven off the overflow distance so every title scrolls at the same
|
||||
// gentle speed, matching the grid-card marquee (see App.videos.measureTitle).
|
||||
const measureFeedTitle = function(slide) {
|
||||
if (!slide) return;
|
||||
const wrap = slide.querySelector('.feed-title');
|
||||
const text = slide.querySelector('.feed-title-text');
|
||||
if (!wrap || !text) return;
|
||||
const overflow = text.scrollWidth - wrap.clientWidth;
|
||||
if (overflow > 4) {
|
||||
const distance = overflow + 16;
|
||||
const MARQUEE_SPEED = 28; // px per second
|
||||
const duration = Math.max(6, distance / MARQUEE_SPEED);
|
||||
text.style.setProperty('--marquee-distance', `${distance}px`);
|
||||
text.style.setProperty('--marquee-duration', `${duration.toFixed(2)}s`);
|
||||
wrap.classList.add('is-marquee');
|
||||
} else {
|
||||
wrap.classList.remove('is-marquee');
|
||||
text.style.removeProperty('--marquee-distance');
|
||||
}
|
||||
};
|
||||
|
||||
const setTimelinePosition = function(slide, ratio) {
|
||||
const fill = slide.querySelector('.feed-timeline-fill');
|
||||
const handle = slide.querySelector('.feed-timeline-handle');
|
||||
@@ -121,6 +233,77 @@ App.feed = App.feed || {};
|
||||
timeline.addEventListener('pointercancel', stopScrubbing);
|
||||
};
|
||||
|
||||
const flashFeed = function(slide, text) {
|
||||
const flashEl = slide.querySelector('.feed-flash');
|
||||
if (!flashEl) return;
|
||||
flashEl.textContent = text;
|
||||
flashEl.classList.remove('is-visible');
|
||||
void flashEl.offsetWidth;
|
||||
flashEl.classList.add('is-visible');
|
||||
};
|
||||
|
||||
// Wires the controls shared with the standalone fullscreen player (skip
|
||||
// escalation + double-tap zones, format switching, PiP) onto a reels
|
||||
// slide, reusing the same App.customPlayer logic so both surfaces behave
|
||||
// identically. Feed's own timeline/favorite/title and scroll-snap
|
||||
// slide-to-slide navigation are untouched (see bindTimeline above and
|
||||
// setActive/onScroll below).
|
||||
const bindSharedControls = function(slide, video, videoData) {
|
||||
const cleanups = [];
|
||||
const escalator = App.customPlayer.createSkipEscalator();
|
||||
cleanups.push(() => escalator.destroy());
|
||||
|
||||
const doSkip = (direction) => {
|
||||
const amount = App.customPlayer.skip(video, direction, escalator);
|
||||
flashFeed(slide, `${direction === 'forward' ? '+' : '-'}${amount}s`);
|
||||
wakeHud();
|
||||
};
|
||||
|
||||
const pipBtn = slide.querySelector('.feed-pip-btn');
|
||||
if (pipBtn) {
|
||||
pipBtn.hidden = !App.customPlayer.supportsPiP();
|
||||
const onClick = async (event) => {
|
||||
event.stopPropagation();
|
||||
await App.customPlayer.togglePiP(video);
|
||||
};
|
||||
pipBtn.addEventListener('click', onClick);
|
||||
cleanups.push(() => pipBtn.removeEventListener('click', onClick));
|
||||
}
|
||||
cleanups.push(App.customPlayer.bindAutoPiP(video));
|
||||
|
||||
const formatBtn = slide.querySelector('.feed-format-btn');
|
||||
const formatMenu = slide.querySelector('.feed-format-menu');
|
||||
cleanups.push(App.customPlayer.bindFormatMenu(formatBtn, formatMenu, videoData, (fmt) => {
|
||||
slide._formatOverride = fmt;
|
||||
const t = video.currentTime;
|
||||
if (isFinite(t) && t > 0) resumeTimes.set(videoData.id, t);
|
||||
// Tear down the current source (mirrors destroySlidePlayback's
|
||||
// hls/video reset) before reloading with the new format -- this
|
||||
// is a live in-place reload, not a fresh never-loaded slide, so
|
||||
// the old Hls.js instance must be destroyed or it keeps running
|
||||
// (fetching segments, attached to the same <video>) forever.
|
||||
if (video._hlsPlayer) {
|
||||
video._hlsPlayer.destroy();
|
||||
video._hlsPlayer = null;
|
||||
}
|
||||
video._tearingDown = true;
|
||||
video.pause();
|
||||
video.removeAttribute('src');
|
||||
video.load();
|
||||
slide.classList.remove('is-loaded');
|
||||
loadSlideSource(slide, videoData, true);
|
||||
}));
|
||||
|
||||
cleanups.push(App.customPlayer.attachGestures(slide, {
|
||||
onSingleTap: wakeHud,
|
||||
onDoubleTapLeft: () => doSkip('back'),
|
||||
onDoubleTapRight: () => doSkip('forward'),
|
||||
ignoreSelector: 'button, input, a, .cp-format-menu, .feed-timeline'
|
||||
}));
|
||||
|
||||
slide._sharedControlCleanups = cleanups;
|
||||
};
|
||||
|
||||
const loadSlideSource = function(slide, videoData, autoplay) {
|
||||
const video = slide.querySelector('.feed-video');
|
||||
if (!video) return;
|
||||
@@ -134,16 +317,22 @@ App.feed = App.feed || {};
|
||||
}
|
||||
slide.classList.add('is-loaded');
|
||||
|
||||
const resolved = App.videos.resolveStreamSource(videoData);
|
||||
if (!resolved.url) return;
|
||||
const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : '';
|
||||
const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : '';
|
||||
const liveParam = resolved.isLive ? '&live=1' : '';
|
||||
const streamUrl = `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`;
|
||||
const resolved = slide._formatOverride
|
||||
? App.videos.resolveSourceForFormat(videoData, slide._formatOverride)
|
||||
: App.videos.resolveStreamSource(videoData);
|
||||
if (!resolved || !resolved.url) {
|
||||
// No playable source -- treat exactly like a load failure so the
|
||||
// clip is dropped from the queue and the next one takes its place.
|
||||
markSlideFailed(slide);
|
||||
return;
|
||||
}
|
||||
const streamUrl = App.videos.buildStreamUrlFromSource(resolved);
|
||||
const isHls = resolved.isLive ? true : /\.m3u8($|\?)/i.test(resolved.url);
|
||||
|
||||
video.muted = state.feedMuted;
|
||||
video.preload = 'auto';
|
||||
video._tearingDown = false;
|
||||
applyResume(video, videoData && videoData.id, resolved.isLive);
|
||||
|
||||
const startPlay = () => {
|
||||
if (!autoplay) return;
|
||||
@@ -160,6 +349,8 @@ App.feed = App.feed || {};
|
||||
if (data && data.fatal && video._hlsPlayer === hls) {
|
||||
hls.destroy();
|
||||
video._hlsPlayer = null;
|
||||
// A fatal HLS error means the stream won't play: drop it.
|
||||
markSlideFailed(slide);
|
||||
}
|
||||
});
|
||||
startPlay();
|
||||
@@ -208,12 +399,20 @@ App.feed = App.feed || {};
|
||||
slide._index = index;
|
||||
const uploaderText = v.uploader || '';
|
||||
const liveBadge = v.isLive ? '<span class="live-badge feed-live-badge">● LIVE</span>' : '';
|
||||
const favKey = App.favorites ? App.favorites.getKey(v) : null;
|
||||
slide.innerHTML = `
|
||||
<img class="feed-poster" src="${v.thumb || ''}" alt="" loading="lazy" decoding="async">
|
||||
<video class="feed-video" muted playsinline webkit-playsinline loop preload="none"></video>
|
||||
<video class="feed-video" muted playsinline webkit-playsinline preload="none"></video>
|
||||
${liveBadge}
|
||||
${favKey ? `<button class="favorite-btn feed-fav-btn" type="button" data-fav-key="${favKey}"></button>` : ''}
|
||||
<button class="cp-pip-btn feed-pip-btn" type="button" aria-label="Picture in picture" hidden>
|
||||
<img class="icon-svg" src="https://cdn.jsdelivr.net/npm/heroicons@2.0.13/24/outline/arrow-top-right-on-square.svg" alt="">
|
||||
</button>
|
||||
<button class="cp-format-btn feed-format-btn" type="button" aria-label="Quality" hidden>HD</button>
|
||||
<div class="cp-format-menu feed-format-menu" hidden></div>
|
||||
<div class="cp-flash feed-flash" aria-hidden="true"></div>
|
||||
<div class="feed-info">
|
||||
<h4 class="feed-title">${v.title || ''}</h4>
|
||||
<h4 class="feed-title"><span class="feed-title-text">${v.title || ''}</span></h4>
|
||||
${uploaderText ? `<p class="feed-uploader">${uploaderText}</p>` : ''}
|
||||
</div>
|
||||
<div class="feed-timeline" role="slider" aria-label="Seek">
|
||||
@@ -225,7 +424,34 @@ App.feed = App.feed || {};
|
||||
`;
|
||||
const poster = slide.querySelector('.feed-poster');
|
||||
App.videos.attachNoReferrerRetry(poster);
|
||||
bindTimeline(slide, slide.querySelector('.feed-video'));
|
||||
const slideVideo = slide.querySelector('.feed-video');
|
||||
bindTimeline(slide, slideVideo);
|
||||
bindSharedControls(slide, slideVideo, v);
|
||||
|
||||
// A media error (bad/expired source, network failure, unsupported codec)
|
||||
// means this clip can't play -- drop it from the queue. Errors fired by
|
||||
// our own teardown (src cleared) carry the _tearingDown flag and are
|
||||
// ignored inside markSlideFailed.
|
||||
slideVideo.addEventListener('error', () => markSlideFailed(slide));
|
||||
|
||||
// On video end, either loop (handled by the `loop` flag, so `ended`
|
||||
// never fires) or auto-scroll to the next clip. We only advance for the
|
||||
// active slide so a preloaded neighbour ending early can't hijack focus.
|
||||
slideVideo.loop = shouldLoop();
|
||||
slideVideo.addEventListener('ended', () => {
|
||||
if (shouldLoop()) return;
|
||||
if (!slide.classList.contains('is-active')) return;
|
||||
advanceToNext(slide._index);
|
||||
});
|
||||
|
||||
const favBtn = slide.querySelector('.feed-fav-btn');
|
||||
if (favBtn && App.favorites) {
|
||||
App.favorites.setButtonState(favBtn, App.favorites.getSet().has(favKey));
|
||||
favBtn.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
App.favorites.toggle(v);
|
||||
});
|
||||
}
|
||||
|
||||
// Insert before the rendered slide with the next-highest index so DOM
|
||||
// order always matches index order; fall back to the sentinel.
|
||||
@@ -242,14 +468,102 @@ App.feed = App.feed || {};
|
||||
return slide;
|
||||
};
|
||||
|
||||
// Tears down everything a slide holds -- playback (video/hls) plus the
|
||||
// shared skip/format/PiP/gesture bindings from bindSharedControls -- but
|
||||
// does not remove it from the DOM or from slidesByIndex (callers differ
|
||||
// on that: removeSlide always does, reset() removes the whole tree at
|
||||
// once).
|
||||
const teardownSlide = function(slide) {
|
||||
destroySlidePlayback(slide);
|
||||
if (Array.isArray(slide._sharedControlCleanups)) {
|
||||
slide._sharedControlCleanups.forEach((fn) => { try { fn(); } catch (err) { /* ignore */ } });
|
||||
slide._sharedControlCleanups = null;
|
||||
}
|
||||
};
|
||||
|
||||
const removeSlide = function(index) {
|
||||
const slide = slidesByIndex.get(index);
|
||||
if (!slide) return;
|
||||
destroySlidePlayback(slide);
|
||||
teardownSlide(slide);
|
||||
slide.remove();
|
||||
slidesByIndex.delete(index);
|
||||
};
|
||||
|
||||
// Re-keys every rendered slide after `removedIndex` was spliced out of
|
||||
// state.loadedVideos: indices past the hole shift down by one so
|
||||
// slidesByIndex (and each slide's _index) stays aligned with the queue.
|
||||
const reindexAfterRemoval = function(removedIndex) {
|
||||
const entries = [];
|
||||
slidesByIndex.forEach((slide, i) => entries.push([i, slide]));
|
||||
slidesByIndex.clear();
|
||||
entries.forEach(([i, slide]) => {
|
||||
const ni = i > removedIndex ? i - 1 : i;
|
||||
slide._index = ni;
|
||||
slide.dataset.index = String(ni);
|
||||
slidesByIndex.set(ni, slide);
|
||||
});
|
||||
};
|
||||
|
||||
// Drops a video that failed to load/resolve from the queue and pulls the
|
||||
// next clip into its place. A failed *preload* neighbour leaves the active
|
||||
// video playing untouched; a failed *active* clip is replaced in-place by
|
||||
// the next one (the broken frame is removed and the next clip slides into
|
||||
// the same scroll position, so playback advances without a visible jump).
|
||||
const removeVideoFromQueue = function(videoId) {
|
||||
const videos = state.loadedVideos || [];
|
||||
const r = videos.findIndex((v) => String(v.id) === String(videoId));
|
||||
if (r < 0) return;
|
||||
const prevActive = state.feedActiveIndex;
|
||||
|
||||
// Drop the failed clip's feed slide element from the DOM, then its JSON
|
||||
// from the queue, then re-key the remaining rendered slides.
|
||||
removeSlide(r);
|
||||
videos.splice(r, 1);
|
||||
reindexAfterRemoval(r);
|
||||
|
||||
// Remove the failed clip's grid card element from the DOM too (the grid
|
||||
// shares the queue) and re-pack the remaining cards.
|
||||
if (App.virtualGrid && typeof App.virtualGrid.removeVideo === 'function') {
|
||||
App.virtualGrid.removeVideo(videoId);
|
||||
}
|
||||
|
||||
if (videos.length === 0) {
|
||||
App.feed.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// The active slot only moves when the removed clip was the active one
|
||||
// (r === prevActive) or, defensively, sat before it.
|
||||
let newActive = prevActive;
|
||||
if (r < prevActive) newActive -= 1;
|
||||
newActive = clampIndex(newActive);
|
||||
|
||||
state.feedActiveIndex = -1; // force setActive to re-promote the slot
|
||||
setActive(newActive);
|
||||
|
||||
if (r <= prevActive) {
|
||||
// Active clip failed: re-anchor scroll onto the clip that slid into
|
||||
// its slot so the snap container stays pinned to the new active.
|
||||
const scroller = getScroller();
|
||||
if (scroller) scroller.scrollTop = newActive * slideHeight();
|
||||
}
|
||||
};
|
||||
|
||||
// Flags a slide whose video failed and schedules its removal from the queue.
|
||||
// Deferred to a macrotask so we never mutate slidesByIndex while setActive /
|
||||
// syncWindow is mid-iteration over it. Teardown-induced errors (src cleared)
|
||||
// are ignored via the video's _tearingDown flag, and we only act while the
|
||||
// feed is open so late errors after close are harmless.
|
||||
const markSlideFailed = function(slide) {
|
||||
if (!slide || slide._failed || !state.feedOpen) return;
|
||||
const video = slide.querySelector('.feed-video');
|
||||
if (video && video._tearingDown) return;
|
||||
const id = slideVideoId(slide);
|
||||
if (id == null) return;
|
||||
slide._failed = true;
|
||||
setTimeout(() => removeVideoFromQueue(id), 0);
|
||||
};
|
||||
|
||||
// Brings the rendered window in line with the active index: drops slides
|
||||
// that fell outside [active - HISTORY_COUNT, active + RENDER_AHEAD], builds
|
||||
// any missing ones inside it, and sizes the top spacer to stand in for the
|
||||
@@ -289,6 +603,8 @@ App.feed = App.feed || {};
|
||||
const clamped = clampIndex(index);
|
||||
if (clamped < 0) return;
|
||||
state.feedActiveIndex = clamped;
|
||||
const activeVideo = (state.loadedVideos || [])[clamped];
|
||||
state.feedActiveVideoId = activeVideo ? activeVideo.id : null;
|
||||
|
||||
syncWindow(clamped);
|
||||
|
||||
@@ -297,12 +613,19 @@ App.feed = App.feed || {};
|
||||
});
|
||||
|
||||
const activeSlide = slidesByIndex.get(clamped);
|
||||
if (activeSlide) loadSlideSource(activeSlide, activeSlide._videoData, true);
|
||||
if (activeSlide) {
|
||||
loadSlideSource(activeSlide, activeSlide._videoData, true);
|
||||
requestAnimationFrame(() => measureFeedTitle(activeSlide));
|
||||
}
|
||||
|
||||
slidesByIndex.forEach((slide, i) => {
|
||||
if (i === clamped) return;
|
||||
if (i > clamped && i <= clamped + PRELOAD_COUNT) {
|
||||
loadSlideSource(slide, slide._videoData, false);
|
||||
} else if (i >= clamped - KEEP_BEHIND && i < clamped) {
|
||||
// Recently-watched slides stay loaded but paused so scrolling
|
||||
// back resumes seamlessly from where it was paused.
|
||||
if (slide.classList.contains('is-loaded')) pauseSlide(slide);
|
||||
} else if (slide.classList.contains('is-loaded')) {
|
||||
destroySlidePlayback(slide);
|
||||
}
|
||||
@@ -312,11 +635,15 @@ App.feed = App.feed || {};
|
||||
};
|
||||
|
||||
const onScroll = function() {
|
||||
wakeHud();
|
||||
if (scrollRaf) return;
|
||||
scrollRaf = requestAnimationFrame(() => {
|
||||
scrollRaf = null;
|
||||
const scroller = getScroller();
|
||||
if (!scroller) return;
|
||||
// Ignore scroll events fired by a resize/orientation re-snap; the
|
||||
// active video is realigned by onResize instead (see suppressScroll).
|
||||
if (suppressScroll) return;
|
||||
const index = clampIndex(Math.round(scroller.scrollTop / slideHeight()));
|
||||
if (index < 0) return;
|
||||
if (index !== state.feedActiveIndex) {
|
||||
@@ -325,20 +652,65 @@ App.feed = App.feed || {};
|
||||
});
|
||||
};
|
||||
|
||||
const onResize = function() {
|
||||
if (!state.feedOpen || state.feedActiveIndex < 0) return;
|
||||
// Re-anchors the scroll position on the currently active video after the
|
||||
// viewport changes. The active slide is resolved by id (not by a possibly
|
||||
// stale scroll position) so an orientation change always keeps the same
|
||||
// video playing/focused rather than snapping to a neighbour.
|
||||
const realignToActive = function() {
|
||||
const total = (state.loadedVideos || []).length;
|
||||
if (total === 0) return;
|
||||
let index = state.feedActiveIndex;
|
||||
if (state.feedActiveVideoId != null) {
|
||||
const found = (state.loadedVideos || [])
|
||||
.findIndex((v) => String(v.id) === String(state.feedActiveVideoId));
|
||||
if (found >= 0) index = found;
|
||||
}
|
||||
index = clampIndex(index);
|
||||
if (index < 0) return;
|
||||
state.feedActiveIndex = index;
|
||||
const h = slideHeight();
|
||||
const start = Math.max(0, state.feedActiveIndex - HISTORY_COUNT);
|
||||
const start = Math.max(0, index - HISTORY_COUNT);
|
||||
const spacer = getTopSpacer();
|
||||
if (spacer) spacer.style.height = `${start * h}px`;
|
||||
const scroller = getScroller();
|
||||
if (scroller) scroller.scrollTop = state.feedActiveIndex * h;
|
||||
if (scroller) scroller.scrollTop = index * h;
|
||||
const activeSlide = slidesByIndex.get(index);
|
||||
if (activeSlide) measureFeedTitle(activeSlide);
|
||||
};
|
||||
|
||||
const onResize = function() {
|
||||
if (!state.feedOpen || state.feedActiveIndex < 0) return;
|
||||
// Suppress scroll handling while we realign so the container's re-snap
|
||||
// doesn't flip the active video, then re-enable it once layout settles.
|
||||
suppressScroll = true;
|
||||
realignToActive();
|
||||
// Orientation changes can settle over more than one frame (the visual
|
||||
// viewport and the scroll-snap re-anchor in stages); realign again once
|
||||
// layout has settled, then stop suppressing real swipes.
|
||||
if (resizeSettleRaf) cancelAnimationFrame(resizeSettleRaf);
|
||||
resizeSettleRaf = requestAnimationFrame(() => {
|
||||
realignToActive();
|
||||
resizeSettleRaf = requestAnimationFrame(() => {
|
||||
resizeSettleRaf = null;
|
||||
suppressScroll = false;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
App.feed.isOpen = function() {
|
||||
return !!state.feedOpen;
|
||||
};
|
||||
|
||||
// Re-applies the on-video-end preference to every rendered slide so toggling
|
||||
// the setting takes effect immediately, without needing to reopen the feed.
|
||||
App.feed.applyEndBehavior = function() {
|
||||
const loop = shouldLoop();
|
||||
slidesByIndex.forEach((slide) => {
|
||||
const video = slide.querySelector('.feed-video');
|
||||
if (video) video.loop = loop;
|
||||
});
|
||||
};
|
||||
|
||||
// Called whenever new video JSON is appended (e.g. after a prefetch). Lets
|
||||
// the open feed pick up newly buffered slides and extend its window if the
|
||||
// active slide is near the end.
|
||||
@@ -349,11 +721,18 @@ App.feed = App.feed || {};
|
||||
|
||||
App.feed.reset = function() {
|
||||
slidesByIndex.forEach((slide) => {
|
||||
destroySlidePlayback(slide);
|
||||
teardownSlide(slide);
|
||||
slide.remove();
|
||||
});
|
||||
slidesByIndex.clear();
|
||||
resumeTimes.clear();
|
||||
state.feedActiveIndex = -1;
|
||||
state.feedActiveVideoId = null;
|
||||
suppressScroll = false;
|
||||
if (resizeSettleRaf) {
|
||||
cancelAnimationFrame(resizeSettleRaf);
|
||||
resizeSettleRaf = null;
|
||||
}
|
||||
const spacer = getTopSpacer();
|
||||
if (spacer) spacer.style.height = '0px';
|
||||
const scroller = getScroller();
|
||||
@@ -367,7 +746,12 @@ App.feed = App.feed || {};
|
||||
state.feedOpen = true;
|
||||
|
||||
if (App.player && typeof App.player.close === 'function') {
|
||||
App.player.close();
|
||||
// fromPopState: true suppresses the player's own history.back()
|
||||
// -- this is an incidental "make sure it's closed" call when
|
||||
// switching to Reels view, not the user pressing the player's
|
||||
// close button, so it must not silently consume a back-button
|
||||
// entry out from under real browser navigation.
|
||||
App.player.close({ fromPopState: true });
|
||||
}
|
||||
|
||||
container.classList.add('open');
|
||||
@@ -381,6 +765,13 @@ App.feed = App.feed || {};
|
||||
scrollBound = true;
|
||||
}
|
||||
|
||||
if (!hudActivityBound) {
|
||||
container.addEventListener('mousemove', wakeHud, { passive: true });
|
||||
container.addEventListener('pointerdown', wakeHud, { passive: true });
|
||||
container.addEventListener('touchstart', wakeHud, { passive: true });
|
||||
hudActivityBound = true;
|
||||
}
|
||||
|
||||
// Start from whichever grid video the user was looking at.
|
||||
let startIndex = 0;
|
||||
if (startVideoId != null) {
|
||||
@@ -396,12 +787,18 @@ App.feed = App.feed || {};
|
||||
|
||||
App.feed.updateToggleButton();
|
||||
App.feed.updateMuteButton();
|
||||
wakeHud();
|
||||
};
|
||||
|
||||
App.feed.close = function() {
|
||||
const container = document.getElementById('feed-view');
|
||||
if (!container) return;
|
||||
state.feedOpen = false;
|
||||
if (hudIdleTimer) {
|
||||
clearTimeout(hudIdleTimer);
|
||||
hudIdleTimer = null;
|
||||
}
|
||||
document.body.classList.remove('feed-hud-idle');
|
||||
slidesByIndex.forEach((slide) => destroySlidePlayback(slide));
|
||||
container.classList.remove('open');
|
||||
container.setAttribute('aria-hidden', 'true');
|
||||
@@ -450,5 +847,8 @@ App.feed = App.feed || {};
|
||||
? 'https://cdn.jsdelivr.net/npm/heroicons@2.0.13/24/outline/speaker-x-mark.svg'
|
||||
: 'https://cdn.jsdelivr.net/npm/heroicons@2.0.13/24/outline/speaker-wave.svg';
|
||||
icon.alt = state.feedMuted ? 'Unmute' : 'Mute';
|
||||
// Pulse a brass ring while muted to hint "tap to hear sound".
|
||||
const btn = document.getElementById('feed-mute-btn');
|
||||
if (btn) btn.classList.toggle('is-muted', !!state.feedMuted);
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -6,6 +6,11 @@ window.App = window.App || {};
|
||||
await App.storage.ensureDefaults();
|
||||
App.ui.applyTheme();
|
||||
App.ui.applyPreferredQuality();
|
||||
App.ui.applyFeedEndBehavior();
|
||||
App.ui.applyDensity();
|
||||
// Set the text-size CSS variable before the first pack so initial card
|
||||
// heights are measured at the user's chosen size.
|
||||
document.documentElement.style.setProperty('--card-font-scale', App.storage.getFontScale());
|
||||
App.ui.renderMenu();
|
||||
App.favorites.renderBar();
|
||||
App.ui.bindGlobalHandlers();
|
||||
@@ -33,6 +38,17 @@ window.App = window.App || {};
|
||||
|
||||
await App.videos.loadVideos();
|
||||
App.favorites.syncButtons();
|
||||
|
||||
// The UI above is rendered entirely from the last known status cached in
|
||||
// localStorage, so startup never blocks on (or breaks because of) a slow
|
||||
// or failing status endpoint. Now fetch fresh status in the background and
|
||||
// reconcile the UI with whatever comes back.
|
||||
App.storage.refreshServerStatusInBackground();
|
||||
|
||||
// Watch for frontend deploys and seamlessly reload/hot-swap changed assets.
|
||||
if (App.version && App.version.start) {
|
||||
App.version.start();
|
||||
}
|
||||
}
|
||||
|
||||
initApp();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -10,14 +10,11 @@ App.state = {
|
||||
hlsPlayer: null,
|
||||
currentLoadController: null,
|
||||
errorToastTimer: null,
|
||||
playerMode: 'modal',
|
||||
playerHome: null,
|
||||
onFullscreenChange: null,
|
||||
onWebkitEndFullscreen: null,
|
||||
loadedVideos: [],
|
||||
feedOpen: false,
|
||||
feedMuted: true,
|
||||
feedActiveIndex: -1,
|
||||
feedActiveVideoId: null,
|
||||
groupCursors: null
|
||||
};
|
||||
|
||||
@@ -25,7 +22,8 @@ App.state = {
|
||||
App.constants = {
|
||||
FAVORITES_KEY: 'favorites',
|
||||
FAVORITES_VISIBILITY_KEY: 'favoritesVisible',
|
||||
PREFERRED_QUALITY_KEY: 'preferredQuality'
|
||||
PREFERRED_QUALITY_KEY: 'preferredQuality',
|
||||
FEED_END_BEHAVIOR_KEY: 'feedEndBehavior'
|
||||
};
|
||||
|
||||
// Lazily injects hls.js the first time a stream actually needs it. Sessions
|
||||
|
||||
@@ -3,7 +3,7 @@ App.storage = App.storage || {};
|
||||
App.session = App.session || {};
|
||||
|
||||
(function() {
|
||||
const { FAVORITES_KEY, FAVORITES_VISIBILITY_KEY, PREFERRED_QUALITY_KEY } = App.constants;
|
||||
const { FAVORITES_KEY, FAVORITES_VISIBILITY_KEY, PREFERRED_QUALITY_KEY, FEED_END_BEHAVIOR_KEY } = App.constants;
|
||||
|
||||
// Basic localStorage helpers.
|
||||
App.storage.getConfig = function() {
|
||||
@@ -38,6 +38,49 @@ App.session = App.session || {};
|
||||
localStorage.setItem(PREFERRED_QUALITY_KEY, nextQuality);
|
||||
};
|
||||
|
||||
// Reels/TikTok mode behavior when a video reaches its end: 'loop' replays
|
||||
// the same clip; 'scroll' advances to the next video. Defaults to 'loop'.
|
||||
App.storage.getFeedEndBehavior = function() {
|
||||
return localStorage.getItem(FEED_END_BEHAVIOR_KEY) === 'scroll' ? 'scroll' : 'loop';
|
||||
};
|
||||
|
||||
App.storage.setFeedEndBehavior = function(nextBehavior) {
|
||||
localStorage.setItem(FEED_END_BEHAVIOR_KEY, nextBehavior === 'scroll' ? 'scroll' : 'loop');
|
||||
};
|
||||
|
||||
// Grid density: 'comfortable' (default) or 'compact' (more, smaller columns).
|
||||
App.storage.getDensity = function() {
|
||||
return localStorage.getItem('density') === 'compact' ? 'compact' : 'comfortable';
|
||||
};
|
||||
|
||||
App.storage.setDensity = function(nextDensity) {
|
||||
localStorage.setItem('density', nextDensity === 'compact' ? 'compact' : 'comfortable');
|
||||
};
|
||||
|
||||
// User-tunable card width / text size multipliers (default 1.0). Clamped so a
|
||||
// stale or hand-edited value can never break the layout.
|
||||
const clampScale = function(value, min, max, fallback) {
|
||||
const n = parseFloat(value);
|
||||
if (!isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
};
|
||||
|
||||
App.storage.getCardScale = function() {
|
||||
return clampScale(localStorage.getItem('cardScale'), 0.7, 1.5, 1);
|
||||
};
|
||||
|
||||
App.storage.setCardScale = function(next) {
|
||||
localStorage.setItem('cardScale', clampScale(next, 0.7, 1.5, 1));
|
||||
};
|
||||
|
||||
App.storage.getFontScale = function() {
|
||||
return clampScale(localStorage.getItem('fontScale'), 0.8, 1.4, 1);
|
||||
};
|
||||
|
||||
App.storage.setFontScale = function(next) {
|
||||
localStorage.setItem('fontScale', clampScale(next, 0.8, 1.4, 1));
|
||||
};
|
||||
|
||||
App.storage.getServerEntries = function() {
|
||||
const config = App.storage.getConfig();
|
||||
if (!config.servers || !Array.isArray(config.servers)) return [];
|
||||
@@ -164,7 +207,11 @@ App.session = App.session || {};
|
||||
return selected;
|
||||
};
|
||||
|
||||
// Ensures defaults exist and refreshes server status.
|
||||
// Ensures defaults exist and establishes a session from cached status.
|
||||
// Intentionally does NOT touch the network: the last known status of every
|
||||
// server is persisted in localStorage, so the UI can render instantly from
|
||||
// it. Fresh status is fetched separately (and non-blockingly) via
|
||||
// refreshServerStatusInBackground().
|
||||
App.storage.ensureDefaults = async function() {
|
||||
if (!localStorage.getItem('config')) {
|
||||
localStorage.setItem('config', JSON.stringify({
|
||||
@@ -187,17 +234,91 @@ App.session = App.session || {};
|
||||
if (!localStorage.getItem(FAVORITES_VISIBILITY_KEY)) {
|
||||
localStorage.setItem(FAVORITES_VISIBILITY_KEY, 'true');
|
||||
}
|
||||
await App.storage.initializeServerStatus();
|
||||
if (!localStorage.getItem(FEED_END_BEHAVIOR_KEY)) {
|
||||
localStorage.setItem(FEED_END_BEHAVIOR_KEY, 'loop');
|
||||
}
|
||||
App.storage.ensureSessionFromCache();
|
||||
};
|
||||
|
||||
// Fetches server status and keeps the session pointing to a valid channel/options.
|
||||
// A stable fingerprint of which server/channel a session targets, used to
|
||||
// decide whether a status refresh actually changed what's being shown (and
|
||||
// thus whether videos need reloading).
|
||||
function sessionSignature(session) {
|
||||
if (!session) return '';
|
||||
return `${session.server}::${session.channel ? session.channel.id : ''}`;
|
||||
}
|
||||
|
||||
// Builds a session pointing at a valid channel/options using ONLY the status
|
||||
// data already cached in `config` (no network). Returns the session object,
|
||||
// or null if no server in the config currently exposes any channels.
|
||||
App.session.buildSessionFromCache = function(config) {
|
||||
if (!config || !Array.isArray(config.servers) || config.servers.length === 0) return null;
|
||||
const serverKeys = config.servers.map((serverObj) => Object.keys(serverObj)[0]);
|
||||
const existingSession = App.storage.getSession();
|
||||
const selectedServerKey = existingSession && serverKeys.includes(existingSession.server)
|
||||
? existingSession.server
|
||||
: serverKeys[0];
|
||||
const serverEntry = config.servers.find((serverObj) => Object.keys(serverObj)[0] === selectedServerKey);
|
||||
const serverData = serverEntry ? serverEntry[selectedServerKey] : null;
|
||||
if (!serverData || !Array.isArray(serverData.channels) || serverData.channels.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const prefs = App.storage.getPreferences();
|
||||
const serverPrefs = prefs[selectedServerKey] || {};
|
||||
const channel = App.session.resolveChannelById(serverData, serverPrefs.channelId) || serverData.channels[0];
|
||||
const savedOptions = serverPrefs.optionsByChannel ? serverPrefs.optionsByChannel[channel.id] : null;
|
||||
const options = savedOptions ? App.session.hydrateOptions(channel, savedOptions) : App.session.buildDefaultOptions(channel);
|
||||
return {
|
||||
server: selectedServerKey,
|
||||
channel: channel,
|
||||
options: options,
|
||||
};
|
||||
};
|
||||
|
||||
// Ensures the stored session points at a channel that still exists in the
|
||||
// cached status, rebuilding it from cache if necessary. Never clears a valid
|
||||
// selection. Returns true if a usable session exists afterwards.
|
||||
App.storage.ensureSessionFromCache = function() {
|
||||
const config = App.storage.getConfig();
|
||||
const serverKeys = (config.servers || []).map((serverObj) => Object.keys(serverObj)[0]);
|
||||
const existingSession = App.storage.getSession();
|
||||
|
||||
// Leave a still-valid session untouched so we don't disturb the user's
|
||||
// current server/channel selection on refresh.
|
||||
if (existingSession && existingSession.channel && serverKeys.includes(existingSession.server)) {
|
||||
const serverEntry = config.servers.find((serverObj) => Object.keys(serverObj)[0] === existingSession.server);
|
||||
const serverData = serverEntry ? serverEntry[existingSession.server] : null;
|
||||
if (serverData && App.session.resolveChannelById(serverData, existingSession.channel.id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const sessionData = App.session.buildSessionFromCache(config);
|
||||
if (sessionData) {
|
||||
App.storage.setSession(sessionData);
|
||||
App.session.savePreference(sessionData);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Fetches fresh server status and merges it into the cached config. Crucially,
|
||||
// a failed status request preserves the server's LAST KNOWN status (channels,
|
||||
// groups, etc.) instead of wiping it -- so a flaky/down status endpoint can no
|
||||
// longer brick the app. Returns true if the active session's target changed
|
||||
// (e.g. channels appeared for the first time), signalling a video reload.
|
||||
App.storage.initializeServerStatus = async function() {
|
||||
const config = JSON.parse(localStorage.getItem('config'));
|
||||
if (!config || !config.servers) return;
|
||||
if (!config || !config.servers) return false;
|
||||
|
||||
const statusPromises = config.servers.map(async (serverObj) => {
|
||||
const server = Object.keys(serverObj)[0];
|
||||
try {
|
||||
const fetchDirectStatus = async (server) => {
|
||||
const directUrl = `${server.replace(/\/$/, '')}/api/status`;
|
||||
const response = await fetch(directUrl);
|
||||
if (!response.ok) throw new Error(`Direct status request failed: ${response.status}`);
|
||||
return await response.json();
|
||||
};
|
||||
|
||||
const fetchProxiedStatus = async (server) => {
|
||||
const response = await fetch(`/api/status`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
@@ -207,44 +328,60 @@ App.session = App.session || {};
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
});
|
||||
const status = await response.json();
|
||||
serverObj[server] = status;
|
||||
if (!response.ok) throw new Error(`Proxied status request failed: ${response.status}`);
|
||||
return await response.json();
|
||||
};
|
||||
|
||||
const statusPromises = config.servers.map(async (serverObj) => {
|
||||
const server = Object.keys(serverObj)[0];
|
||||
const prior = serverObj[server];
|
||||
try {
|
||||
// Try a direct request first, then fall back to the server-side proxy.
|
||||
try {
|
||||
serverObj[server] = await fetchDirectStatus(server);
|
||||
} catch (directErr) {
|
||||
serverObj[server] = await fetchProxiedStatus(server);
|
||||
}
|
||||
} catch (err) {
|
||||
// The request failed. Keep the last known good status so the user
|
||||
// doesn't lose their channels when the status endpoint is down;
|
||||
// just flag it offline. Only fall back to an empty stub when we've
|
||||
// never successfully fetched this server.
|
||||
if (prior && Array.isArray(prior.channels) && prior.channels.length > 0) {
|
||||
serverObj[server] = Object.assign({}, prior, { online: false });
|
||||
} else {
|
||||
serverObj[server] = {
|
||||
online: false,
|
||||
channels: []
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(statusPromises);
|
||||
localStorage.setItem('config', JSON.stringify(config));
|
||||
|
||||
const existingSession = App.storage.getSession();
|
||||
const serverKeys = config.servers.map((serverObj) => Object.keys(serverObj)[0]);
|
||||
if (serverKeys.length === 0) return;
|
||||
const selectedServerKey = existingSession && serverKeys.includes(existingSession.server)
|
||||
? existingSession.server
|
||||
: serverKeys[0];
|
||||
const serverEntry = config.servers.find((serverObj) => Object.keys(serverObj)[0] === selectedServerKey);
|
||||
const serverData = serverEntry ? serverEntry[selectedServerKey] : null;
|
||||
|
||||
if (serverData && serverData.channels && serverData.channels.length > 0) {
|
||||
const prefs = App.storage.getPreferences();
|
||||
const serverPrefs = prefs[selectedServerKey] || {};
|
||||
const preferredChannelId = serverPrefs.channelId;
|
||||
const channel = App.session.resolveChannelById(serverData, preferredChannelId) || serverData.channels[0];
|
||||
const savedOptions = serverPrefs.optionsByChannel ? serverPrefs.optionsByChannel[channel.id] : null;
|
||||
const options = savedOptions ? App.session.hydrateOptions(channel, savedOptions) : App.session.buildDefaultOptions(channel);
|
||||
|
||||
const sessionData = {
|
||||
server: selectedServerKey,
|
||||
channel: channel,
|
||||
options: options,
|
||||
const before = sessionSignature(App.storage.getSession());
|
||||
App.storage.ensureSessionFromCache();
|
||||
const after = sessionSignature(App.storage.getSession());
|
||||
return before !== after;
|
||||
};
|
||||
|
||||
App.storage.setSession(sessionData);
|
||||
App.session.savePreference(sessionData);
|
||||
// Refreshes server status without blocking; updates the menu and reloads
|
||||
// videos only if the refresh actually changed the active selection. Safe to
|
||||
// fire-and-forget during startup so the UI renders from cache immediately.
|
||||
App.storage.refreshServerStatusInBackground = function() {
|
||||
return App.storage.initializeServerStatus()
|
||||
.then((changed) => {
|
||||
if (App.ui && typeof App.ui.renderMenu === 'function') {
|
||||
App.ui.renderMenu();
|
||||
}
|
||||
if (changed && App.videos && typeof App.videos.resetAndReload === 'function') {
|
||||
App.videos.resetAndReload();
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Background status refresh failed:', err);
|
||||
});
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -16,6 +16,41 @@ App.ui = App.ui || {};
|
||||
if (select) select.value = App.storage.getPreferredQuality();
|
||||
};
|
||||
|
||||
App.ui.applyFeedEndBehavior = function() {
|
||||
const select = document.getElementById('feed-end-select');
|
||||
if (select) select.value = App.storage.getFeedEndBehavior();
|
||||
};
|
||||
|
||||
App.ui.applyDensity = function() {
|
||||
const density = App.storage.getDensity();
|
||||
document.body.dataset.density = density;
|
||||
const select = document.getElementById('density-select');
|
||||
if (select) select.value = density;
|
||||
};
|
||||
|
||||
// Card Size: re-packs the virtual grid (column count derives from the scaled
|
||||
// minimum card width in videos.js).
|
||||
App.ui.applyCardScale = function() {
|
||||
const scale = App.storage.getCardScale();
|
||||
const range = document.getElementById('card-size-range');
|
||||
if (range) range.value = scale;
|
||||
if (App.virtualGrid && typeof App.virtualGrid.relayout === 'function') {
|
||||
App.virtualGrid.relayout();
|
||||
}
|
||||
};
|
||||
|
||||
// Text Size: drives the --card-font-scale CSS variable; a re-pack follows so
|
||||
// card heights account for the new text size.
|
||||
App.ui.applyFontScale = function() {
|
||||
const scale = App.storage.getFontScale();
|
||||
document.documentElement.style.setProperty('--card-font-scale', scale);
|
||||
const range = document.getElementById('text-size-range');
|
||||
if (range) range.value = scale;
|
||||
if (App.virtualGrid && typeof App.virtualGrid.relayout === 'function') {
|
||||
App.virtualGrid.relayout();
|
||||
}
|
||||
};
|
||||
|
||||
// Toast helper for playback + network errors.
|
||||
App.ui.showError = function(message) {
|
||||
const toast = document.getElementById('error-toast');
|
||||
@@ -281,6 +316,47 @@ App.ui = App.ui || {};
|
||||
};
|
||||
}
|
||||
|
||||
const densitySelect = document.getElementById('density-select');
|
||||
if (densitySelect) {
|
||||
densitySelect.value = App.storage.getDensity();
|
||||
densitySelect.onchange = () => {
|
||||
App.storage.setDensity(densitySelect.value);
|
||||
App.ui.applyDensity();
|
||||
if (App.virtualGrid && typeof App.virtualGrid.relayout === 'function') {
|
||||
App.virtualGrid.relayout();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const cardSizeRange = document.getElementById('card-size-range');
|
||||
if (cardSizeRange) {
|
||||
cardSizeRange.value = App.storage.getCardScale();
|
||||
cardSizeRange.oninput = () => {
|
||||
App.storage.setCardScale(cardSizeRange.value);
|
||||
App.ui.applyCardScale();
|
||||
};
|
||||
}
|
||||
|
||||
const textSizeRange = document.getElementById('text-size-range');
|
||||
if (textSizeRange) {
|
||||
textSizeRange.value = App.storage.getFontScale();
|
||||
textSizeRange.oninput = () => {
|
||||
App.storage.setFontScale(textSizeRange.value);
|
||||
App.ui.applyFontScale();
|
||||
};
|
||||
}
|
||||
|
||||
const feedEndSelect = document.getElementById('feed-end-select');
|
||||
if (feedEndSelect) {
|
||||
feedEndSelect.value = App.storage.getFeedEndBehavior();
|
||||
feedEndSelect.onchange = () => {
|
||||
App.storage.setFeedEndBehavior(feedEndSelect.value);
|
||||
if (App.feed && typeof App.feed.applyEndBehavior === 'function') {
|
||||
App.feed.applyEndBehavior();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (favoritesToggle) {
|
||||
favoritesToggle.checked = App.favorites.isVisible();
|
||||
favoritesToggle.onchange = () => {
|
||||
@@ -536,7 +612,6 @@ App.ui = App.ui || {};
|
||||
App.ui.bindGlobalHandlers = function() {
|
||||
window.toggleDrawer = App.ui.toggleDrawer;
|
||||
window.closeDrawers = App.ui.closeDrawers;
|
||||
window.closePlayer = App.player.close;
|
||||
window.handleSearch = App.videos.handleSearch;
|
||||
|
||||
const modeToggleBtn = document.getElementById('mode-toggle-btn');
|
||||
|
||||
140
frontend/js/version.js
Normal file
140
frontend/js/version.js
Normal file
@@ -0,0 +1,140 @@
|
||||
window.App = window.App || {};
|
||||
App.version = App.version || {};
|
||||
|
||||
(function() {
|
||||
const VERSION_URL = '/api/version';
|
||||
const POLL_INTERVAL_MS = 60000;
|
||||
|
||||
// Baseline manifest captured on startup: { version, files: { rel: hash } }.
|
||||
let baseline = null;
|
||||
let timer = null;
|
||||
// Set once a JS/HTML change is detected; the page reloads at a safe moment.
|
||||
let reloadPending = false;
|
||||
let checking = false;
|
||||
|
||||
async function fetchVersion() {
|
||||
const resp = await fetch(VERSION_URL, { cache: 'no-store' });
|
||||
if (!resp.ok) throw new Error('version fetch failed: ' + resp.status);
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
// Swap a stylesheet <link> in place using a cache-busted href so updated CSS
|
||||
// applies instantly. The old link is removed only after the new one loads to
|
||||
// avoid a flash of unstyled content.
|
||||
function hotReloadCss(relPath, hash) {
|
||||
const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
|
||||
const match = links.find((l) => {
|
||||
const href = (l.getAttribute('href') || '').split('?')[0];
|
||||
return href.endsWith(relPath) || href.endsWith('/' + relPath);
|
||||
});
|
||||
if (!match) return false;
|
||||
const base = (match.getAttribute('href') || '').split('?')[0];
|
||||
const fresh = match.cloneNode(false);
|
||||
fresh.setAttribute('href', base + '?v=' + hash);
|
||||
fresh.addEventListener('load', () => { if (match.parentNode) match.remove(); });
|
||||
fresh.addEventListener('error', () => { if (fresh.parentNode) fresh.remove(); });
|
||||
match.parentNode.insertBefore(fresh, match.nextSibling);
|
||||
return true;
|
||||
}
|
||||
|
||||
function diffFiles(oldFiles, newFiles) {
|
||||
const changed = [];
|
||||
const keys = new Set([
|
||||
...Object.keys(oldFiles || {}),
|
||||
...Object.keys(newFiles || {})
|
||||
]);
|
||||
keys.forEach((k) => {
|
||||
if ((oldFiles || {})[k] !== (newFiles || {})[k]) changed.push(k);
|
||||
});
|
||||
return changed;
|
||||
}
|
||||
|
||||
// A reload is "safe" when the user isn't mid-playback: no open custom
|
||||
// player, no active reels feed, and no playing <video>. App state survives
|
||||
// a reload because it is restored from localStorage on boot.
|
||||
function isSafeToReload() {
|
||||
if (App.state && App.state.feedOpen) return false;
|
||||
const player = document.getElementById('custom-player');
|
||||
if (player && player.classList.contains('open')) {
|
||||
const video = player.querySelector('.cp-video');
|
||||
if (video && !video.paused && !video.ended) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function showUpdateBanner() {
|
||||
const banner = document.getElementById('update-banner');
|
||||
if (!banner) return;
|
||||
banner.classList.add('show');
|
||||
const btn = document.getElementById('update-banner-btn');
|
||||
if (btn) btn.onclick = () => window.location.reload();
|
||||
}
|
||||
|
||||
function tryReloadWhenSafe() {
|
||||
if (!reloadPending) return;
|
||||
if (isSafeToReload()) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
showUpdateBanner();
|
||||
}
|
||||
}
|
||||
|
||||
function apply(latest) {
|
||||
const changed = diffFiles(baseline.files, latest.files);
|
||||
if (!changed.length) return;
|
||||
|
||||
let needsReload = false;
|
||||
changed.forEach((file) => {
|
||||
if (file.endsWith('.css') && hotReloadCss(file, latest.files[file])) {
|
||||
return; // hot-swapped without reload
|
||||
}
|
||||
// JS and HTML can't be safely live-patched; they require a reload.
|
||||
needsReload = true;
|
||||
});
|
||||
|
||||
// Adopt the new manifest so we don't re-trigger on the same change.
|
||||
baseline = latest;
|
||||
|
||||
if (needsReload) {
|
||||
reloadPending = true;
|
||||
tryReloadWhenSafe();
|
||||
}
|
||||
}
|
||||
|
||||
async function check() {
|
||||
if (checking || !baseline) return;
|
||||
checking = true;
|
||||
try {
|
||||
const latest = await fetchVersion();
|
||||
apply(latest);
|
||||
} catch (e) {
|
||||
// Network blips are non-fatal; we retry on the next tick.
|
||||
} finally {
|
||||
checking = false;
|
||||
}
|
||||
}
|
||||
|
||||
App.version.start = async function() {
|
||||
try {
|
||||
baseline = await fetchVersion();
|
||||
} catch (e) {
|
||||
return; // endpoint unavailable; skip version checking entirely
|
||||
}
|
||||
timer = setInterval(check, POLL_INTERVAL_MS);
|
||||
// Check promptly when the user returns to the tab so updates land while
|
||||
// they were away, and retry a pending reload once playback stops.
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
tryReloadWhenSafe();
|
||||
check();
|
||||
}
|
||||
});
|
||||
// Re-attempt a deferred reload whenever a video finishes/pauses. The
|
||||
// custom player's <video> is torn down and rebuilt on every open(), so
|
||||
// bind on the capture phase at the document level instead of to a
|
||||
// specific element (media events don't bubble, but capture still sees
|
||||
// them on ancestors).
|
||||
document.addEventListener('pause', tryReloadWhenSafe, true);
|
||||
document.addEventListener('ended', tryReloadWhenSafe, true);
|
||||
};
|
||||
})();
|
||||
@@ -71,10 +71,26 @@ App.videos = App.videos || {};
|
||||
const overflow = titleText.scrollWidth - titleWrap.clientWidth;
|
||||
if (overflow > 4) {
|
||||
card.classList.add('has-marquee');
|
||||
titleText.style.setProperty('--marquee-distance', `${overflow + 12}px`);
|
||||
const distance = overflow + 12;
|
||||
titleText.style.setProperty('--marquee-distance', `${distance}px`);
|
||||
// Drive the duration off the distance so every title scrolls at the
|
||||
// same gentle speed (px/sec) instead of a fixed duration that made
|
||||
// longer titles whip past. A floor keeps short titles from snapping.
|
||||
const MARQUEE_SPEED = 28; // px per second
|
||||
const MARQUEE_MIN_DURATION = 6; // seconds
|
||||
const duration = Math.max(MARQUEE_MIN_DURATION, distance / MARQUEE_SPEED);
|
||||
titleText.style.setProperty('--marquee-duration', `${duration.toFixed(2)}s`);
|
||||
// Only marquee cards need the scroll-position observer that picks the
|
||||
// centered card to animate; observing every card made scrolling a
|
||||
// large grid needlessly expensive.
|
||||
if (titleObserver) titleObserver.observe(card);
|
||||
} else {
|
||||
card.classList.remove('has-marquee', 'is-title-active');
|
||||
titleText.style.removeProperty('--marquee-distance');
|
||||
if (titleObserver) {
|
||||
titleObserver.unobserve(card);
|
||||
titleVisibility.delete(card);
|
||||
}
|
||||
}
|
||||
updateTitleActive(card);
|
||||
};
|
||||
@@ -87,6 +103,8 @@ App.videos = App.videos || {};
|
||||
document.querySelectorAll('.video-card').forEach((card) => {
|
||||
measureTitle(card);
|
||||
});
|
||||
// The virtualizer re-packs and remounts on resize via its own
|
||||
// listener; nothing else to do here.
|
||||
});
|
||||
};
|
||||
|
||||
@@ -280,17 +298,11 @@ App.videos = App.videos || {};
|
||||
}
|
||||
};
|
||||
|
||||
// Renders new cards for videos, wiring favorites + playback behavior.
|
||||
App.videos.renderVideos = function(videos) {
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (!grid) return;
|
||||
|
||||
const items = videos && Array.isArray(videos.items) ? videos.items : [];
|
||||
// Builds a fully-wired video card element for `v`. Kept separate from
|
||||
// mounting so the virtualizer can create a card the moment it needs to be
|
||||
// on screen and throw it away once it scrolls out of the window.
|
||||
App.videos.buildCard = function(v) {
|
||||
const favoritesSet = App.favorites.getSet();
|
||||
items.forEach(v => {
|
||||
if (state.renderedVideoIds.has(v.id)) return;
|
||||
state.loadedVideos.push(v);
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'video-card';
|
||||
card.dataset.videoId = v.id;
|
||||
@@ -310,20 +322,19 @@ App.videos = App.videos || {};
|
||||
<button class="video-menu-item" type="button" data-action="info" role="menuitem">Show info</button>
|
||||
<button class="video-menu-item" type="button" data-action="download" role="menuitem">Download</button>
|
||||
</div>
|
||||
<div class="video-thumb">
|
||||
<img src="${v.thumb}" alt="${v.title}" loading="lazy" decoding="async">
|
||||
<div class="video-loading" aria-hidden="true">
|
||||
<div class="video-loading-spinner"></div>
|
||||
</div>
|
||||
${uploaderText ? `<button class="video-uploader uploader-link" type="button" data-uploader="${uploaderText}">${uploaderText}</button>` : ''}
|
||||
${durationText ? `<span class="video-duration">${durationText}</span>` : ''}
|
||||
</div>
|
||||
<h4 class="video-title"><span class="video-title-text">${v.title}</span></h4>
|
||||
${tagsMarkup}
|
||||
${uploaderText ? `<p class="video-meta"><button class="uploader-link" type="button" data-uploader="${uploaderText}">${uploaderText}</button></p>` : ''}
|
||||
${durationText ? `<p class="video-duration">${durationText}</p>` : ''}
|
||||
`;
|
||||
const thumb = card.querySelector('img');
|
||||
App.videos.attachNoReferrerRetry(thumb);
|
||||
if (thumb) {
|
||||
thumb.addEventListener('load', App.videos.scheduleMasonryLayout);
|
||||
}
|
||||
const favoriteBtn = card.querySelector('.favorite-btn');
|
||||
if (favoriteBtn && favoriteKey) {
|
||||
App.favorites.setButtonState(favoriteBtn, favoritesSet.has(favoriteKey));
|
||||
@@ -335,9 +346,6 @@ App.videos = App.videos || {};
|
||||
const titleWrap = card.querySelector('.video-title');
|
||||
const titleText = card.querySelector('.video-title-text');
|
||||
if (titleWrap && titleText) {
|
||||
requestAnimationFrame(() => {
|
||||
measureTitle(card);
|
||||
});
|
||||
card.addEventListener('focusin', () => {
|
||||
card.dataset.titleFocused = '1';
|
||||
updateTitleActive(card);
|
||||
@@ -355,9 +363,9 @@ App.videos = App.videos || {};
|
||||
card.dataset.titleHovered = '0';
|
||||
updateTitleActive(card);
|
||||
});
|
||||
} else if (titleObserver) {
|
||||
titleObserver.observe(card);
|
||||
}
|
||||
// On touch devices the marquee observer is attached lazily by
|
||||
// measureTitle (called on mount), and only for overflowing titles.
|
||||
}
|
||||
const uploaderBtn = card.querySelector('.uploader-link');
|
||||
if (uploaderBtn) {
|
||||
@@ -406,11 +414,32 @@ App.videos = App.videos || {};
|
||||
card.classList.add('is-loading');
|
||||
App.player.open(v, { originEl: card });
|
||||
};
|
||||
grid.appendChild(card);
|
||||
state.renderedVideoIds.add(v.id);
|
||||
});
|
||||
cardVideo.set(card, v);
|
||||
card.addEventListener('pointerenter', () => App.videos.resolveAndProbe(v), { once: true });
|
||||
return card;
|
||||
};
|
||||
|
||||
// Appends a freshly-loaded page of videos. The card DOM is *not* built here;
|
||||
// we only grow the data buffer, extend the masonry layout for the new
|
||||
// items, then let the virtualizer mount whatever currently falls inside the
|
||||
// viewport window.
|
||||
App.videos.renderVideos = function(videos) {
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (!grid) return;
|
||||
App.virtualGrid.ensureInit();
|
||||
|
||||
const items = videos && Array.isArray(videos.items) ? videos.items : [];
|
||||
const startLen = state.loadedVideos.length;
|
||||
items.forEach((v) => {
|
||||
if (state.renderedVideoIds.has(v.id)) return;
|
||||
state.renderedVideoIds.add(v.id);
|
||||
state.loadedVideos.push(v);
|
||||
});
|
||||
if (state.loadedVideos.length > startLen) {
|
||||
App.virtualGrid.packFrom(startLen);
|
||||
}
|
||||
App.virtualGrid.update();
|
||||
|
||||
App.videos.scheduleMasonryLayout();
|
||||
if (App.feed && typeof App.feed.renderSlides === 'function') {
|
||||
App.feed.renderSlides();
|
||||
}
|
||||
@@ -462,8 +491,7 @@ App.videos = App.videos || {};
|
||||
state.renderedVideoIds.clear();
|
||||
state.loadedVideos = [];
|
||||
state.groupCursors = null;
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (grid) grid.innerHTML = "";
|
||||
App.virtualGrid.reset();
|
||||
if (App.feed && typeof App.feed.reset === 'function') {
|
||||
App.feed.reset();
|
||||
}
|
||||
@@ -482,8 +510,7 @@ App.videos = App.videos || {};
|
||||
state.renderedVideoIds.clear();
|
||||
state.loadedVideos = [];
|
||||
state.groupCursors = null;
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (grid) grid.innerHTML = "";
|
||||
App.virtualGrid.reset();
|
||||
if (App.feed && typeof App.feed.reset === 'function') {
|
||||
App.feed.reset();
|
||||
}
|
||||
@@ -501,32 +528,327 @@ App.videos = App.videos || {};
|
||||
}
|
||||
};
|
||||
|
||||
let masonryRaf = null;
|
||||
App.videos.scheduleMasonryLayout = function() {
|
||||
if (masonryRaf) {
|
||||
cancelAnimationFrame(masonryRaf);
|
||||
// ---------------------------------------------------------------------
|
||||
// Virtualized masonry grid
|
||||
//
|
||||
// The full set of loaded videos lives in state.loadedVideos. Only the cards
|
||||
// whose computed position falls within the viewport (plus an overscan
|
||||
// buffer) are kept in the DOM; the rest are unmounted. The container is
|
||||
// given an explicit pixel height and every card is absolutely positioned at
|
||||
// a precomputed (top,left), so:
|
||||
// * the scrollbar and scroll position are identical to a fully-rendered
|
||||
// grid, and
|
||||
// * mounting/unmounting a card never moves any other card -- positions are
|
||||
// assigned once and never change -- so there is no scroll jank.
|
||||
//
|
||||
// Thumbnails keep their natural aspect ratio (not cropped), so a card's real
|
||||
// height isn't known until its image loads. We place each card with a 16:9
|
||||
// estimate first, then once the image loads we correct that card's height
|
||||
// and shift only the cards below it *in the same column* (each column is an
|
||||
// independent vertical stack), so a correction never disturbs other columns
|
||||
// or anything above it. Columns are assigned once and never change.
|
||||
// ---------------------------------------------------------------------
|
||||
App.virtualGrid = (function() {
|
||||
const mounted = new Map(); // loadedVideos index -> card element
|
||||
const revealed = new Set(); // indices that have played their entrance once
|
||||
const layout = []; // index -> { top, left, width, height, col, posInCol }
|
||||
const heightCache = new Map(); // shape signature -> estimated px height
|
||||
let colItems = []; // col -> ordered list of item indices in that column
|
||||
let colBottoms = []; // running bottom y of each column
|
||||
let cols = 0, colWidth = 0, gap = 16, padX = 24, padY = 24;
|
||||
let initialized = false;
|
||||
let rafPending = false;
|
||||
const OVERSCAN = 1.2; // viewports of cards kept mounted off-screen
|
||||
|
||||
const grid = () => document.getElementById('video-grid');
|
||||
|
||||
const measureMetrics = function() {
|
||||
const el = grid();
|
||||
if (!el) return false;
|
||||
const phone = window.matchMedia('(max-width: 480px)').matches;
|
||||
const mobile = window.matchMedia('(max-width: 768px)').matches;
|
||||
const large = window.matchMedia('(min-width: 1600px)').matches;
|
||||
gap = mobile ? 12 : (large ? 24 : 16);
|
||||
padX = mobile ? 16 : (large ? 48 : 24);
|
||||
padY = mobile ? 16 : (large ? 32 : 24);
|
||||
// We own positioning, so neutralize the CSS grid + padding and read
|
||||
// the resulting content width (which still honors max-width:auto
|
||||
// centering).
|
||||
el.style.display = 'block';
|
||||
el.style.position = 'relative';
|
||||
el.style.padding = '0';
|
||||
const inner = el.clientWidth - padX * 2;
|
||||
if (inner <= 0) return false;
|
||||
// Density toggle (see enhance.js / settings) tunes the minimum card
|
||||
// width, so "compact" packs more columns at the same viewport width.
|
||||
// The user's Card Size setting scales that minimum on top of density.
|
||||
const cardScale = (App.storage && App.storage.getCardScale) ? App.storage.getCardScale() : 1;
|
||||
const minCardW = (document.body.dataset.density === 'compact' ? 210 : 260) * cardScale;
|
||||
// One card per row on phones, two on larger handsets/tablets, and a
|
||||
// size-driven count on desktop.
|
||||
cols = phone ? 1 : (mobile ? 2 : Math.max(1, Math.floor((inner + gap) / (minCardW + gap))));
|
||||
colWidth = (inner - gap * (cols - 1)) / cols;
|
||||
return true;
|
||||
};
|
||||
|
||||
const signatureOf = function(v) {
|
||||
const hasTags = Array.isArray(v.tags) && v.tags.some((t) => t);
|
||||
return [Math.round(colWidth), v.isLive ? 1 : 0, hasTags ? 1 : 0,
|
||||
v.uploader ? 1 : 0, (v.duration > 0) ? 1 : 0].join('|');
|
||||
};
|
||||
|
||||
// Estimated height of a card of `v`'s shape at the current column width,
|
||||
// using the CSS 16:9 thumbnail placeholder (the image isn't loaded in the
|
||||
// probe). Measured once per shape, then cached. The real height replaces
|
||||
// this per-card once the thumbnail loads (see correct()).
|
||||
const heightOf = function(v) {
|
||||
const sig = signatureOf(v);
|
||||
const cached = heightCache.get(sig);
|
||||
if (cached != null) return cached;
|
||||
const el = grid();
|
||||
if (!el) return 240;
|
||||
const probe = App.videos.buildCard(v);
|
||||
probe.style.position = 'absolute';
|
||||
probe.style.visibility = 'hidden';
|
||||
probe.style.left = '-99999px';
|
||||
probe.style.top = '0';
|
||||
probe.style.width = colWidth + 'px';
|
||||
el.appendChild(probe);
|
||||
const h = probe.getBoundingClientRect().height;
|
||||
el.removeChild(probe);
|
||||
heightCache.set(sig, h || 240);
|
||||
return h || 240;
|
||||
};
|
||||
|
||||
const setContainerHeight = function() {
|
||||
const el = grid();
|
||||
if (!el) return;
|
||||
const maxBottom = colBottoms.length ? Math.max.apply(null, colBottoms) : padY;
|
||||
el.style.height = Math.max(0, maxBottom - gap + padY) + 'px';
|
||||
};
|
||||
|
||||
// Assigns positions to items [start, end). Earlier items keep their
|
||||
// positions because colBottoms carries forward unchanged. Each item is
|
||||
// assigned to the currently-shortest column and stays there for good.
|
||||
const packFrom = function(start) {
|
||||
if (!cols) { if (!measureMetrics()) return; }
|
||||
if (!colBottoms.length) colBottoms = new Array(cols).fill(padY);
|
||||
if (!colItems.length) colItems = Array.from({ length: cols }, () => []);
|
||||
for (let i = start; i < state.loadedVideos.length; i++) {
|
||||
const v = state.loadedVideos[i];
|
||||
const h = heightOf(v);
|
||||
let col = 0;
|
||||
for (let c = 1; c < cols; c++) {
|
||||
if (colBottoms[c] < colBottoms[col]) col = c;
|
||||
}
|
||||
masonryRaf = requestAnimationFrame(() => {
|
||||
masonryRaf = null;
|
||||
App.videos.applyMasonryLayout();
|
||||
const top = colBottoms[col];
|
||||
layout[i] = {
|
||||
top,
|
||||
left: padX + col * (colWidth + gap),
|
||||
width: colWidth,
|
||||
height: h,
|
||||
col,
|
||||
posInCol: colItems[col].length
|
||||
};
|
||||
colItems[col].push(i);
|
||||
colBottoms[col] = top + h + gap;
|
||||
}
|
||||
setContainerHeight();
|
||||
};
|
||||
|
||||
// Replaces item i's estimated height with its real (post-image-load)
|
||||
// height and slides every card below it in the same column by the delta.
|
||||
// Other columns and everything above are untouched -> no global reflow.
|
||||
const correct = function(i) {
|
||||
const card = mounted.get(i);
|
||||
const l = layout[i];
|
||||
if (!card || !l) return;
|
||||
const real = card.getBoundingClientRect().height;
|
||||
if (!real || Math.abs(real - l.height) < 1) return;
|
||||
const delta = real - l.height;
|
||||
l.height = real;
|
||||
const list = colItems[l.col];
|
||||
for (let k = l.posInCol + 1; k < list.length; k++) {
|
||||
const j = list[k];
|
||||
layout[j].top += delta;
|
||||
const mc = mounted.get(j);
|
||||
if (mc) mc.style.top = layout[j].top + 'px';
|
||||
}
|
||||
colBottoms[l.col] += delta;
|
||||
setContainerHeight();
|
||||
scheduleUpdate();
|
||||
};
|
||||
|
||||
const place = function(card, l) {
|
||||
card.style.position = 'absolute';
|
||||
card.style.top = l.top + 'px';
|
||||
card.style.left = l.left + 'px';
|
||||
card.style.width = l.width + 'px';
|
||||
};
|
||||
|
||||
const mount = function(i) {
|
||||
if (mounted.has(i)) return;
|
||||
const v = state.loadedVideos[i];
|
||||
const l = layout[i];
|
||||
if (!v || !l) return;
|
||||
const card = App.videos.buildCard(v);
|
||||
place(card, l);
|
||||
// Entrance animation only the first time an index appears, so cards
|
||||
// don't re-animate every time they scroll back into the window.
|
||||
if (!revealed.has(i)) {
|
||||
revealed.add(i);
|
||||
card.classList.add('is-revealing');
|
||||
card.addEventListener('animationend', () => card.classList.remove('is-revealing'), { once: true });
|
||||
}
|
||||
grid().appendChild(card);
|
||||
mounted.set(i, card);
|
||||
// Once the thumbnail loads, drop the 16:9 placeholder so it shows at
|
||||
// its true aspect ratio, clear the shimmer, then correct the height.
|
||||
const img = card.querySelector('img');
|
||||
if (img) {
|
||||
const reveal = () => {
|
||||
img.style.aspectRatio = 'auto';
|
||||
img.classList.add('is-loaded');
|
||||
if (mounted.get(i) === card) correct(i);
|
||||
};
|
||||
if (img.complete && img.naturalHeight > 0) requestAnimationFrame(reveal);
|
||||
else img.addEventListener('load', reveal);
|
||||
}
|
||||
// Marquee + direct-playability probe only matter for on-screen cards.
|
||||
requestAnimationFrame(() => { if (mounted.get(i) === card) measureTitle(card); });
|
||||
probeObserver.observe(card);
|
||||
};
|
||||
|
||||
const unmount = function(i) {
|
||||
const card = mounted.get(i);
|
||||
if (!card) return;
|
||||
probeObserver.unobserve(card);
|
||||
if (titleObserver) {
|
||||
titleObserver.unobserve(card);
|
||||
titleVisibility.delete(card);
|
||||
}
|
||||
cardVideo.delete(card);
|
||||
card.remove();
|
||||
mounted.delete(i);
|
||||
};
|
||||
|
||||
// Mounts cards intersecting the viewport window, unmounts the rest.
|
||||
const update = function() {
|
||||
const el = grid();
|
||||
if (!el || !state.loadedVideos.length) return;
|
||||
const rectTop = el.getBoundingClientRect().top; // container top vs viewport
|
||||
const vh = window.innerHeight || 800;
|
||||
const viewTop = -rectTop; // viewport top in container space
|
||||
const start = viewTop - vh * OVERSCAN;
|
||||
const end = viewTop + vh * (1 + OVERSCAN);
|
||||
for (let i = 0; i < layout.length; i++) {
|
||||
const l = layout[i];
|
||||
if (!l) continue;
|
||||
const visible = l.top < end && (l.top + l.height) > start;
|
||||
if (visible) mount(i);
|
||||
else if (mounted.has(i)) unmount(i);
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleUpdate = function() {
|
||||
if (rafPending) return;
|
||||
rafPending = true;
|
||||
requestAnimationFrame(() => { rafPending = false; update(); });
|
||||
};
|
||||
|
||||
// Full re-pack + remount, used when the column geometry changes.
|
||||
const relayout = function() {
|
||||
if (!measureMetrics()) return;
|
||||
heightCache.clear(); // colWidth changed -> heights differ
|
||||
mounted.forEach((card, i) => unmount(i));
|
||||
layout.length = 0;
|
||||
colBottoms = new Array(cols).fill(padY);
|
||||
colItems = Array.from({ length: cols }, () => []);
|
||||
packFrom(0);
|
||||
update();
|
||||
};
|
||||
|
||||
// Records the topmost card crossing (or just below) the viewport top,
|
||||
// plus how far its top sits from the viewport top. A column re-pack (on
|
||||
// resize / orientation change) reassigns every card's position, so the
|
||||
// raw scrollTop would otherwise point at a different video afterwards.
|
||||
// Anchoring on the topmost visible card (rather than the centred one)
|
||||
// is independent of the viewport height, which has *already* changed by
|
||||
// the time a resize/orientation event fires -- so it stays correct even
|
||||
// as portrait<->landscape swaps the height out from under us.
|
||||
const captureAnchor = function() {
|
||||
let anchor = null;
|
||||
let bestTop = Infinity;
|
||||
mounted.forEach((card, i) => {
|
||||
const rect = card.getBoundingClientRect();
|
||||
if (rect.bottom <= 0) return; // fully scrolled past
|
||||
if (rect.top < bestTop) {
|
||||
bestTop = rect.top;
|
||||
anchor = { index: i, offsetTop: rect.top };
|
||||
}
|
||||
});
|
||||
return anchor;
|
||||
};
|
||||
|
||||
// Scrolls so the anchored card sits at the same viewport offset it had
|
||||
// before the re-pack, keeping the user's place across the layout change.
|
||||
const restoreAnchor = function(anchor) {
|
||||
if (!anchor) return;
|
||||
const el = grid();
|
||||
const l = layout[anchor.index];
|
||||
if (!el || !l) return;
|
||||
const gridTopDoc = el.getBoundingClientRect().top + window.scrollY;
|
||||
const target = gridTopDoc + l.top - anchor.offsetTop;
|
||||
window.scrollTo(0, Math.max(0, target));
|
||||
};
|
||||
|
||||
let resizeRaf = null;
|
||||
let pendingAnchor = null;
|
||||
const ensureInit = function() {
|
||||
if (!cols) measureMetrics();
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
window.addEventListener('scroll', scheduleUpdate, { passive: true });
|
||||
window.addEventListener('resize', () => {
|
||||
// Capture before the re-pack (positions are still the old ones)
|
||||
// and keep the earliest anchor across a burst of resize events.
|
||||
if (!pendingAnchor) pendingAnchor = captureAnchor();
|
||||
if (resizeRaf) cancelAnimationFrame(resizeRaf);
|
||||
resizeRaf = requestAnimationFrame(() => {
|
||||
resizeRaf = null;
|
||||
relayout();
|
||||
restoreAnchor(pendingAnchor);
|
||||
pendingAnchor = null;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
App.videos.applyMasonryLayout = function() {
|
||||
const grid = document.getElementById('video-grid');
|
||||
if (!grid) return;
|
||||
const styles = window.getComputedStyle(grid);
|
||||
if (styles.display !== 'grid') return;
|
||||
const rowHeight = parseInt(styles.getPropertyValue('grid-auto-rows'), 10);
|
||||
const rowGap = parseInt(styles.getPropertyValue('row-gap') || styles.getPropertyValue('gap'), 10) || 0;
|
||||
if (!rowHeight) return;
|
||||
Array.from(grid.children).forEach((item) => {
|
||||
const itemHeight = item.getBoundingClientRect().height;
|
||||
const span = Math.ceil((itemHeight + rowGap) / (rowHeight + rowGap));
|
||||
item.style.gridRowEnd = `span ${span}`;
|
||||
});
|
||||
const reset = function() {
|
||||
mounted.forEach((card, i) => unmount(i));
|
||||
mounted.clear();
|
||||
revealed.clear(); // new result set should animate in again
|
||||
layout.length = 0;
|
||||
colBottoms = [];
|
||||
colItems = [];
|
||||
const el = grid();
|
||||
if (el) { el.innerHTML = ''; el.style.height = '0px'; }
|
||||
};
|
||||
|
||||
// Removes a single video's card from the grid: its DOM element is
|
||||
// unmounted directly (so it's gone even if the re-pack below can't run),
|
||||
// then the remaining cards are re-packed against the now-shorter queue.
|
||||
// The caller must have already removed the video from state.loadedVideos.
|
||||
const removeVideo = function(videoId) {
|
||||
const id = String(videoId);
|
||||
mounted.forEach((card, i) => {
|
||||
if (card.dataset.videoId === id) unmount(i);
|
||||
});
|
||||
relayout();
|
||||
};
|
||||
|
||||
return { ensureInit, packFrom, update: scheduleUpdate, relayout, removeVideo, reset };
|
||||
})();
|
||||
|
||||
App.videos.updateLoadMoreState = function() {
|
||||
const loadMoreBtn = document.getElementById('load-more-btn');
|
||||
if (!loadMoreBtn) return;
|
||||
@@ -570,6 +892,23 @@ App.videos = App.videos || {};
|
||||
return headers[name] || headers[name.toLowerCase()] || '';
|
||||
};
|
||||
|
||||
// Merge the resource-level (meta) and format-level http_headers into a single
|
||||
// map so every upstream header the extractor attached (Referer, User-Agent,
|
||||
// Cookie, etc.) can be relayed to the stream proxy. Format-level headers win
|
||||
// on conflict since they describe the specific media URL.
|
||||
const mergeHeaders = function(metaHeaders, fmtHeaders) {
|
||||
const merged = {};
|
||||
[metaHeaders, fmtHeaders].forEach((headers) => {
|
||||
if (!headers || typeof headers !== 'object') return;
|
||||
Object.keys(headers).forEach((name) => {
|
||||
const value = headers[name];
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
merged[name] = String(value);
|
||||
});
|
||||
});
|
||||
return merged;
|
||||
};
|
||||
|
||||
const deriveReferer = function(url) {
|
||||
if (!url) return '';
|
||||
try {
|
||||
@@ -647,7 +986,7 @@ App.videos = App.videos || {};
|
||||
const isLive = !!(videoOrUrl && typeof videoOrUrl === 'object' &&
|
||||
(videoOrUrl.isLive || (videoOrUrl.meta && videoOrUrl.meta.isLive)));
|
||||
if (typeof videoOrUrl === 'string') {
|
||||
return videoOrUrl ? [{ url: videoOrUrl, referer: deriveReferer(videoOrUrl), userAgent: '', isLive }] : [];
|
||||
return videoOrUrl ? [{ url: videoOrUrl, referer: deriveReferer(videoOrUrl), userAgent: '', isLive, refererRequired: false }] : [];
|
||||
}
|
||||
if (!videoOrUrl || typeof videoOrUrl !== 'object') return [];
|
||||
|
||||
@@ -661,9 +1000,15 @@ App.videos = App.videos || {};
|
||||
}
|
||||
|
||||
const sources = App.videos.rankFormats(meta.formats, preferredHeight).map((fmt) => {
|
||||
const referer = headerValue(fmt.http_headers, 'Referer') || metaReferer || deriveReferer(fmt.url);
|
||||
// An *explicit* Referer (from the extractor) signals the upstream
|
||||
// enforces it; deriveReferer is only a best-effort fallback. The
|
||||
// browser can't set a cross-origin Referer, so refererRequired tells
|
||||
// callers (the probe) that direct playback can't work.
|
||||
const explicitReferer = headerValue(fmt.http_headers, 'Referer') || metaReferer;
|
||||
const referer = explicitReferer || deriveReferer(fmt.url);
|
||||
const userAgent = headerValue(fmt.http_headers, 'User-Agent') || metaUserAgent;
|
||||
return { url: fmt.url, referer, userAgent, isLive };
|
||||
const headers = mergeHeaders(meta.http_headers, fmt.http_headers);
|
||||
return { url: fmt.url, referer, userAgent, headers, isLive, refererRequired: !!explicitReferer };
|
||||
});
|
||||
|
||||
if (!sources.length) {
|
||||
@@ -673,7 +1018,9 @@ App.videos = App.videos || {};
|
||||
url: fallbackUrl,
|
||||
referer: metaReferer || deriveReferer(fallbackUrl),
|
||||
userAgent: metaUserAgent,
|
||||
isLive
|
||||
headers: mergeHeaders(meta.http_headers, null),
|
||||
isLive,
|
||||
refererRequired: !!metaReferer
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -682,23 +1029,210 @@ App.videos = App.videos || {};
|
||||
|
||||
App.videos.resolveStreamSource = function(videoOrUrl, options) {
|
||||
const sources = App.videos.resolveStreamSources(videoOrUrl, options);
|
||||
return sources.length ? sources[0] : { url: '', referer: '', userAgent: '', isLive: false };
|
||||
return sources.length ? sources[0] : { url: '', referer: '', userAgent: '', isLive: false, refererRequired: false };
|
||||
};
|
||||
|
||||
// Resolves one specific format (as picked from a format-switcher menu, see
|
||||
// App.customPlayer.buildFormatOptions) into a playable source, using the
|
||||
// same header-merging rules as the automatic ranked path above.
|
||||
App.videos.resolveSourceForFormat = function(videoOrUrl, fmt) {
|
||||
if (!fmt || !fmt.url) return null;
|
||||
const isLive = !!(videoOrUrl && typeof videoOrUrl === 'object' &&
|
||||
(videoOrUrl.isLive || (videoOrUrl.meta && videoOrUrl.meta.isLive)));
|
||||
const meta = (videoOrUrl && typeof videoOrUrl === 'object' && (videoOrUrl.meta || videoOrUrl)) || {};
|
||||
const metaReferer = headerValue(meta.http_headers, 'Referer');
|
||||
const metaUserAgent = headerValue(meta.http_headers, 'User-Agent');
|
||||
const explicitReferer = headerValue(fmt.http_headers, 'Referer') || metaReferer;
|
||||
const referer = explicitReferer || deriveReferer(fmt.url);
|
||||
const userAgent = headerValue(fmt.http_headers, 'User-Agent') || metaUserAgent;
|
||||
const headers = mergeHeaders(meta.http_headers, fmt.http_headers);
|
||||
return { url: fmt.url, referer, userAgent, headers, isLive, refererRequired: !!explicitReferer };
|
||||
};
|
||||
|
||||
// Background "direct playability" probe. The backend proxy exists to work
|
||||
// around CORS, hotlink (403) protection, and TLS fingerprinting. When the
|
||||
// browser can fetch a media URL cross-origin and actually read the response
|
||||
// (CORS allowed, not blocked/403), playing it directly works and the proxy
|
||||
// is pure overhead. CORS is an origin-level policy, so the answer is the
|
||||
// same for every media URL served by a given host: we probe (and cache)
|
||||
// once per host and let the player skip the proxy for any URL on a host
|
||||
// that's been proven.
|
||||
const DIRECT_PROBE_TIMEOUT_MS = 8000;
|
||||
|
||||
const directHostOf = (url) => {
|
||||
try { return new URL(url).host; } catch (err) { return ''; }
|
||||
};
|
||||
|
||||
// host -> true (proven directly playable) | false (proven not). Absent
|
||||
// means unknown/unprobed, in which case the proxy is used.
|
||||
App.videos._directStatus = new Map();
|
||||
const directPending = new Map();
|
||||
|
||||
App.videos.isDirectProven = function(url) {
|
||||
return App.videos._directStatus.get(directHostOf(url)) === true;
|
||||
};
|
||||
|
||||
App.videos.probeDirect = function(url) {
|
||||
if (!url) return Promise.resolve(false);
|
||||
const host = directHostOf(url);
|
||||
if (!host) return Promise.resolve(false);
|
||||
if (App.videos._directStatus.has(host)) {
|
||||
return Promise.resolve(App.videos._directStatus.get(host));
|
||||
}
|
||||
if (directPending.has(host)) {
|
||||
return directPending.get(host);
|
||||
}
|
||||
const promise = (async () => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), DIRECT_PROBE_TIMEOUT_MS);
|
||||
let ok = false;
|
||||
let detail = '';
|
||||
try {
|
||||
// A simple GET (no custom headers) avoids a CORS preflight. If
|
||||
// the response is readable and successful, CORS + reachability
|
||||
// are both proven; we abort immediately so the body isn't
|
||||
// downloaded (it can be a whole video file).
|
||||
const res = await fetch(url, {
|
||||
method: 'GET',
|
||||
mode: 'cors',
|
||||
credentials: 'omit',
|
||||
signal: controller.signal
|
||||
});
|
||||
ok = res.ok || res.status === 206;
|
||||
detail = `HTTP ${res.status}`;
|
||||
controller.abort();
|
||||
} catch (err) {
|
||||
ok = false;
|
||||
detail = (err && err.name === 'AbortError') ? 'timeout' : (err && err.message) || 'fetch failed';
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
App.videos._directStatus.set(host, ok);
|
||||
directPending.delete(host);
|
||||
console.log(`[direct-probe] ${ok ? 'DIRECT' : 'PROXY '} (${detail}) ${host}`);
|
||||
return ok;
|
||||
})();
|
||||
directPending.set(host, promise);
|
||||
return promise;
|
||||
};
|
||||
|
||||
// Kicks off a background probe of a video's best (first-played) source so a
|
||||
// later playback can skip the proxy if its host is proven reachable. Only
|
||||
// runs once the video has resolved formats (see resolveAndProbe): those are
|
||||
// real media URLs (or redirects to them), whereas a bare listing item only
|
||||
// carries a page URL that the player can't use directly.
|
||||
App.videos.probeVideoSources = function(video) {
|
||||
if (!video || typeof video !== 'object') return;
|
||||
const meta = video.meta || video;
|
||||
if (!meta || !Array.isArray(meta.formats) || !meta.formats.length) return;
|
||||
let sources;
|
||||
try {
|
||||
sources = App.videos.resolveStreamSources(video);
|
||||
} catch (err) {
|
||||
return;
|
||||
}
|
||||
const best = sources && sources[0];
|
||||
if (!best || !best.url || best.isLive) return;
|
||||
// Sources that require a specific upstream Referer can't be fetched
|
||||
// directly by the browser (it can't forge a cross-origin Referer), so a
|
||||
// probe would always fail -- leave them to the proxy.
|
||||
if (best.refererRequired) return;
|
||||
App.videos.probeDirect(best.url);
|
||||
};
|
||||
|
||||
// Listing items arrive without formats (meta is null) -- only a page URL --
|
||||
// so there's nothing direct-playable to probe up front. This resolves a
|
||||
// video's real media formats via the backend (yt-dlp), attaches them as
|
||||
// `video.meta` so the player and probe can use them, then probes the best
|
||||
// source. Resolution is per-video and deduped: it runs at most once per
|
||||
// video, triggered lazily by hover/scroll so we don't resolve cards the
|
||||
// user never looks at.
|
||||
const cardVideo = new WeakMap();
|
||||
const metaResolved = new Set();
|
||||
const metaPending = new Map();
|
||||
|
||||
const probeObserver = new IntersectionObserver((entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (!entry.isIntersecting) return;
|
||||
probeObserver.unobserve(entry.target);
|
||||
const video = cardVideo.get(entry.target);
|
||||
if (video) App.videos.resolveAndProbe(video);
|
||||
});
|
||||
}, { rootMargin: '200px' });
|
||||
|
||||
App.videos.resolveAndProbe = function(video) {
|
||||
if (!video || typeof video !== 'object' || !video.id) return Promise.resolve();
|
||||
// Already have formats (resolved earlier): just (re)probe the best one.
|
||||
if (video.meta && Array.isArray(video.meta.formats) && video.meta.formats.length) {
|
||||
App.videos.probeVideoSources(video);
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (metaResolved.has(video.id)) return Promise.resolve();
|
||||
if (metaPending.has(video.id)) return metaPending.get(video.id);
|
||||
if (!video.url) return Promise.resolve();
|
||||
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const response = await fetch('/api/resolve', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: video.url })
|
||||
});
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
if (data && Array.isArray(data.formats) && data.formats.length) {
|
||||
video.meta = data;
|
||||
App.videos.probeVideoSources(video);
|
||||
}
|
||||
} catch (err) {
|
||||
// Best-effort: playback still works through the proxy.
|
||||
} finally {
|
||||
metaResolved.add(video.id);
|
||||
metaPending.delete(video.id);
|
||||
}
|
||||
})();
|
||||
metaPending.set(video.id, promise);
|
||||
return promise;
|
||||
};
|
||||
|
||||
// Builds a proxied stream URL. Extra params other than `url` are forwarded
|
||||
// by the backend as request headers, so use real header names here.
|
||||
App.videos.buildStreamUrlFromSource = function(resolved) {
|
||||
if (!resolved || !resolved.url) return '';
|
||||
const refererParam = resolved.referer ? `&referer=${encodeURIComponent(resolved.referer)}` : '';
|
||||
const userAgentParam = resolved.userAgent ? `&User-Agent=${encodeURIComponent(resolved.userAgent)}` : '';
|
||||
const liveParam = resolved.isLive ? '&live=1' : '';
|
||||
return `/api/stream?url=${encodeURIComponent(resolved.url)}${refererParam}${userAgentParam}${liveParam}`;
|
||||
const params = [];
|
||||
// Referer keeps its dedicated lowercase param (the backend maps it back to
|
||||
// `Referer`) so the derived-referer fallback in resolveStreamSources is
|
||||
// honoured even when no explicit Referer header was present.
|
||||
if (resolved.referer) params.push(`referer=${encodeURIComponent(resolved.referer)}`);
|
||||
if (resolved.userAgent) params.push(`User-Agent=${encodeURIComponent(resolved.userAgent)}`);
|
||||
// Relay every other upstream header the extractor attached (e.g. Cookie).
|
||||
// Referer/User-Agent are already emitted above, so skip them here to avoid
|
||||
// duplicating the same header under two query keys.
|
||||
const headers = resolved.headers;
|
||||
if (headers && typeof headers === 'object') {
|
||||
Object.keys(headers).forEach((name) => {
|
||||
const lower = name.toLowerCase();
|
||||
if (lower === 'referer' || lower === 'user-agent') return;
|
||||
const value = headers[name];
|
||||
if (value === undefined || value === null || value === '') return;
|
||||
params.push(`${encodeURIComponent(name)}=${encodeURIComponent(value)}`);
|
||||
});
|
||||
}
|
||||
if (resolved.isLive) params.push('live=1');
|
||||
const query = params.length ? `&${params.join('&')}` : '';
|
||||
return `/api/stream?url=${encodeURIComponent(resolved.url)}${query}`;
|
||||
};
|
||||
|
||||
App.videos.buildStreamUrl = function(videoOrUrl, options) {
|
||||
return App.videos.buildStreamUrlFromSource(App.videos.resolveStreamSource(videoOrUrl, options));
|
||||
};
|
||||
|
||||
// Lets enhancement layers (e.g. hover preview) recover the video object that
|
||||
// backs a mounted card without reaching into the virtualizer internals.
|
||||
App.videos.getVideoForCard = function(card) {
|
||||
return cardVideo.get(card);
|
||||
};
|
||||
|
||||
App.videos.downloadVideo = function(video) {
|
||||
if (!video) return;
|
||||
const streamUrl = App.videos.buildStreamUrl(video, { applyPreferredQuality: false });
|
||||
|
||||
Reference in New Issue
Block a user