Files
ani-cli-web/watchlist_page.py
T

1251 lines
40 KiB
Python

#!/usr/bin/env python3
"""Watchlist page template for ani-cli-web."""
from template_helpers import BROWSER_API_HELPER, BROWSER_POLL_HELPER, render_page_links, render_sidebar_brand
WATCHLIST_HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ani-cli web - watchlist</title>
<style>
:root {
color-scheme: dark;
--bg: #090611;
--bg-2: #140d21;
--panel: rgba(25, 18, 41, 0.82);
--panel-strong: rgba(18, 13, 31, 0.92);
--panel-2: rgba(157, 123, 255, 0.12);
--line: rgba(255, 255, 255, 0.08);
--line-strong: rgba(157, 123, 255, 0.26);
--text: #f6f2ff;
--muted: #b8b0cf;
--accent: #9d7bff;
--accent-strong: #7b5cff;
--accent-soft: rgba(157, 123, 255, 0.14);
--good: #95e4ba;
--bad: #ff90a4;
--focus: #b296ff;
--shadow: 0 24px 60px rgba(5, 2, 15, 0.42);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(circle at top left, rgba(157, 123, 255, 0.18), transparent 28%),
radial-gradient(circle at top right, rgba(117, 201, 255, 0.12), transparent 24%),
linear-gradient(180deg, #120c1d 0%, #0b0813 56%, #07050d 100%);
color: var(--text);
font: 15px/1.5 "Segoe UI", Inter, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
}
body::before {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.03), transparent 24%);
opacity: 0.5;
}
button, input, select {
font: inherit;
}
button {
border: 1px solid var(--line);
background: var(--panel-2);
color: var(--text);
min-height: 40px;
border-radius: 14px;
padding: 0 14px;
cursor: pointer;
transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease, box-shadow 0.16s ease;
}
button:hover {
border-color: var(--line-strong);
background: rgba(157, 123, 255, 0.18);
transform: translateY(-1px);
}
button.primary {
background: linear-gradient(135deg, var(--accent), var(--accent-strong));
border-color: transparent;
color: #fcfaff;
font-weight: 700;
box-shadow: 0 16px 32px rgba(123, 92, 255, 0.26);
}
button.ghost {
background: transparent;
}
input, select {
width: 100%;
min-height: 42px;
border-radius: 14px;
border: 1px solid var(--line);
background: rgba(10, 7, 18, 0.82);
color: var(--text);
padding: 0 13px;
outline: none;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
}
input:focus {
border-color: var(--focus);
box-shadow: 0 0 0 3px rgba(178, 150, 255, 0.12);
}
select:focus {
border-color: var(--focus);
box-shadow: 0 0 0 3px rgba(178, 150, 255, 0.12);
}
label {
display: grid;
gap: 7px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.app {
display: grid;
grid-template-columns: minmax(320px, 380px) 1fr;
min-height: 100vh;
}
aside, main {
padding: 22px;
}
aside {
border-right: 1px solid var(--line);
background: linear-gradient(180deg, rgba(25, 18, 41, 0.94), rgba(14, 10, 24, 0.9));
display: grid;
align-content: start;
gap: 20px;
backdrop-filter: blur(18px) saturate(170%);
}
main {
display: grid;
gap: 20px;
min-width: 0;
}
.topline, .toolbar, .row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.topline, .toolbar {
justify-content: space-between;
}
.brand-wrap {
display: grid;
gap: 6px;
}
.brand-word {
color: var(--accent);
}
.shell-note {
color: var(--muted);
font-size: 13px;
max-width: 28ch;
}
.page-links {
display: grid;
gap: 8px;
padding: 6px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255, 255, 255, 0.03);
}
.page-link {
display: flex;
align-items: center;
justify-content: flex-start;
width: 100%;
min-height: 40px;
border: 0;
border-radius: 12px;
padding: 0 14px;
color: var(--muted);
background: transparent;
font-weight: 700;
text-decoration: none;
transition: background 0.16s ease, color 0.16s ease, transform 0.16s ease;
}
.page-link.active {
background: var(--accent-soft);
color: var(--text);
box-shadow: inset 0 0 0 1px rgba(157, 123, 255, 0.22);
}
.page-link:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.05);
}
h1, h2, h3, p { margin: 0; }
h1 {
font-size: 29px;
line-height: 1.05;
letter-spacing: -0.04em;
}
h2 {
font-size: 17px;
letter-spacing: -0.02em;
}
h3 { font-size: 15px; }
.row > * { flex: 1; }
.row {
align-items: end;
}
.settings, .summary-card, .watchlist-shell {
border: 1px solid var(--line);
border-radius: 22px;
background: linear-gradient(180deg, rgba(29, 22, 47, 0.88), rgba(17, 13, 29, 0.94));
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.settings {
padding: 18px;
display: grid;
gap: 14px;
}
.watchlist-shell {
padding: 18px;
display: grid;
gap: 14px;
}
.muted {
color: var(--muted);
font-size: 13px;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
}
.summary-card {
padding: 18px;
display: grid;
gap: 6px;
}
.summary-value {
font-size: 32px;
font-weight: 800;
line-height: 1;
}
.summary-label {
color: var(--muted);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.badge {
border: 1px solid var(--line);
border-radius: 999px;
padding: 6px 10px;
color: var(--muted);
background: rgba(255, 255, 255, 0.04);
font-size: 12px;
white-space: nowrap;
}
.notice {
min-height: 20px;
color: #ddd0ff;
font-size: 13px;
}
.field-hint {
color: var(--muted);
font-size: 12px;
}
.stack {
display: grid;
gap: 6px;
}
.watchlist-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 12px;
min-width: 0;
}
.category-tabs {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.category-tab {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 38px;
border: 1px solid var(--line);
border-radius: 999px;
padding: 0 14px;
background: rgba(255, 255, 255, 0.04);
color: var(--muted);
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease;
}
.category-tab.active {
background: rgba(157, 123, 255, 0.18);
border-color: rgba(157, 123, 255, 0.34);
color: var(--text);
}
.anime-card {
border: 1px solid var(--line);
border-radius: 20px;
background: linear-gradient(180deg, rgba(32, 24, 54, 0.9) 0%, rgba(17, 13, 29, 0.96) 100%);
padding: 12px;
display: grid;
gap: 12px;
min-width: 0;
box-shadow: 0 18px 38px rgba(5, 2, 15, 0.32);
transition: transform 0.18s ease, border-color 0.18s ease;
}
.anime-card.fully-ready {
border-color: rgba(149, 228, 186, 0.72);
box-shadow:
inset 0 0 0 1px rgba(149, 228, 186, 0.18),
0 18px 38px rgba(5, 2, 15, 0.32);
}
.anime-card:hover {
border-color: var(--line-strong);
transform: translateY(-2px);
}
.anime-card.fully-ready:hover {
border-color: rgba(149, 228, 186, 0.88);
}
.anime-card.error {
border-color: rgba(255, 144, 164, 0.3);
}
.cover-tile {
aspect-ratio: 3 / 4;
position: relative;
border-radius: 16px;
overflow: hidden;
border: 1px solid rgba(157, 123, 255, 0.16);
background:
radial-gradient(circle at top, rgba(157, 123, 255, 0.28), transparent 44%),
linear-gradient(180deg, #221734 0%, #0c0915 100%);
}
.cover-tile img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.cover-fallback {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: #d8e5ef;
font-size: 28px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
background: linear-gradient(180deg, rgba(157, 123, 255, 0.24), rgba(9, 7, 15, 0.18));
}
.cover-tile.has-image .cover-fallback {
display: none;
}
.thumb-reload-btn {
position: absolute;
top: 8px;
right: 8px;
z-index: 2;
min-height: 28px;
padding: 0 8px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(12, 9, 20, 0.84);
color: #d8e5ef;
font-size: 11px;
font-weight: 700;
cursor: pointer;
}
.thumb-reload-btn:hover,
.thumb-reload-btn:focus-visible {
background: rgba(157, 123, 255, 0.18);
}
.thumb-reload-btn:disabled {
opacity: 0.65;
cursor: wait;
}
.thumb-upload-btn {
position: absolute;
left: 8px;
bottom: 8px;
z-index: 2;
min-height: 28px;
padding: 0 8px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(12, 9, 20, 0.84);
color: #d8e5ef;
font-size: 11px;
font-weight: 700;
cursor: pointer;
display: none;
}
.thumb-upload-btn:hover,
.thumb-upload-btn:focus-visible {
background: rgba(157, 123, 255, 0.18);
}
.thumb-upload-btn:disabled {
opacity: 0.65;
cursor: wait;
}
.card-title {
font-size: 14px;
font-weight: 800;
line-height: 1.3;
min-height: 2.6em;
overflow-wrap: anywhere;
}
.title-row {
display: flex;
align-items: start;
gap: 8px;
}
.title-row .card-title {
flex: 1;
min-width: 0;
}
.card-title a {
color: inherit;
text-decoration: none;
}
.card-title a:hover,
.card-title a:focus-visible {
text-decoration: underline;
}
.count-row {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.count-pill {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, 0.04);
color: var(--muted);
font-size: 12px;
padding: 6px 10px;
}
.count-pill strong {
color: var(--text);
font-size: 13px;
}
.count-pill.complete {
border-color: rgba(149, 228, 186, 0.3);
background: rgba(149, 228, 186, 0.12);
color: #d6f7e5;
}
.count-pill.complete strong {
color: var(--good);
}
.status-row {
display: flex;
gap: 6px;
flex-wrap: wrap;
min-height: 30px;
}
.status-tag {
display: inline-flex;
align-items: center;
border: 1px solid var(--line);
border-radius: 999px;
padding: 5px 10px;
background: rgba(255, 255, 255, 0.04);
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.status-tag.complete {
border-color: rgba(149, 228, 186, 0.3);
background: rgba(149, 228, 186, 0.12);
color: var(--good);
}
.finish-check {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 999px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.06);
color: #a0a5b5;
font-size: 14px;
line-height: 1;
flex: 0 0 auto;
}
.finish-check.downloaded {
border-color: rgba(149, 228, 186, 0.3);
background: rgba(149, 228, 186, 0.12);
color: var(--good);
}
.finish-check.manual {
color: #a3a7b5;
}
.card-date {
min-height: 44px;
font-size: 12px;
line-height: 1.35;
white-space: pre-line;
}
.category-editor {
display: grid;
gap: 6px;
}
.category-editor label {
font-size: 10px;
letter-spacing: 0.08em;
}
.category-editor select {
min-height: 36px;
padding: 0 10px;
font-size: 13px;
}
.card-actions {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.card-actions button {
min-height: 34px;
padding: 0 10px;
}
.pager {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.pager-controls {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.empty {
border: 1px dashed rgba(157, 123, 255, 0.22);
border-radius: 22px;
color: var(--muted);
padding: 24px;
text-align: center;
background: rgba(157, 123, 255, 0.06);
}
@media (max-width: 1500px) {
.watchlist-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@media (max-width: 1240px) {
.watchlist-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 900px) {
.app { grid-template-columns: 1fr; }
aside { border-right: 0; border-bottom: 1px solid var(--line); }
.toolbar, .row { align-items: stretch; flex-direction: column; }
.summary-grid { grid-template-columns: 1fr; }
.watchlist-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 560px) {
.watchlist-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="app">
<aside>
""" + render_sidebar_brand(
"Tsuki-inspired watch tracking with softer cards and poster-first scanning.",
"Watchlist",
) + render_page_links("watchlist") + r"""
<section class="settings">
<div class="toolbar">
<div>
<h2>Add manually</h2>
<p class="muted">Track a show directly when you already know its AllAnime ID.</p>
</div>
</div>
<form id="watchlist-form" class="stack" onsubmit="event.preventDefault(); addAnimeToWatchlist();">
<label>Anime title
<input type="text" id="watchlist-title" placeholder="Anime Title" required>
</label>
<label>Show ID
<input type="text" id="watchlist-show-id" placeholder="Show ID" required>
</label>
<label>Category
<select id="watchlist-category">
<option value="watching">Watching</option>
<option value="planned">Planned</option>
<option value="finished">Finished</option>
<option value="dropped">Dropped</option>
</select>
</label>
<div class="field-hint">Tip: you can also add entries directly from the Search page.</div>
<button class="primary" type="submit">Add to watchlist</button>
</form>
</section>
<section class="settings">
<h2>How it works</h2>
<div class="stack muted">
<p>Use Refresh to pull the latest sub and dub episode counts for a single show.</p>
<p>Use Download all to queue every currently available episode after choosing sub or dub.</p>
<p>Refresh All updates your whole tracked list in one pass.</p>
</div>
</section>
</aside>
<main>
<section class="watchlist-shell">
<div class="toolbar">
<div>
<h2>Tracked shows</h2>
<p class="muted">Compact cards with local AnimeSchedule cover caching when artwork is available.</p>
</div>
<button class="ghost" id="refreshAllWatchlistBtn" type="button">Refresh All</button>
</div>
<div class="notice" id="notice"></div>
<div class="summary-grid" id="watchlist-summary">
<div class="summary-card">
<span class="summary-value">0</span>
<span class="summary-label">Tracked shows</span>
</div>
<div class="summary-card">
<span class="summary-value">0</span>
<span class="summary-label">Sub episodes</span>
</div>
<div class="summary-card">
<span class="summary-value">0</span>
<span class="summary-label">Dub episodes</span>
</div>
</div>
</section>
<section class="watchlist-shell">
<div class="toolbar">
<div>
<h2>Watchlist library</h2>
<p class="muted" id="watchlist-meta">Compact poster grid for faster scanning.</p>
<p class="muted" id="refreshJobStatus"></p>
</div>
</div>
<div class="category-tabs" id="watchlistTabs"></div>
<div class="watchlist-grid" id="watchlist-container"></div>
<div class="pager" id="watchlistPager"></div>
</section>
</main>
</div>
<script>
const state = {
watchlistPage: 1,
watchlistPages: 1,
watchlistTotal: 0,
watchlistPerPage: 30,
queuedCount: 0,
watchlistCategory: "watching",
thumbnailNonce: Date.now(),
thumbnailWarmupTokens: {},
thumbnailWarmupPending: new Set(),
refreshRunning: false,
refreshJobId: null,
watchlistRequestId: 0
};
const categoryLabels = {
watching: "Watching",
planned: "Planned",
finished: "Finished",
dropped: "Dropped"
};
const $ = (id) => document.getElementById(id);
""" + BROWSER_API_HELPER + BROWSER_POLL_HELPER + r"""
function setNotice(text) {
$("notice").textContent = text || "";
}
function setRefreshAllButton(running) {
const button = $("refreshAllWatchlistBtn");
if (!button) return;
button.disabled = !!running;
button.textContent = running ? "Refreshing..." : "Refresh All";
}
function setRefreshJobStatus(job) {
const el = $("refreshJobStatus");
if (!el) return;
if (!job) {
el.textContent = "";
return;
}
if (job.status === "running") {
el.textContent = `${job.completed || 0}/${job.total || 0} refreshed${job.current_title ? ` · ${job.current_title}` : ""}`;
return;
}
el.textContent = job.message || "";
}
function coverInitials(title) {
const parts = String(title || "")
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2);
if (!parts.length) return "AN";
return parts.map((part) => part[0]).join("").slice(0, 2);
}
function watchlistCardClassName(item) {
const isFullyReady = item.sub_complete && item.dub_complete;
return `anime-card${item.status === "error" ? " error" : ""}${isFullyReady ? " fully-ready" : ""}`;
}
function formatModeProgress(currentCount, expectedCount) {
const current = Number(currentCount || 0);
const expected = Number(expectedCount || 0);
return expected > 0 ? `${current} / ${expected}` : String(current);
}
function appendStatusTag(container, label, className = "") {
if (!container || !label) return;
const tag = document.createElement("span");
tag.className = `status-tag${className ? ` ${className}` : ""}`;
tag.textContent = label;
container.appendChild(tag);
}
function categoryOptions(selected) {
return Object.entries(categoryLabels)
.map(([value, label]) => `<option value="${value}"${value === selected ? " selected" : ""}>${label}</option>`)
.join("");
}
function renderSummary(summary) {
const totals = summary || { shows: 0, sub: 0, dub: 0 };
const cards = $("watchlist-summary").querySelectorAll(".summary-card");
cards[0].querySelector(".summary-value").textContent = String(totals.shows);
cards[1].querySelector(".summary-value").textContent = String(totals.sub);
cards[2].querySelector(".summary-value").textContent = String(totals.dub);
$("watchlist-meta").textContent = totals.shows
? `${state.watchlistTotal} shows in ${categoryLabels[state.watchlistCategory]} · ${totals.shows} tracked total.`
: "Track shows and sort them into watching, planned, finished, or dropped.";
}
function renderCategoryTabs(categories = {}) {
const container = $("watchlistTabs");
if (!container) return;
container.innerHTML = "";
for (const [value, label] of Object.entries(categoryLabels)) {
const button = document.createElement("button");
button.type = "button";
button.className = `category-tab${state.watchlistCategory === value ? " active" : ""}`;
button.textContent = `${label} (${Number(categories[value] || 0)})`;
button.addEventListener("click", () => {
if (state.watchlistCategory === value) return;
state.watchlistCategory = value;
fetchWatchlist(1);
});
container.appendChild(button);
}
}
function renderPager() {
const pager = $("watchlistPager");
const start = state.watchlistTotal ? ((state.watchlistPage - 1) * state.watchlistPerPage) + 1 : 0;
const end = Math.min(state.watchlistPage * state.watchlistPerPage, state.watchlistTotal);
pager.innerHTML = `
<span class="muted"></span>
<div class="pager-controls"></div>
`;
pager.querySelector(".muted").textContent =
`${start}-${end} of ${state.watchlistTotal} · page ${state.watchlistPage} of ${state.watchlistPages}`;
const controls = pager.querySelector(".pager-controls");
const prev = document.createElement("button");
prev.type = "button";
prev.className = "ghost";
prev.textContent = "Previous";
prev.disabled = state.watchlistPage <= 1;
prev.addEventListener("click", () => fetchWatchlist(state.watchlistPage - 1));
const next = document.createElement("button");
next.type = "button";
next.className = "ghost";
next.textContent = "Next";
next.disabled = state.watchlistPage >= state.watchlistPages;
next.addEventListener("click", () => fetchWatchlist(state.watchlistPage + 1));
controls.append(prev, next);
}
function applyThumbnail(card, item, force = false) {
const tile = card.querySelector(".cover-tile");
const img = card.querySelector("img");
const uploadButton = card.querySelector(".thumb-upload-btn");
const showImage = () => {
img.style.display = "block";
tile.classList.add("has-image");
if (uploadButton) uploadButton.style.display = "none";
};
const hideImage = () => {
img.style.display = "none";
tile.classList.remove("has-image");
if (uploadButton) uploadButton.style.display = "inline-flex";
};
card.title = item.thumbnail_debug || "Thumbnail source: unresolved";
tile.title = item.thumbnail_debug || "Thumbnail source: unresolved";
img.alt = `${item.title} cover`;
hideImage();
if (!item.thumbnail_ready) {
img.removeAttribute("src");
return;
}
const src = `${item.thumbnail_url}?v=${encodeURIComponent(item.thumbnail_checked_at || "")}&n=${state.thumbnailNonce}${force ? `&t=${Date.now()}` : ""}`;
img.dataset.retry = force ? "1" : "0";
img.onload = showImage;
img.onerror = hideImage;
if (img.src !== src) {
img.src = src;
}
if (img.complete) {
if (img.naturalWidth > 0) {
showImage();
} else {
hideImage();
}
}
}
function setThumbnailReloading(card, reloading) {
const button = card.querySelector(".thumb-reload-btn");
if (!button) return;
button.disabled = !!reloading;
button.textContent = reloading ? "..." : "Reload";
}
function setThumbnailUploading(card, uploading) {
const button = card.querySelector(".thumb-upload-btn");
if (!button) return;
button.disabled = !!uploading;
button.textContent = uploading ? "..." : "Upload";
}
function findCardByShowId(showId) {
return Array.from(document.querySelectorAll(".anime-card"))
.find((card) => card.dataset.showId === showId) || null;
}
function thumbnailWarmupToken(item) {
return [
item.thumbnail_ready ? "1" : "0",
item.thumbnail_checked_at || "",
item.animeschedule_route || "",
item.anidb_aid || "",
item.thumbnail_path || ""
].join("|");
}
async function hydrateThumbnailsOnce(items) {
const missing = [];
for (const item of items) {
const token = thumbnailWarmupToken(item);
if (item.thumbnail_ready) {
state.thumbnailWarmupPending.delete(item.show_id);
state.thumbnailWarmupTokens[item.show_id] = token;
continue;
}
if (state.thumbnailWarmupPending.has(item.show_id)) continue;
if (state.thumbnailWarmupTokens[item.show_id] === token) continue;
state.thumbnailWarmupPending.add(item.show_id);
state.thumbnailWarmupTokens[item.show_id] = token;
missing.push(item.show_id);
if (missing.length >= 8) break;
}
if (!missing.length) return;
try {
const data = await api("/api/watchlist/ensure-thumbnails", {
method: "POST",
body: JSON.stringify({ show_ids: missing, limit: 8, force: false })
});
for (const item of data.items || []) {
state.thumbnailWarmupTokens[item.show_id] = thumbnailWarmupToken(item);
const card = findCardByShowId(item.show_id);
if (!card) continue;
applyThumbnail(card, item, true);
}
} catch (_error) {
} finally {
for (const showId of missing) {
state.thumbnailWarmupPending.delete(showId);
}
}
}
async function reloadWatchlistThumbnail(showId, title) {
const card = findCardByShowId(showId);
if (card) setThumbnailReloading(card, true);
setNotice(`Reloading thumbnail for ${title || "selected anime"}...`);
try {
const data = await api("/api/watchlist/ensure-thumbnails", {
method: "POST",
body: JSON.stringify({ show_ids: [showId], limit: 1, force: true })
});
const item = (data.items || [])[0];
if (card && item) {
state.thumbnailWarmupPending.delete(item.show_id);
state.thumbnailWarmupTokens[item.show_id] = thumbnailWarmupToken(item);
applyThumbnail(card, item, true);
}
if (item && item.thumbnail_ready) {
setNotice(`Redownloaded thumbnail for ${item.title || title || "selected anime"}.`);
} else {
setNotice(`Could not redownload thumbnail for ${title || "selected anime"}.`);
}
} catch (error) {
setNotice(error.message);
} finally {
if (card) setThumbnailReloading(card, false);
}
}
function readFileAsDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result || ""));
reader.onerror = () => reject(new Error("Could not read the selected image file."));
reader.readAsDataURL(file);
});
}
async function uploadWatchlistThumbnail(showId, title, file) {
if (!file) return;
if (!String(file.type || "").startsWith("image/")) {
setNotice("Choose an image file for the thumbnail.");
return;
}
if (file.size > 8 * 1024 * 1024) {
setNotice("Thumbnail image is too large. Keep it under 8 MB.");
return;
}
const card = findCardByShowId(showId);
if (card) setThumbnailUploading(card, true);
setNotice(`Uploading thumbnail for ${title || "selected anime"}...`);
try {
const dataUrl = await readFileAsDataUrl(file);
const data = await api("/api/watchlist/upload-thumbnail", {
method: "POST",
body: JSON.stringify({ show_id: showId, filename: file.name, data_url: dataUrl })
});
if (card && data.item) {
state.thumbnailWarmupPending.delete(data.item.show_id);
state.thumbnailWarmupTokens[data.item.show_id] = thumbnailWarmupToken(data.item);
applyThumbnail(card, data.item, true);
}
setNotice(data.message || `Uploaded thumbnail for ${title || "selected anime"}.`);
} catch (error) {
setNotice(error.message);
} finally {
if (card) setThumbnailUploading(card, false);
}
}
function renderWatchlist(data) {
const items = data.items || [];
state.watchlistPage = data.page || 1;
state.watchlistPages = data.pages || 1;
state.watchlistTotal = data.total || 0;
state.watchlistPerPage = data.per_page || 30;
state.queuedCount = Number(data.queued_count || 0);
state.watchlistCategory = data.active_category || state.watchlistCategory;
const container = $("watchlist-container");
container.innerHTML = "";
renderSummary(data.summary);
renderCategoryTabs(data.categories || {});
if (!items.length) {
container.innerHTML = `<div class="empty">No anime in ${categoryLabels[state.watchlistCategory]}. Add one here or move entries between tabs.</div>`;
renderPager();
return;
}
for (const item of items) {
const card = document.createElement("article");
const checked = item.last_checked ? new Date(item.last_checked).toLocaleString() : "Never";
card.className = watchlistCardClassName(item);
card.dataset.showId = item.show_id;
card.title = item.thumbnail_debug || "Thumbnail source: unresolved";
card.innerHTML = `
<div class="cover-tile">
<img alt="">
<div class="cover-fallback"></div>
<button class="thumb-reload-btn" type="button" title="Redownload thumbnail">Reload</button>
<button class="thumb-upload-btn" type="button" title="Upload thumbnail">Upload</button>
<input class="thumb-upload-input" type="file" accept="image/*" hidden>
</div>
<div class="title-row">
<div class="card-title"></div>
<span class="finish-check ${item.finished_badge || ""}" ${item.finished_badge ? "" : "hidden"}>${item.finished_badge ? "&check;" : ""}</span>
</div>
<div class="count-row">
<span class="count-pill${item.sub_complete ? " complete" : ""}">Sub <strong>${formatModeProgress(item.sub_count, item.expected_count)}</strong></span>
<span class="count-pill${item.dub_complete ? " complete" : ""}">Dub <strong>${formatModeProgress(item.dub_count, item.expected_count)}</strong></span>
</div>
<div class="status-row"></div>
<div class="category-editor">
<label>Category
<select class="category-select">${categoryOptions(item.category)}</select>
</label>
</div>
<div class="muted card-date"></div>
<div class="card-actions">
<button class="primary" type="button">Refresh</button>
<button class="ghost" type="button">Download all</button>
<button class="danger" type="button">Remove</button>
</div>
`;
card.querySelector(".cover-fallback").textContent = coverInitials(item.title);
const titleNode = card.querySelector(".card-title");
const titleLink = document.createElement("a");
titleLink.href = item.source_url || `/?query=${encodeURIComponent(item.title || item.show_id)}`;
titleLink.target = "_blank";
titleLink.rel = "noopener noreferrer";
titleLink.textContent = item.title;
titleNode.replaceChildren(titleLink);
const finishCheck = card.querySelector(".finish-check");
if (finishCheck && item.finished_badge) {
finishCheck.title = item.finished_badge === "downloaded"
? "Finished and downloaded"
: "Finished, but not marked as downloaded";
}
const statusRow = card.querySelector(".status-row");
appendStatusTag(statusRow, item.category_label || categoryLabels[item.category] || "Watching");
if (item.airing_status) {
appendStatusTag(statusRow, item.airing_status);
}
if (item.sub_complete) {
appendStatusTag(statusRow, "Sub ready", "complete");
}
if (item.dub_complete) {
appendStatusTag(statusRow, "Dub ready", "complete");
}
card.querySelector(".card-date").textContent = item.status_message
? `Last checked: ${checked}\n${item.status_message}`
: `Last checked: ${checked}`;
card.querySelector(".thumb-reload-btn").addEventListener("click", () => reloadWatchlistThumbnail(item.show_id, item.title));
const uploadButton = card.querySelector(".thumb-upload-btn");
const uploadInput = card.querySelector(".thumb-upload-input");
uploadButton.addEventListener("click", () => uploadInput.click());
uploadInput.addEventListener("change", () => {
const [file] = Array.from(uploadInput.files || []);
uploadWatchlistThumbnail(item.show_id, item.title, file).finally(() => {
uploadInput.value = "";
});
});
const actionButtons = card.querySelector(".card-actions").querySelectorAll("button");
const refreshBtn = actionButtons[0];
const searchBtn = actionButtons[1];
const removeBtn = actionButtons[2];
const categorySelect = card.querySelector(".category-select");
categorySelect.addEventListener("change", async () => {
categorySelect.disabled = true;
try {
const data = await api("/api/watchlist/update-category", {
method: "POST",
body: JSON.stringify({ show_id: item.show_id, category: categorySelect.value })
});
setNotice(data.message || "Watchlist category updated.");
await fetchWatchlist(state.watchlistPage);
} catch (error) {
setNotice(error.message);
categorySelect.value = item.category;
} finally {
categorySelect.disabled = false;
}
});
refreshBtn.addEventListener("click", () => refreshWatchlistItem(item.show_id));
searchBtn.addEventListener("click", () => downloadWatchlistItem(item));
removeBtn.addEventListener("click", () => removeWatchlistItem(item.show_id, item.title));
container.appendChild(card);
applyThumbnail(card, item, false);
}
renderPager();
window.setTimeout(() => hydrateThumbnailsOnce(items), 150);
}
async function fetchWatchlist(page = state.watchlistPage || 1, options = {}) {
const requestId = ++state.watchlistRequestId;
const silent = !!options.silent;
if (!silent) {
setNotice("Loading watchlist...");
}
try {
const data = await api(`/api/watchlist?page=${page}&per_page=30&category=${encodeURIComponent(state.watchlistCategory)}`);
if (requestId !== state.watchlistRequestId) return data;
if (data.page > data.pages && data.pages > 0) {
return fetchWatchlist(data.pages, options);
}
renderWatchlist(data);
if (!silent) {
setNotice("");
}
return data;
} catch (error) {
if (requestId !== state.watchlistRequestId) return null;
if (!silent) {
setNotice(error.message);
}
throw error;
}
}
async function pollRefreshStatus(refreshOnComplete = true) {
try {
const data = await api("/api/watchlist/refresh-status");
const job = data.job || null;
const running = !!data.running && !!job;
const wasRunning = state.refreshRunning;
state.refreshRunning = running;
state.refreshJobId = job ? job.id : null;
setRefreshAllButton(running);
setRefreshJobStatus(job);
if (running) {
setNotice(job.message || "Refreshing all watchlist entries...");
} else if (job && wasRunning && refreshOnComplete) {
const message = job.message || "Watchlist refreshed.";
await fetchWatchlist();
setNotice(message);
}
} catch (error) {
setNotice(error.message);
}
}
async function addAnimeToWatchlist() {
const showId = $("watchlist-show-id").value.trim();
const title = $("watchlist-title").value.trim();
if (!showId || !title) {
setNotice("Fill in the watchlist title and show ID.");
return;
}
try {
const data = await api("/api/watchlist", {
method: "POST",
body: JSON.stringify({
show_id: showId,
title,
category: $("watchlist-category").value
})
});
$("watchlist-form").reset();
$("watchlist-category").value = "watching";
setNotice(data.message || "Added to watchlist.");
await fetchWatchlist();
} catch (error) {
setNotice(error.message);
}
}
async function refreshWatchlistItem(showId) {
try {
const data = await api("/api/watchlist/update-status", {
method: "POST",
body: JSON.stringify({ show_id: showId })
});
setNotice(data.message || "Watchlist refresh queued.");
await fetchWatchlist();
} catch (error) {
setNotice(error.message);
}
}
function chooseWatchlistDownloadMode(item) {
const fallback = item.dub_count > 0 && item.sub_count < 1 ? "dub" : "sub";
const answer = window.prompt(
`Download all available episodes for ${item.title || "this anime"}.\nEnter sub or dub:`,
fallback,
);
if (answer === null) return "";
const mode = String(answer || "").trim().toLowerCase();
if (mode === "sub" || mode === "dub") {
return mode;
}
setNotice("Enter sub or dub to queue a watchlist download.");
return "";
}
async function downloadWatchlistItem(item) {
const mode = chooseWatchlistDownloadMode(item);
if (!mode) return;
setNotice(`Queueing ${item.title || "selected anime"} for ${mode} download...`);
try {
const data = await api("/api/watchlist/download-all", {
method: "POST",
body: JSON.stringify({ show_id: item.show_id, mode })
});
setNotice(data.message || "Added to queue.");
} catch (error) {
setNotice(error.message);
}
}
async function removeWatchlistItem(showId, title) {
if (!window.confirm(`Remove ${title || "this anime"} from the watchlist?`)) {
return;
}
try {
const data = await api("/api/watchlist/remove", {
method: "POST",
body: JSON.stringify({ show_id: showId })
});
state.thumbnailWarmupPending.delete(showId);
delete state.thumbnailWarmupTokens[showId];
setNotice(data.message || "Removed from watchlist.");
await fetchWatchlist(state.watchlistPage);
} catch (error) {
setNotice(error.message);
}
}
async function refreshAllWatchlist() {
try {
const data = await api("/api/watchlist/update-all", {
method: "POST",
body: "{}"
});
setNotice(data.message || "Watchlist refresh started.");
await pollRefreshStatus(false);
} catch (error) {
setNotice(error.message);
}
}
$("refreshAllWatchlistBtn").addEventListener("click", refreshAllWatchlist);
(async function init() {
try {
await fetchWatchlist();
await pollRefreshStatus(false);
startSerialPoll(async () => {
if (state.refreshRunning) {
await pollRefreshStatus(true);
} else if (state.queuedCount > 0) {
await fetchWatchlist(state.watchlistPage, { silent: true }).catch(() => {});
}
}, 2500);
} catch (error) {
setNotice(error.message);
}
})();
</script>
</body>
</html>
"""