Files
ani-cli-web/web_templates.py
T

2123 lines
65 KiB
Python

#!/usr/bin/env python3
"""Shared inline page templates for ani-cli-web."""
PAGE_LINKS = (
("search", "Search", "/"),
("config", "Config", "/config"),
("watchlist", "Watchlist", "/watchlist"),
)
def render_sidebar_brand(note, badge, badge_id=""):
badge_attr = f' id="{badge_id}"' if badge_id else ""
return (
' <div class="topline">\n'
' <div class="brand-wrap">\n'
' <h1>ani-cli <span class="brand-word">web</span></h1>\n'
f" <p class=\"shell-note\">{note}</p>\n"
" </div>\n"
f" <span class=\"badge\"{badge_attr}>{badge}</span>\n"
" </div>\n"
)
def render_page_links(active_page):
links = []
for key, label, href in PAGE_LINKS:
class_name = "page-link active" if key == active_page else "page-link"
links.append(f' <a class="{class_name}" href="{href}">{label}</a>')
return " <div class=\"page-links\">\n" + "\n".join(links) + "\n </div>\n"
INDEX_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</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;
--warn: #f0c67a;
--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;
}
button.danger {
border-color: rgba(255, 144, 164, 0.3);
background: rgba(255, 144, 164, 0.12);
color: #ffd7df;
}
button.danger:hover {
border-color: rgba(255, 144, 164, 0.48);
background: rgba(255, 144, 164, 0.18);
}
button.danger {
border-color: rgba(255, 144, 164, 0.28);
color: #ffd7df;
}
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, 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;
grid-template-rows: auto auto 1fr;
gap: 20px;
min-width: 0;
}
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; }
.topline, .row, .controls, .toolbar {
display: flex;
gap: 10px;
align-items: center;
}
.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;
}
.row > * { flex: 1; }
.controls {
align-items: end;
}
.search-box {
display: grid;
gap: 12px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 22px;
background: linear-gradient(180deg, rgba(31, 24, 50, 0.86), rgba(17, 13, 29, 0.92));
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.page-links {
display: flex;
gap: 8px;
flex-wrap: wrap;
padding: 6px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255, 255, 255, 0.03);
}
.page-link {
display: inline-flex;
align-items: center;
justify-content: center;
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);
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
border: 1px solid var(--line);
border-radius: 16px;
overflow: hidden;
background: rgba(255, 255, 255, 0.03);
}
.segmented button {
border: 0;
border-radius: 0;
background: transparent;
}
.segmented button.active {
background: var(--accent-soft);
color: var(--text);
font-weight: 700;
}
.results, .queue {
display: grid;
gap: 10px;
min-width: 0;
}
.result, .job, .settings, .episodes-panel, .deps {
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);
}
.result {
padding: 14px;
display: grid;
gap: 6px;
text-align: left;
transition: transform 0.16s ease, border-color 0.16s ease, background 0.16s ease;
}
.result:hover {
border-color: var(--line-strong);
transform: translateY(-1px);
}
.result.active {
border-color: rgba(157, 123, 255, 0.34);
background: linear-gradient(180deg, rgba(48, 36, 80, 0.96), rgba(20, 15, 35, 0.96));
}
.result-title {
color: var(--text);
font-weight: 700;
overflow-wrap: anywhere;
}
.muted {
color: var(--muted);
font-size: 13px;
}
.settings, .episodes-panel, .deps {
padding: 18px;
display: grid;
gap: 14px;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
max-height: 168px;
overflow: auto;
}
.chip, .badge {
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
padding: 6px 10px;
color: var(--muted);
background: rgba(255, 255, 255, 0.04);
font-size: 12px;
white-space: nowrap;
}
.badge.ok { color: var(--good); border-color: rgba(149, 228, 186, 0.24); }
.badge.bad { color: #ffd0da; border-color: rgba(255, 144, 164, 0.22); }
.job {
padding: 18px;
display: grid;
gap: 14px;
transition: border-color 0.16s ease, transform 0.16s ease;
}
.job:hover {
border-color: var(--line-strong);
transform: translateY(-1px);
}
.job-head {
display: grid;
grid-template-columns: 1fr auto;
gap: 12px;
align-items: start;
min-width: 0;
}
.job-title {
font-weight: 800;
overflow-wrap: anywhere;
}
.status {
border-radius: 999px;
padding: 6px 10px;
font-size: 12px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.04em;
background: rgba(255, 255, 255, 0.06);
color: var(--muted);
}
.status.running {
color: #fcfaff;
background: linear-gradient(135deg, var(--accent), var(--accent-strong));
}
.status.done { color: #082312; background: var(--good); }
.status.failed { color: #2d0910; background: var(--bad); }
.status.canceled { color: #2d1c00; background: var(--warn); }
pre {
margin: 0;
max-height: 180px;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
padding: 12px;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.05);
background: rgba(7, 5, 12, 0.86);
color: #d6d0e7;
font-size: 12px;
}
.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);
}
.notice {
min-height: 20px;
color: #ddd0ff;
font-size: 13px;
}
.statline {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
@media (max-width: 900px) {
.app { grid-template-columns: 1fr; }
aside { border-right: 0; border-bottom: 1px solid var(--line); }
.controls, .row, .toolbar { align-items: stretch; flex-direction: column; }
.job-head { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="app">
<aside>
""" + render_sidebar_brand(
"Tsuki-inspired control center for anime search and download flow.",
"Search",
badge_id="serverBadge",
) + render_page_links("search") + r"""
<div class="search-box">
<label for="search-query">Anime Title / Keyword</label>
<input type="text" id="search-query" placeholder="e.g., Attack on Titan">
<label for="search-mode">Mode</label>
<select id="search-mode">
<option value="sub">Subtitled (Sub)</option>
<option value="dub">Dubbed (Dub)</option>
</select>
<label for="search-quality">Quality</label>
<select id="search-quality">
<option value="best">Best</option>
<option value="1080">1080p</option>
<option value="720">720p</option>
<option value="480">480p</option>
</select>
<button class="primary" id="searchBtn" type="button">Search</button>
</div>
<div class="notice" id="notice"></div>
<div class="results" id="results"></div>
</aside>
<main>
<section class="episodes-panel" id="episodesPanel">
<div class="toolbar">
<div>
<h2 id="selectedTitle">Select a result</h2>
<p class="muted" id="selectedMeta">Episodes will appear here.</p>
</div>
<div class="row" style="flex:0 0 auto">
<button class="ghost" id="trackBtn" type="button" disabled>Add to watchlist</button>
<button class="primary" id="addBtn" type="button" disabled>Add to queue</button>
</div>
</div>
<div class="row">
<label>Library name
<input id="animeNameInput" placeholder="Anime name">
</label>
<label>Season
<input id="seasonInput" inputmode="numeric" pattern="[0-9]*" value="1">
</label>
</div>
<div class="row">
<label>Episodes
<input id="episodesInput" placeholder="1-12">
</label>
<label>Download folder
<input id="jobFolder" placeholder="/home/me/Downloads/Anime">
</label>
</div>
<div class="toolbar">
<div class="chips" id="episodeChips"></div>
<div class="row" style="flex:0 0 auto">
<button class="ghost" id="firstEpBtn" type="button">First</button>
<button class="ghost" id="latestEpBtn" type="button">Latest</button>
<button class="ghost" id="allEpBtn" type="button">All</button>
</div>
</div>
</section>
<section>
<div class="toolbar">
<h2>Download queue</h2>
<div class="row" style="flex:0 0 auto">
<button class="ghost" id="retryFailedBtn" type="button">Retry failed</button>
<button class="ghost" id="removeFinishedBtn" type="button">Remove finished</button>
</div>
</div>
<div class="queue" id="queue"></div>
<div class="toolbar" id="queuePager"></div>
</section>
</main>
</div>
<script>
const state = {
config: { mode: "sub", quality: "best", download_dir: "" },
selected: null,
episodes: [],
queuePage: 1,
queuePages: 1,
queueTotal: 0,
queueTimer: null
};
const $ = (id) => document.getElementById(id);
async function api(path, options = {}) {
const response = await fetch(path, {
headers: { "Content-Type": "application/json" },
...options
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || "Request failed");
return data;
}
function setNotice(text) {
const notice = $("notice");
if (notice) notice.textContent = text || "";
}
function setMode(mode) {
state.config.mode = mode;
$("search-mode").value = mode;
}
function renderResults(results) {
const el = $("results");
el.innerHTML = "";
if (!results.length) {
el.innerHTML = '<div class="empty">No matching anime found.</div>';
return;
}
for (const item of results) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "result";
btn.innerHTML = `
<span class="result-title"></span>
<span class="muted"></span>
`;
btn.querySelector(".result-title").textContent = item.title;
btn.querySelector(".muted").textContent = `${item.episodes} episodes · result ${item.index}`;
btn.addEventListener("click", () => selectResult(item, btn));
el.appendChild(btn);
}
}
async function selectResult(item, button) {
document.querySelectorAll(".result").forEach((node) => node.classList.remove("active"));
button.classList.add("active");
state.selected = item;
state.episodes = [];
$("selectedTitle").textContent = item.title;
$("animeNameInput").value = item.title;
$("seasonInput").value = $("seasonInput").value || "1";
$("selectedMeta").textContent = "Loading episodes...";
$("episodeChips").innerHTML = "";
$("addBtn").disabled = true;
$("trackBtn").disabled = false;
try {
const data = await api(`/api/anime/${encodeURIComponent(item.id)}/episodes?mode=${state.config.mode}`);
state.episodes = data.episodes;
const first = state.episodes[0] || "";
const last = state.episodes[state.episodes.length - 1] || "";
$("episodesInput").value = first && last ? `${first}-${last}` : "";
$("selectedMeta").textContent = `${state.episodes.length} available episodes`;
renderEpisodeChips();
$("addBtn").disabled = !state.episodes.length;
} catch (error) {
$("selectedMeta").textContent = error.message;
}
}
function renderEpisodeChips() {
const el = $("episodeChips");
el.innerHTML = "";
for (const ep of state.episodes.slice(0, 90)) {
const chip = document.createElement("button");
chip.type = "button";
chip.className = "chip";
chip.textContent = ep;
chip.addEventListener("click", () => { $("episodesInput").value = ep; });
el.appendChild(chip);
}
}
async function search() {
const query = $("search-query").value.trim();
if (!query) return setNotice("Type a title first.");
setMode($("search-mode").value);
setNotice("Searching...");
state.selected = null;
$("addBtn").disabled = true;
$("trackBtn").disabled = true;
$("results").innerHTML = "";
try {
const data = await api(`/api/search?q=${encodeURIComponent(query)}&mode=${state.config.mode}`);
renderResults(data.results);
setNotice(`${data.results.length} results`);
} catch (error) {
setNotice(error.message);
}
}
async function addSelectedToWatchlist() {
if (!state.selected) {
setNotice("Select a search result first.");
return;
}
try {
const data = await api("/api/watchlist", {
method: "POST",
body: JSON.stringify({ show_id: state.selected.id, title: state.selected.title })
});
setNotice(data.message || "Added to watchlist.");
} catch (error) {
setNotice(error.message);
}
}
async function addSelected() {
if (!state.selected) return;
const payload = {
query: state.selected.query,
title: state.selected.title,
anime_name: $("animeNameInput").value || state.selected.title,
season: $("seasonInput").value || "1",
index: state.selected.index,
mode: state.config.mode,
quality: $("search-quality").value,
episodes: $("episodesInput").value,
download_dir: $("jobFolder").value || state.config.download_dir
};
try {
await api("/api/queue", { method: "POST", body: JSON.stringify(payload) });
setNotice("Added to queue.");
await loadQueue();
} catch (error) {
setNotice(error.message);
}
}
function renderQueue(data) {
const jobs = data.jobs || [];
state.queuePage = data.page || 1;
state.queuePages = data.pages || 1;
state.queueTotal = data.total || 0;
const el = $("queue");
el.innerHTML = "";
if (!jobs.length) {
el.innerHTML = '<div class="empty">Queue is empty.</div>';
renderQueuePager();
return;
}
for (const job of jobs) {
const item = document.createElement("article");
item.className = "job";
const log = (job.log || []).slice(-28).join("\n");
item.innerHTML = `
<div class="job-head">
<div>
<div class="job-title"></div>
<p class="muted"></p>
</div>
<span class="status"></span>
</div>
<pre></pre>
<div class="toolbar">
<span class="muted"></span>
<div class="row" style="flex:0 0 auto"></div>
</div>
`;
item.querySelector(".job-title").textContent = job.title;
const libraryName = job.anime_name || job.title;
const season = String(job.season || "1").padStart(2, "0");
const seasonFolder = `Season ${season}`;
const target = job.target_dir || `${job.download_dir}/${libraryName}/${seasonFolder}`;
item.querySelector(".job-head .muted").textContent =
`${libraryName} · S${season} · ${job.mode} · ${job.quality} · episodes ${job.episodes} · ${target}`;
const status = item.querySelector(".status");
status.textContent = job.status;
status.classList.add(job.status);
item.querySelector("pre").textContent = log || "Waiting...";
item.querySelector(".toolbar .muted").textContent = job.exit_code === null ? "" : `exit ${job.exit_code}`;
const actions = item.querySelector(".row");
if (job.status === "running") {
actions.append(actionButton("Cancel", () => queueAction(job.id, "cancel"), "danger"));
} else if (job.status === "pending") {
actions.append(actionButton("Cancel", () => queueAction(job.id, "cancel"), "danger"));
} else {
actions.append(actionButton("Retry", () => queueAction(job.id, "retry")));
actions.append(actionButton("Remove", () => queueAction(job.id, "remove")));
}
el.appendChild(item);
}
renderQueuePager();
}
function renderQueuePager() {
const el = $("queuePager");
const start = state.queueTotal ? ((state.queuePage - 1) * 10) + 1 : 0;
const end = Math.min(state.queuePage * 10, state.queueTotal);
el.innerHTML = `
<span class="muted"></span>
<div class="row" style="flex:0 0 auto"></div>
`;
el.querySelector(".muted").textContent =
`${start}-${end} of ${state.queueTotal} · page ${state.queuePage} of ${state.queuePages}`;
const controls = el.querySelector(".row");
const prev = actionButton("Previous", () => {
if (state.queuePage > 1) loadQueue(state.queuePage - 1);
});
const next = actionButton("Next", () => {
if (state.queuePage < state.queuePages) loadQueue(state.queuePage + 1);
});
prev.disabled = state.queuePage <= 1;
next.disabled = state.queuePage >= state.queuePages;
controls.append(prev, next);
}
function actionButton(text, handler, extra = "") {
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = text;
btn.className = extra;
btn.addEventListener("click", handler);
return btn;
}
async function queueAction(id, action) {
try {
await api(`/api/queue/${id}/${action}`, { method: "POST", body: "{}" });
await loadQueue(state.queuePage);
} catch (error) {
setNotice(error.message);
}
}
async function queueBulkAction(path, message) {
try {
const data = await api(path, { method: "POST", body: "{}" });
setNotice(`${message}: ${data.count || 0}`);
await loadQueue(state.queuePage);
} catch (error) {
setNotice(error.message);
}
}
async function loadQueue(page = state.queuePage || 1) {
const data = await api(`/api/queue?page=${page}&per_page=10`);
if (data.page > data.pages && data.pages > 0) return loadQueue(data.pages);
renderQueue(data);
}
async function loadConfig() {
state.config = await api("/api/config");
$("jobFolder").value = state.config.download_dir;
$("search-quality").value = state.config.quality;
setMode(state.config.mode);
}
$("searchBtn").addEventListener("click", search);
$("search-query").addEventListener("keydown", (event) => {
if (event.key === "Enter") search();
});
$("search-mode").addEventListener("change", (event) => setMode(event.target.value));
$("trackBtn").addEventListener("click", addSelectedToWatchlist);
$("addBtn").addEventListener("click", addSelected);
$("removeFinishedBtn").addEventListener("click", () => queueBulkAction("/api/queue/clear-finished", "Removed finished jobs"));
$("retryFailedBtn").addEventListener("click", () => queueBulkAction("/api/queue/retry-failed", "Retried failed jobs"));
$("search-quality").addEventListener("change", () => { state.config.quality = $("search-quality").value; });
$("firstEpBtn").addEventListener("click", () => { $("episodesInput").value = state.episodes[0] || ""; });
$("latestEpBtn").addEventListener("click", () => {
$("episodesInput").value = state.episodes[state.episodes.length - 1] || "";
});
$("allEpBtn").addEventListener("click", () => {
const first = state.episodes[0] || "";
const last = state.episodes[state.episodes.length - 1] || "";
$("episodesInput").value = first && last ? `${first}-${last}` : "";
});
(async function init() {
try {
const params = new URLSearchParams(window.location.search);
const query = (params.get("query") || "").trim();
if (query) $("search-query").value = query;
await loadConfig();
await loadQueue();
if (query) await search();
state.queueTimer = setInterval(loadQueue, 2500);
} catch (error) {
setNotice(error.message);
}
})();
</script>
</body>
</html>
"""
CONFIG_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 - config</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);
--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);
}
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, 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;
align-content: start;
justify-items: start;
}
h1, h2, p { margin: 0; }
h1 {
font-size: 29px;
line-height: 1.05;
letter-spacing: -0.04em;
}
h2 {
font-size: 17px;
letter-spacing: -0.02em;
}
.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;
}
.row > * { flex: 1; }
.page-links {
display: flex;
gap: 8px;
flex-wrap: wrap;
padding: 6px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255, 255, 255, 0.03);
}
.page-link {
display: inline-flex;
align-items: center;
justify-content: center;
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);
}
.settings, .deps {
border: 1px solid var(--line);
border-radius: 22px;
background: linear-gradient(180deg, rgba(29, 22, 47, 0.88), rgba(17, 13, 29, 0.94));
padding: 18px;
display: grid;
gap: 14px;
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.muted {
color: var(--muted);
font-size: 13px;
}
.notice {
min-height: 20px;
color: #ddd0ff;
font-size: 13px;
}
.stack {
display: grid;
gap: 10px;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.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;
}
.badge.ok { color: #95e4ba; border-color: rgba(149, 228, 186, 0.24); }
.badge.bad { color: #ffd0da; border-color: rgba(255, 144, 164, 0.22); }
.field-hint {
color: var(--muted);
font-size: 12px;
}
.form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.settings-main, .deps {
width: min(760px, 100%);
}
@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; }
}
@media (max-width: 640px) {
.form-grid {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="app">
<aside>
""" + render_sidebar_brand(
"Tsuki-inspired settings view for saved defaults and runtime checks.",
"Config",
) + render_page_links("config") + r"""
<section class="settings">
<h2>Saved defaults</h2>
<div class="stack muted">
<p>These values preload the Search page and act as the fallback folder for new queue jobs.</p>
<p>Mode and quality can still be changed on the Search page before queueing a download.</p>
</div>
</section>
<section class="settings">
<h2>Runtime info</h2>
<div class="stack muted">
<p id="versionLine">Loading version...</p>
<p>Saved settings live in `.ani-cli-web/config.json` inside this project.</p>
</div>
</section>
</aside>
<main>
<section class="settings settings-main">
<div class="toolbar">
<div>
<h2>Defaults</h2>
<p class="muted">Manage the folder, mode, and quality that the Search page starts with.</p>
</div>
<button class="primary" id="saveConfigBtn" type="button">Save</button>
</div>
<div class="notice" id="notice"></div>
<div class="stack">
<label>Default folder
<input id="downloadDir" placeholder="/home/me/Downloads/Anime">
</label>
</div>
<div class="form-grid">
<label>Default mode
<select id="configMode">
<option value="sub">Subtitled (Sub)</option>
<option value="dub">Dubbed (Dub)</option>
</select>
</label>
<label>Default quality
<select id="configQuality">
<option value="best">Best</option>
<option value="1080">1080p</option>
<option value="720">720p</option>
<option value="480">480p</option>
</select>
</label>
</div>
<div class="field-hint">Tip: these are the saved defaults only. The active search form can still be adjusted per download.</div>
</section>
<section class="deps" id="deps"></section>
</main>
</div>
<script>
const state = {
config: { mode: "sub", quality: "best", download_dir: "" }
};
const $ = (id) => document.getElementById(id);
async function api(path, options = {}) {
const response = await fetch(path, {
headers: { "Content-Type": "application/json" },
...options
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || "Request failed");
return data;
}
function setNotice(text) {
$("notice").textContent = text || "";
}
async function loadConfig() {
state.config = await api("/api/config");
$("downloadDir").value = state.config.download_dir;
$("configMode").value = state.config.mode;
$("configQuality").value = state.config.quality;
}
async function saveConfig() {
try {
const data = await api("/api/config", {
method: "POST",
body: JSON.stringify({
download_dir: $("downloadDir").value,
mode: $("configMode").value,
quality: $("configQuality").value
})
});
state.config = data;
$("downloadDir").value = data.download_dir;
$("configMode").value = data.mode;
$("configQuality").value = data.quality;
setNotice("Defaults saved.");
} catch (error) {
setNotice(error.message);
}
}
async function loadDeps() {
const data = await api("/api/dependencies");
const el = $("deps");
el.innerHTML = "<h2>Dependencies</h2>";
const wrap = document.createElement("div");
wrap.className = "chips";
for (const [name, ok] of Object.entries(data)) {
const span = document.createElement("span");
span.className = `badge ${ok ? "ok" : "bad"}`;
span.textContent = `${name} ${ok ? "ok" : "missing"}`;
wrap.appendChild(span);
}
el.appendChild(wrap);
}
async function loadVersion() {
const data = await api("/api/version");
$("versionLine").textContent = `${data.name} ${data.version}`;
}
$("saveConfigBtn").addEventListener("click", saveConfig);
(async function init() {
try {
await loadConfig();
await loadDeps();
await loadVersion();
} catch (error) {
setNotice(error.message);
}
})();
</script>
</body>
</html>
"""
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);
--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 {
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 {
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);
}
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: flex;
gap: 8px;
flex-wrap: wrap;
padding: 6px;
border: 1px solid var(--line);
border-radius: 18px;
background: rgba(255, 255, 255, 0.03);
}
.page-link {
display: inline-flex;
align-items: center;
justify-content: center;
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;
}
.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:hover {
border-color: var(--line-strong);
transform: translateY(-2px);
}
.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;
}
.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;
}
.card-date {
min-height: 32px;
font-size: 12px;
line-height: 1.35;
}
.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>
<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 Open In Search to jump back to the main page with the title pre-filled.</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="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,
thumbnailNonce: Date.now(),
refreshRunning: false,
refreshJobId: null
};
const $ = (id) => document.getElementById(id);
async function api(path, options = {}) {
const response = await fetch(path, {
headers: { "Content-Type": "application/json" },
...options
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || "Request failed");
return data;
}
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 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
? `${totals.shows} tracked shows across ${state.watchlistPages} pages.`
: "Track shows and manually refresh sub and dub episode counts.";
}
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;
}
async function hydrateThumbnailsOnce(items) {
const missing = items.filter((item) => !item.thumbnail_ready).map((item) => item.show_id).slice(0, 8);
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 || []) {
const card = findCardByShowId(item.show_id);
if (!card) continue;
applyThumbnail(card, item, true);
}
} catch (_error) {
}
}
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) {
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) {
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;
const container = $("watchlist-container");
container.innerHTML = "";
renderSummary(data.summary);
if (!items.length) {
container.innerHTML = '<div class="empty">Your watchlist is empty. Add anime here or from the search page.</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 = `anime-card${item.status === "error" ? " error" : ""}`;
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="card-title"></div>
<div class="count-row">
<span class="count-pill">Sub <strong>${item.sub_count || 0}</strong></span>
<span class="count-pill">Dub <strong>${item.dub_count || 0}</strong></span>
</div>
<div class="muted card-date"></div>
<div class="card-actions">
<button class="primary" type="button">Refresh</button>
<button class="ghost" type="button">Open</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);
card.querySelector(".card-date").textContent = `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];
refreshBtn.addEventListener("click", () => refreshWatchlistItem(item.show_id));
searchBtn.addEventListener("click", () => {
window.location.href = `/?query=${encodeURIComponent(item.title || item.show_id)}`;
});
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) {
setNotice("Loading watchlist...");
try {
const data = await api(`/api/watchlist?page=${page}&per_page=30`);
if (data.page > data.pages && data.pages > 0) {
return fetchWatchlist(data.pages);
}
renderWatchlist(data);
setNotice("");
} catch (error) {
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 })
});
$("watchlist-form").reset();
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 status updated.");
await fetchWatchlist();
} 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 })
});
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);
window.setInterval(() => {
if (state.refreshRunning) {
pollRefreshStatus(true);
}
}, 2500);
} catch (error) {
setNotice(error.message);
}
})();
</script>
</body>
</html>
"""