Files
jacuzzi/frontend/js/favorites.js
Simon d508263946 Don't re-resolve a favorite whose URL is already the media file
Some channels hand back the media URL itself as an item's url. Since the
favorites fix, opening one of those sent it to /api/resolve first, so
yt-dlp fetched the media just to report the URL we already had. On a
signed link (`?secure=<ts>-<token>`) that is a second request against
something that may be single-use or IP-bound, and the request that
matters -- the playback fetch -- is then refused. Such URLs now play
directly, with no resolve round trip, as they did before.

Alongside that, three things that make expiry survivable:

/api/stream, after its existing referer-less retry, now retries a 403
completely bare (Range only). Signed CDN links are routinely served to a
plain browser request and refused when it carries extras -- a
`Sec-Fetch-Mode: navigate` on a media subresource, say, which is what
yt-dlp's generic extractor hands back and no real player would send.

When every source fails, the player re-resolves once and retries instead
of giving up, since the likeliest cause is that signed URLs went stale in
a long-open tab rather than the video being gone. A manual quality pick
is dropped for that retry, as it names one of the URLs that just failed.

Favorites stored by older versions still carry a `meta` blob of resolved
formats, long expired; it's now stripped on read so nothing can reach for
one.

Verified: a favorite whose url is a .mp4 plays with zero /api/resolve
calls, straight from that URL; playback, prefetch, feed paging, HUD,
rotation, momentum and the version check all still pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QBDkEXP4htyXTCZUwMLphd
2026-09-05 20:41:31 +00:00

224 lines
10 KiB
JavaScript

window.App = window.App || {};
App.favorites = App.favorites || {};
(function() {
const { FAVORITES_KEY, FAVORITES_VISIBILITY_KEY } = App.constants;
// Favorites storage helpers.
App.favorites.getAll = function() {
try {
const raw = localStorage.getItem(FAVORITES_KEY);
const parsed = raw ? JSON.parse(raw) : [];
if (!Array.isArray(parsed)) return [];
// Favorites saved by older versions carry a `meta` blob of resolved
// formats whose URLs are signed and long expired. Drop it on the way
// in so no code path can reach for one; everything re-resolves from
// `url` at play time, and normalize() no longer stores it.
return parsed.map((item) => {
if (item && typeof item === 'object' && item.meta) {
const clean = Object.assign({}, item);
delete clean.meta;
return clean;
}
return item;
});
} catch (err) {
return [];
}
};
App.favorites.setAll = function(items) {
localStorage.setItem(FAVORITES_KEY, JSON.stringify(items));
};
App.favorites.getKey = function(video) {
if (!video) return null;
const meta = video.meta || video;
return video.key || meta.key || video.id || meta.id || video.url || meta.url || null;
};
App.favorites.normalize = function(video) {
const key = App.favorites.getKey(video);
if (!key) return null;
const meta = video && video.meta ? video.meta : video;
return {
key,
id: video.id || null,
// The page/source URL (e.g. the YouTube watch URL), not a resolved
// CDN media URL -- those expire, so favorites must always re-resolve
// via the server at play time instead of caching a stream link.
url: video.url || (meta && meta.url) || '',
title: video.title || '',
thumb: video.thumb || '',
channel: video.channel || (meta && meta.channel) || '',
uploader: video.uploader || (meta && meta.uploader) || '',
duration: video.duration || (meta && meta.duration) || 0,
isLive: !!(video.isLive || (meta && meta.isLive))
// No `meta` field: persisting resolved formats would freeze their
// (expiring) CDN URLs into localStorage. Leaving it unset makes a
// favorite look like a fresh, unresolved listing item again, so
// playback/download/info all re-resolve through the backend from
// `url` -- see resolveStreamSources' no-formats fallback, which the
// backend resolves live via yt-dlp (main.py stream_video).
};
};
App.favorites.getSet = function() {
return new Set(App.favorites.getAll().map((item) => item.key));
};
App.favorites.isVisible = function() {
return localStorage.getItem(FAVORITES_VISIBILITY_KEY) !== 'false';
};
App.favorites.setVisible = function(isVisible) {
localStorage.setItem(FAVORITES_VISIBILITY_KEY, isVisible ? 'true' : 'false');
};
// UI helpers for rendering and syncing heart states.
App.favorites.setButtonState = function(button, isFavorite) {
button.classList.toggle('is-favorite', isFavorite);
button.textContent = isFavorite ? '♥' : '♡';
button.setAttribute('aria-pressed', isFavorite ? 'true' : 'false');
button.setAttribute('aria-label', isFavorite ? 'Remove from favorites' : 'Add to favorites');
};
App.favorites.syncButtons = function() {
const favoritesSet = App.favorites.getSet();
document.querySelectorAll('.favorite-btn[data-fav-key]').forEach((button) => {
const key = button.dataset.favKey;
if (!key) return;
App.favorites.setButtonState(button, favoritesSet.has(key));
});
};
App.favorites.toggle = function(video) {
const key = App.favorites.getKey(video);
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 {
const entry = App.favorites.normalize(video);
if (entry) favorites.unshift(entry);
}
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() {
const bar = document.getElementById('favorites-bar');
const list = document.getElementById('favorites-list');
const empty = document.getElementById('favorites-empty');
if (!bar || !list) return;
const favorites = App.favorites.getAll();
const visible = App.favorites.isVisible();
bar.style.display = visible ? 'block' : 'none';
list.innerHTML = "";
favorites.forEach((item) => {
const card = document.createElement('div');
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}
<button class="favorite-btn is-favorite" type="button" aria-pressed="true" aria-label="Remove from favorites" data-fav-key="${item.key}">♥</button>
<button class="video-menu-btn" type="button" aria-haspopup="true" aria-expanded="false" aria-label="More options">⋯</button>
<div class="video-menu" role="menu">
<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>
</div>
`;
const thumb = card.querySelector('img');
if (App.videos && typeof App.videos.attachNoReferrerRetry === 'function') {
App.videos.attachNoReferrerRetry(thumb);
}
card.onclick = () => {
if (card.classList.contains('is-loading')) return;
card.classList.add('is-loading');
// Ignore any stale `meta` a favorite saved before this fix may
// still carry in localStorage -- always re-resolve from `item`
// (id/url) so playback never reuses an expired stream URL.
App.player.open(item, { originEl: card });
};
const favoriteBtn = card.querySelector('.favorite-btn');
if (favoriteBtn) {
favoriteBtn.onclick = (event) => {
event.stopPropagation();
App.favorites.toggle(item);
};
}
const menuBtn = card.querySelector('.video-menu-btn');
const menu = card.querySelector('.video-menu');
const showInfoBtn = card.querySelector('.video-menu-item[data-action="info"]');
const downloadBtn = card.querySelector('.video-menu-item[data-action="download"]');
if (menuBtn && menu) {
menuBtn.onclick = (event) => {
event.stopPropagation();
App.videos.toggleMenu(menu, menuBtn);
};
}
if (showInfoBtn) {
showInfoBtn.onclick = (event) => {
event.stopPropagation();
App.videos.closeAllMenus();
// Favorites deliberately store no resolved metadata, so pull
// it fresh before showing the full info dump.
App.videos.ensureFormats(item).then(() => App.ui.showInfo(item));
};
}
if (downloadBtn) {
downloadBtn.onclick = (event) => {
event.stopPropagation();
App.videos.closeAllMenus();
// Same as playback: resolve a real media URL first rather
// than pointing the download at the page URL.
App.videos.ensureFormats(item).then(() => App.videos.downloadVideo(item));
};
}
const uploaderBtn = card.querySelector('.uploader-link');
if (uploaderBtn) {
uploaderBtn.onclick = (event) => {
event.stopPropagation();
const uploader = uploaderBtn.dataset.uploader || uploaderBtn.textContent || '';
App.videos.handleSearch(uploader);
};
}
list.appendChild(card);
});
if (empty) {
empty.style.display = favorites.length > 0 ? 'none' : 'block';
}
};
})();