Compare commits

6 Commits
Author SHA1 Message Date
Dymas 6bec0e068a Add botan to Docker image 2026-07-17 22:25:56 +02:00
Dymas 604265c44f Show Jellyfin handoff jobs in queue 2026-07-17 12:30:23 +02:00
Dymas ba408877b5 Add website favicon support 2026-07-09 18:15:52 +02:00
Dymas 34c77ed9bb Reuse failed queue jobs for duplicate retries 2026-07-09 17:38:24 +02:00
Dymas 292bbedd6b Add clear failed queue action
Add a Queue page bulk action and API route to remove all failed jobs, cover it with regression tests, and update the version, changelog, and README for the new queue workflow.
2026-07-09 17:20:55 +02:00
Dymas 0257924785 Merge branch 'anipy_backup' 2026-07-09 17:17:45 +02:00
12 changed files with 454 additions and 21 deletions
+16
View File
@@ -1,5 +1,21 @@
# Changelog
## 0.48.3 - 2026-07-17
- Added Jellyfin handoff jobs to the Queue page so manual copy jobs appear alongside downloads with live progress, moved-file counts, and recent handoff activity.
## 0.48.2 - 2026-07-09
- Added support for a checked-in `favicon.png`, serving it from the app and wiring it into the website pages so browsers show the custom favicon.
## 0.48.1 - 2026-07-09
- Changed queue inserts so adding a download that exactly matches an existing failed job now reuses that failed entry and resets it to pending instead of creating another duplicate failed row.
## 0.48.0 - 2026-07-09
- Added a `Clear failed` bulk action to the Queue page so failed jobs can be removed without touching pending, running, finished, or canceled downloads.
## 0.47.1 - 2026-07-09
- Fixed `anipy-cli` fallback renaming for queued TV downloads so retried jobs now keep the requested episode numbers from the queue, avoiding cases like a retried `S02E11` being renamed as `S02E01`.
+1
View File
@@ -22,6 +22,7 @@ ENV DEBIAN_FRONTEND=noninteractive \
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
aria2 \
botan \
ca-certificates \
curl \
ffmpeg \
+11 -4
View File
@@ -2,7 +2,7 @@
Local web UI for a system-wide `ani-cli` install.
Current version: `0.47.1`
Current version: `0.48.3`
## What it does
@@ -13,13 +13,14 @@ Current version: `0.47.1`
- Expose a small JSON summary endpoint for Homepage dashboard widgets
- Refresh watchlist episode counts manually or on a schedule
- Auto-download missing episodes for `Watching` entries after later refreshes, with a per-show `Source name` override for `ani-cli` search
- Move fully completed libraries into Jellyfin TV or movie folders with a tracked background handoff job
- Move fully completed libraries into Jellyfin TV or movie folders with tracked background handoff jobs that also appear in the Queue page
- Send optional Discord webhook notifications
- Serve a checked-in `favicon.png` as the site favicon
## Pages
- `/`: Search and queue downloads, with poster-card search results below the selection box and alternate English titles under the main name when available
- `/queue`: Monitor jobs, inspect logs, retry failed jobs, remove finished jobs
- `/queue`: Monitor downloads and Jellyfin handoff jobs, inspect logs, retry failed downloads, avoid duplicate re-queues for the same failed download, clear failed jobs, and remove finished jobs
- `/watchlist`: Track shows, refresh them, download all available episodes, and manage auto-download settings such as `Source name`, library `Name`, season, and episode offset
- `/config`: Save defaults, toggle `anipy-cli` fallback retries, schedule refreshes, configure Jellyfin and Discord, monitor Jellyfin handoff progress, and view runtime info and the changelog
@@ -29,7 +30,7 @@ Requirements:
- `ani-cli` installed and available in `PATH`
- Optional: `anipy-cli` installed and available in `PATH` if you want automatic fallback retries outside Docker
- Common runtime tools used by `ani-cli`, especially `curl`, `ffmpeg`, `fzf`, `grep`, `openssl`, `sed`, `aria2c`, and `yt-dlp`
- Common runtime tools used by `ani-cli`, especially `curl`, `ffmpeg`, `fzf`, `grep`, `openssl`, `sed`, `aria2c`, `botan`, and `yt-dlp`
Run locally:
@@ -93,6 +94,7 @@ Docker notes:
- `USER_UID` and `USER_GID` help keep mounted files owned by your host user
- `UPDATE_ON_START=true` runs `ani-cli --update` before startup
- `ANI_CLI_WEB_BRANCH` lets the image clone a specific `ani-cli-web` branch at build time
- `botan` is installed inside the container for providers or scripts that need Botan cryptography tooling
- `anipy-cli` is installed systemwide inside the container, so fallback retries are available without extra container setup
## Key behavior
@@ -119,6 +121,11 @@ Docker notes:
- Fallback retries keep the queued episode numbers when the downloaded `anipy-cli` filenames are renumbered from `1`
- Docker images install `anipy-cli` automatically; non-Docker installs should provide it in `PATH` themselves
### Queue retries
- Adding a download that exactly matches an existing failed queue job reuses that failed entry and sets it back to `pending`
- This avoids stacking multiple failed rows for the same episode when you queue the same job again
### Jellyfin handoff
- Optional and configured from `/config`
+1 -1
View File
@@ -1 +1 @@
0.47.1
0.48.3
+1
View File
@@ -21,6 +21,7 @@ CONFIG_HTML = r"""<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ani-cli web - config</title>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">
<style>
:root {
color-scheme: dark;
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

+76 -4
View File
@@ -27,6 +27,7 @@ from app_support import (
CLIENT_DISCONNECT_ERRORS,
MAX_JSON_BODY_BYTES,
MODE_CHOICES,
PROJECT_ROOT,
VERSION,
client_address_is_local,
configured_remote_path_roots,
@@ -46,6 +47,8 @@ from app_support import (
validate_discord_webhook_url,
)
FAVICON_PATH = PROJECT_ROOT / "favicon.png"
@dataclass(frozen=True)
class HandlerContext:
add_to_watchlist: object
@@ -153,6 +156,66 @@ def browse_filesystem(path_value="", mode="dir", allowed_roots=None):
}
def queue_list_payload(runtime, page=1, per_page=10):
page = max(1, int(page or 1))
per_page = min(50, max(1, int(per_page or 10)))
download_queue = runtime["download_queue"]
jellyfin_jobs = runtime.get("watchlist_jellyfin_sync")
download_payload = download_queue.list(page=1, per_page=50)
jobs = list(download_payload.get("jobs") or [])
for download_page in range(2, int(download_payload.get("pages") or 1) + 1):
jobs.extend(download_queue.list(page=download_page, per_page=50).get("jobs") or [])
if jellyfin_jobs is not None:
jobs.extend(jellyfin_jobs.list_queue_jobs(limit=200))
jobs.sort(key=lambda job: str(job.get("created_at") or ""), reverse=True)
total = len(jobs)
pages = max(1, (total + per_page - 1) // per_page)
offset = (page - 1) * per_page
return {
"jobs": jobs[offset : offset + per_page],
"page": page,
"per_page": per_page,
"total": total,
"pages": pages,
}
def queue_get_job(runtime, job_id):
try:
return runtime["download_queue"].get(job_id)
except KeyError:
jellyfin_jobs = runtime.get("watchlist_jellyfin_sync")
if jellyfin_jobs is None:
raise
return jellyfin_jobs.get_queue_job(job_id)
def queue_remove_job(runtime, job_id):
try:
return runtime["download_queue"].remove(job_id)
except KeyError:
jellyfin_jobs = runtime.get("watchlist_jellyfin_sync")
if jellyfin_jobs is None:
raise
return jellyfin_jobs.remove_queue_job(job_id)
def queue_clear_finished(runtime):
result = runtime["download_queue"].clear_finished()
jellyfin_jobs = runtime.get("watchlist_jellyfin_sync")
if jellyfin_jobs is not None:
result["count"] = int(result.get("count") or 0) + int(jellyfin_jobs.clear_finished_queue_jobs().get("count") or 0)
return result
def queue_clear_failed(runtime):
result = runtime["download_queue"].clear_failed()
jellyfin_jobs = runtime.get("watchlist_jellyfin_sync")
if jellyfin_jobs is not None:
result["count"] = int(result.get("count") or 0) + int(jellyfin_jobs.clear_failed_queue_jobs().get("count") or 0)
return result
@lru_cache(maxsize=1)
def installed_ani_cli_version():
try:
@@ -382,6 +445,7 @@ class Handler(BaseHTTPRequestHandler):
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{APP_NAME} sign in</title>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">
<style>
:root {{
color-scheme: dark;
@@ -545,6 +609,11 @@ class Handler(BaseHTTPRequestHandler):
self.ensure_client_access()
if parsed.path == "/":
self.html(Handler._context(self).index_html)
elif parsed.path in {"/favicon.png", "/favicon.ico"}:
if not FAVICON_PATH.exists():
self.error(HTTPStatus.NOT_FOUND, "Favicon not found")
return
self.file(FAVICON_PATH)
elif parsed.path == "/queue":
self.html(Handler._context(self).queue_html)
elif parsed.path == "/config":
@@ -610,7 +679,7 @@ class Handler(BaseHTTPRequestHandler):
params = parse_qs(parsed.query)
page = (params.get("page") or ["1"])[0]
per_page = (params.get("per_page") or ["10"])[0]
self.json(runtime["download_queue"].list(page=page, per_page=per_page))
self.json(queue_list_payload(runtime, page=page, per_page=per_page))
elif parsed.path.startswith("/api/queue/"):
runtime = Handler._runtime(self)
parts = parsed.path.strip("/").split("/")
@@ -618,7 +687,7 @@ class Handler(BaseHTTPRequestHandler):
self.error(HTTPStatus.NOT_FOUND, "Not found")
return
_, _, job_id = parts
self.json(runtime["download_queue"].get(job_id))
self.json(queue_get_job(runtime, job_id))
elif parsed.path.startswith("/api/watchlist/thumb/"):
runtime = Handler._runtime(self)
show_id = unquote(parsed.path[len("/api/watchlist/thumb/") :]).strip()
@@ -703,7 +772,10 @@ class Handler(BaseHTTPRequestHandler):
self.json(runtime["download_queue"].retry_all_failed())
elif parsed.path == "/api/queue/clear-finished":
runtime = Handler._runtime(self)
self.json(runtime["download_queue"].clear_finished())
self.json(queue_clear_finished(runtime))
elif parsed.path == "/api/queue/clear-failed":
runtime = Handler._runtime(self)
self.json(queue_clear_failed(runtime))
elif parsed.path.startswith("/api/queue/"):
runtime = Handler._runtime(self)
parts = parsed.path.strip("/").split("/")
@@ -714,7 +786,7 @@ class Handler(BaseHTTPRequestHandler):
actions = {
"retry": runtime["download_queue"].retry,
"cancel": runtime["download_queue"].cancel,
"remove": runtime["download_queue"].remove,
"remove": lambda job_id: queue_remove_job(runtime, job_id),
}
if action not in actions:
self.error(HTTPStatus.NOT_FOUND, "Not found")
+123 -9
View File
@@ -647,6 +647,74 @@ class JellyfinSyncJobs:
def _copy_job(self, job):
return json.loads(json.dumps(job))
def _queue_job_payload(self, job):
config = job.get("config") or {}
target_paths = [
str(config.get(key) or "").strip()
for key in ("jellyfin_tv_dir", "jellyfin_movie_dir")
if str(config.get(key) or "").strip()
]
log_lines = [str(job.get("message") or "")]
if job.get("current_file"):
log_lines.append(f"Moving: {job['current_file']}")
for item in job.get("items") or []:
title = str(item.get("title") or item.get("show_id") or "Unknown title")
outcome = "moved" if item.get("moved") else str(item.get("reason") or "skipped")
target = str(item.get("target") or "").strip()
suffix = f" -> {target}" if target else ""
log_lines.append(f"{title}: {outcome}{suffix}")
payload = self._copy_job(job)
payload.update(
{
"job_type": "jellyfin_handoff",
"title": "Jellyfin handoff",
"anime_name": "Jellyfin handoff",
"mode": "copy",
"quality": "library",
"episodes": f"{int(job.get('completed') or 0)}/{int(job.get('total') or 0)} entries",
"download_dir": str(config.get("download_dir") or ""),
"target_dir": ", ".join(target_paths),
"exit_code": 1 if job.get("status") == "failed" else None,
"log": [line for line in log_lines if line],
}
)
return payload
def list_queue_jobs(self, limit=50):
limit = min(200, max(1, int(limit or 50)))
with self.lock, self._connect() as conn:
rows = conn.execute(
"SELECT payload FROM jellyfin_sync_jobs ORDER BY created_at DESC LIMIT ?",
(limit,),
).fetchall()
return [self._queue_job_payload(self._job_from_row(row)) for row in rows]
def get_queue_job(self, job_id):
with self.lock, self._connect() as conn:
row = conn.execute("SELECT payload FROM jellyfin_sync_jobs WHERE id = ?", (job_id,)).fetchone()
if row:
return self._queue_job_payload(self._job_from_row(row))
raise KeyError("Job not found")
def remove_queue_job(self, job_id):
with self.lock:
job = self.get_queue_job(job_id)
if job["status"] in {"pending", "running"}:
raise ValueError("Running Jellyfin handoff jobs cannot be removed")
with self._connect() as conn:
conn.execute("DELETE FROM jellyfin_sync_jobs WHERE id = ?", (job_id,))
return {"ok": True}
def clear_finished_queue_jobs(self):
with self.lock, self._connect() as conn:
cursor = conn.execute("DELETE FROM jellyfin_sync_jobs WHERE status IN ('done', 'interrupted')")
return {"ok": True, "count": cursor.rowcount}
def clear_failed_queue_jobs(self):
with self.lock, self._connect() as conn:
cursor = conn.execute("DELETE FROM jellyfin_sync_jobs WHERE status = 'failed'")
return {"ok": True, "count": cursor.rowcount}
def _find_locked(self, job_id):
for job in self.jobs:
if job["id"] == job_id:
@@ -1136,6 +1204,51 @@ class DownloadQueue:
with self.lock:
return self._find(job_id)
def _job_identity_fields(self, job):
return (
str(job.get("show_id") or "").strip(),
str(job.get("title") or "").strip(),
str(job.get("anime_name") or "").strip(),
str(job.get("media_type") or "").strip(),
str(job.get("season") or "").strip(),
str(job.get("episode_offset") or "").strip(),
str(job.get("query") or "").strip(),
job.get("result_index"),
str(job.get("mode") or "").strip().lower(),
str(job.get("quality") or "").strip().lower(),
str(job.get("episodes") or "").strip(),
str(job.get("download_dir") or "").strip(),
)
def _find_reusable_failed_job_locked(self, job):
expected = self._job_identity_fields(job)
with self._connect() as conn:
rows = conn.execute(
"""
SELECT *
FROM jobs
WHERE status = 'failed'
ORDER BY created_at DESC
"""
).fetchall()
for row in rows:
candidate = self._job_from_row(row)
if self._job_identity_fields(candidate) == expected:
return candidate
return None
def _reset_retryable_job_locked(self, job):
job["status"] = "pending"
job["exit_code"] = None
job["pid"] = None
job["started_at"] = None
job["finished_at"] = None
job["updated_at"] = now_iso()
job["cancel_requested"] = False
job["log"] = []
self._save_job_locked(job)
return job
def add(self, payload):
job = build_job(payload, self.config_getter())
if self.job_prepare_fn is not None:
@@ -1143,6 +1256,10 @@ class DownloadQueue:
if prepared is not None:
job = prepared
with self.lock:
reusable = self._find_reusable_failed_job_locked(job)
if reusable is not None:
job = self._reset_retryable_job_locked(reusable)
else:
self._save_job_locked(job)
self.wakeup.set()
return job
@@ -1221,15 +1338,7 @@ class DownloadQueue:
raise ValueError("Running jobs cannot be retried")
if job["status"] not in {"failed", "canceled"}:
raise ValueError("Only failed or canceled jobs can be retried")
job["status"] = "pending"
job["exit_code"] = None
job["pid"] = None
job["started_at"] = None
job["finished_at"] = None
job["updated_at"] = now_iso()
job["cancel_requested"] = False
job["log"] = []
self._save_job_locked(job)
job = self._reset_retryable_job_locked(job)
self.wakeup.set()
return job
@@ -1291,6 +1400,11 @@ class DownloadQueue:
cursor = conn.execute("DELETE FROM jobs WHERE status IN ('done', 'canceled')")
return {"ok": True, "count": cursor.rowcount}
def clear_failed(self):
with self.lock, self._connect() as conn:
cursor = conn.execute("DELETE FROM jobs WHERE status = 'failed'")
return {"ok": True, "count": cursor.rowcount}
def _find(self, job_id):
with self._connect() as conn:
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
+18 -2
View File
@@ -11,6 +11,7 @@ QUEUE_HTML = r"""<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ani-cli web queue</title>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">
<style>
:root {
color-scheme: dark;
@@ -317,6 +318,7 @@ QUEUE_HTML = r"""<!doctype html>
<p class="muted">Monitor active downloads, inspect recent output, and clean up finished jobs without leaving the queue view.</p>
<div class="row">
<button class="ghost" id="retryFailedBtn" type="button">Retry failed</button>
<button class="ghost" id="clearFailedBtn" type="button">Clear failed</button>
<button class="ghost" id="removeFinishedBtn" type="button">Remove finished</button>
</div>
</section>
@@ -388,6 +390,13 @@ QUEUE_HTML = r"""<!doctype html>
}
function buildJobSummary(job) {
if (job.job_type === "jellyfin_handoff") {
const progress = `${job.completed || 0}/${job.total || 0} entries`;
const moved = `${job.moved || 0} moved`;
const files = `${job.moved_files || 0} files`;
const target = job.target_dir || "Jellyfin libraries";
return `${progress} · ${moved} · ${files} · ${target}`;
}
const libraryName = job.anime_name || job.title;
const season = String(job.season || "1").padStart(2, "0");
const seasonFolder = `Season ${season}`;
@@ -401,6 +410,12 @@ QUEUE_HTML = r"""<!doctype html>
function renderJobActions(job, actions) {
actions.innerHTML = "";
if (job.job_type === "jellyfin_handoff") {
if (job.status !== "running" && job.status !== "pending") {
actions.append(actionButton("Remove", () => queueAction(job.id, "remove")));
}
return;
}
if (job.status === "running" || job.status === "pending") {
actions.append(actionButton("Cancel", () => queueAction(job.id, "cancel"), "danger"));
return;
@@ -414,14 +429,14 @@ QUEUE_HTML = r"""<!doctype html>
function updateJobCard(item, job) {
item.dataset.jobId = job.id;
item.dataset.jobStatus = job.status;
item.querySelector(".job-title").textContent = job.title;
item.querySelector(".job-title").textContent = job.title || "Untitled job";
item.querySelector(".job-head .muted").textContent = buildJobSummary(job);
const status = item.querySelector(".status");
status.textContent = job.status;
status.className = "status";
status.classList.add(job.status);
item.querySelector("pre").textContent = buildJobLog(job) || "Waiting...";
item.querySelector(".toolbar .muted").textContent = job.exit_code === null ? "" : `exit ${job.exit_code}`;
item.querySelector(".toolbar .muted").textContent = job.exit_code === null || job.exit_code === undefined ? "" : `exit ${job.exit_code}`;
renderJobActions(job, item.querySelector(".row"));
state.jobCards[job.id] = item;
}
@@ -548,6 +563,7 @@ QUEUE_HTML = r"""<!doctype html>
}
$("removeFinishedBtn").addEventListener("click", () => queueBulkAction("/api/queue/clear-finished", "Removed finished and canceled jobs"));
$("clearFailedBtn").addEventListener("click", () => queueBulkAction("/api/queue/clear-failed", "Removed failed jobs"));
$("retryFailedBtn").addEventListener("click", () => queueBulkAction("/api/queue/retry-failed", "Retried failed jobs"));
(async function init() {
+1
View File
@@ -11,6 +11,7 @@ INDEX_HTML = r"""<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ani-cli web</title>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">
<style>
:root {
color-scheme: dark;
+204
View File
@@ -176,6 +176,14 @@ class NetworkGuardTests(unittest.TestCase):
self.assertIn("Username", body)
self.assertIn("Password", body)
def test_favicon_route_serves_checked_in_png(self):
handler = DummyHandler("/favicon.png")
handler.command = "GET"
APP.Handler.do_GET(handler)
self.assertEqual(handler.file_path, http_handler.FAVICON_PATH)
def test_remote_login_page_escapes_hidden_next_value(self):
handler = DummyHandler('/?next="><script>alert(1)</script>')
handler.client_address = ("192.168.1.25", 8421)
@@ -381,6 +389,7 @@ class QueueApiTests(unittest.TestCase):
self.queue = APP.DOWNLOAD_QUEUE
with self.queue._connect() as conn:
conn.execute("DELETE FROM jobs")
conn.execute("DELETE FROM jellyfin_sync_jobs")
def test_download_queue_get_returns_single_job(self):
created = self.queue.add(
@@ -421,6 +430,42 @@ class QueueApiTests(unittest.TestCase):
self.assertEqual(handler.json_status, HTTPStatus.OK)
self.assertEqual(handler.json_payload["id"], created["id"])
def test_queue_route_includes_jellyfin_handoff_jobs(self):
APP.WATCHLIST_JELLYFIN_SYNC.start(
config={
"download_dir": "/tmp/downloads",
"jellyfin_sync_enabled": True,
"jellyfin_tv_dir": "/tmp/jellyfin-tv",
"jellyfin_movie_dir": "/tmp/jellyfin-movies",
}
)
handler = DummyHandler("/api/queue?page=1&per_page=10")
APP.Handler.do_GET(handler)
self.assertEqual(handler.json_status, HTTPStatus.OK)
jellyfin_jobs = [job for job in handler.json_payload["jobs"] if job.get("job_type") == "jellyfin_handoff"]
self.assertEqual(len(jellyfin_jobs), 1)
self.assertEqual(jellyfin_jobs[0]["title"], "Jellyfin handoff")
self.assertEqual(jellyfin_jobs[0]["mode"], "copy")
def test_queue_item_get_route_returns_jellyfin_handoff_job(self):
created = APP.WATCHLIST_JELLYFIN_SYNC.start(
config={
"download_dir": "/tmp/downloads",
"jellyfin_sync_enabled": True,
"jellyfin_tv_dir": "/tmp/jellyfin-tv",
"jellyfin_movie_dir": "",
}
)["job"]
handler = DummyHandler(f"/api/queue/{created['id']}")
APP.Handler.do_GET(handler)
self.assertEqual(handler.json_status, HTTPStatus.OK)
self.assertEqual(handler.json_payload["id"], created["id"])
self.assertEqual(handler.json_payload["job_type"], "jellyfin_handoff")
def test_retry_rejects_done_jobs(self):
created = self.queue.add(
{
@@ -466,6 +511,121 @@ class QueueApiTests(unittest.TestCase):
self.assertEqual(retried["status"], "pending")
self.assertFalse(retried["cancel_requested"])
def test_add_reuses_matching_failed_job_instead_of_creating_duplicate(self):
payload = {
"show_id": "show-42",
"query": "Failed Show",
"title": "Failed Show",
"anime_name": "Failed Show",
"media_type": "tv",
"mode": "dub",
"quality": "best",
"episodes": "11",
"download_dir": "/tmp/example",
"season": "2",
"episode_offset": "13",
}
created = self.queue.add(payload)
with self.queue.lock:
job = self.queue._find(created["id"])
job["status"] = "failed"
job["exit_code"] = 1
job["cancel_requested"] = True
job["started_at"] = APP.now_iso()
job["finished_at"] = APP.now_iso()
job["log"] = ["Download failed"]
self.queue._save_job_locked(job)
retried = self.queue.add(payload)
listing = self.queue.list(per_page=10)
self.assertEqual(retried["id"], created["id"])
self.assertEqual(retried["status"], "pending")
self.assertEqual(retried["log"], [])
self.assertIsNone(retried["exit_code"])
self.assertFalse(retried["cancel_requested"])
self.assertEqual(listing["total"], 1)
def test_add_keeps_new_job_when_failed_job_differs(self):
created = self.queue.add(
{
"show_id": "show-42",
"query": "Failed Show",
"title": "Failed Show",
"anime_name": "Failed Show",
"media_type": "tv",
"mode": "dub",
"quality": "best",
"episodes": "11",
"download_dir": "/tmp/example",
"season": "2",
"episode_offset": "13",
}
)
with self.queue.lock:
job = self.queue._find(created["id"])
job["status"] = "failed"
self.queue._save_job_locked(job)
new_job = self.queue.add(
{
"show_id": "show-42",
"query": "Failed Show",
"title": "Failed Show",
"anime_name": "Failed Show",
"media_type": "tv",
"mode": "dub",
"quality": "720",
"episodes": "11",
"download_dir": "/tmp/example",
"season": "2",
"episode_offset": "13",
}
)
listing = self.queue.list(per_page=10)
self.assertNotEqual(new_job["id"], created["id"])
self.assertEqual(listing["total"], 2)
def test_clear_failed_removes_only_failed_jobs(self):
failed = self.queue.add(
{
"query": "Failed Show",
"title": "Failed Show",
"anime_name": "Failed Show",
"mode": "sub",
"quality": "best",
"episodes": "1",
"download_dir": "/tmp/example",
"season": "1",
}
)
done = self.queue.add(
{
"query": "Done Show",
"title": "Done Show",
"anime_name": "Done Show",
"mode": "sub",
"quality": "best",
"episodes": "1",
"download_dir": "/tmp/example",
"season": "1",
}
)
with self.queue.lock:
failed_job = self.queue._find(failed["id"])
failed_job["status"] = "failed"
self.queue._save_job_locked(failed_job)
done_job = self.queue._find(done["id"])
done_job["status"] = "done"
self.queue._save_job_locked(done_job)
result = self.queue.clear_failed()
listing = self.queue.list()
self.assertEqual(result["count"], 1)
self.assertEqual([job["id"] for job in listing["jobs"]], [done["id"]])
def test_detach_show_clears_queue_coverage_and_sync_binding(self):
created = self.queue.add(
{
@@ -2817,6 +2977,33 @@ class HandlerRouteTests(unittest.TestCase):
self.assertEqual(handler.json_status, HTTPStatus.OK)
self.assertIn("anipy-cli", handler.json_payload)
def test_clear_failed_route_removes_failed_jobs(self):
with APP.DOWNLOAD_QUEUE._connect() as conn:
conn.execute("DELETE FROM jobs")
job = APP.DOWNLOAD_QUEUE.add(
{
"query": "Failed Route Show",
"title": "Failed Route Show",
"anime_name": "Failed Route Show",
"mode": "sub",
"quality": "best",
"episodes": "1",
"download_dir": "/tmp/example",
"season": "1",
}
)
with APP.DOWNLOAD_QUEUE.lock:
stored = APP.DOWNLOAD_QUEUE._find(job["id"])
stored["status"] = "failed"
APP.DOWNLOAD_QUEUE._save_job_locked(stored)
handler = DummyHandler("/api/queue/clear-failed", body=b"{}", content_length=2)
APP.Handler.do_POST(handler)
self.assertEqual(handler.json_status, HTTPStatus.OK)
self.assertEqual(handler.json_payload["count"], 1)
self.assertEqual(APP.DOWNLOAD_QUEUE.list()["total"], 0)
def test_changelog_route_returns_project_changelog_content(self):
handler = DummyHandler("/api/changelog")
APP.Handler.do_GET(handler)
@@ -3340,6 +3527,13 @@ class TemplateHelperTests(unittest.TestCase):
self.assertIn("async function api(path, options = {})", APP.CONFIG_HTML)
self.assertIn("async function api(path, options = {})", APP.WATCHLIST_HTML)
def test_pages_include_favicon_link(self):
expected = '<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">'
self.assertIn(expected, APP.INDEX_HTML)
self.assertIn(expected, APP.QUEUE_HTML)
self.assertIn(expected, APP.CONFIG_HTML)
self.assertIn(expected, APP.WATCHLIST_HTML)
def test_config_page_places_dependencies_before_settings_grid(self):
self.assertIn('<section class="deps" id="deps"></section>', APP.CONFIG_HTML)
self.assertIn('<div class="settings-grid">', APP.CONFIG_HTML)
@@ -3366,6 +3560,16 @@ class TemplateHelperTests(unittest.TestCase):
def test_search_page_sends_watchlist_auto_download_series(self):
self.assertIn('auto_download_series: $("seasonInput").value || "1"', APP.INDEX_HTML)
def test_queue_page_includes_clear_failed_bulk_action(self):
self.assertIn('id="clearFailedBtn"', APP.QUEUE_HTML)
self.assertIn('/api/queue/clear-failed', APP.QUEUE_HTML)
self.assertIn('Removed failed jobs', APP.QUEUE_HTML)
def test_queue_page_formats_jellyfin_handoff_jobs(self):
self.assertIn('job.job_type === "jellyfin_handoff"', APP.QUEUE_HTML)
self.assertIn('const progress = `${job.completed || 0}/${job.total || 0} entries`;', APP.QUEUE_HTML)
self.assertIn('const moved = `${job.moved || 0} moved`;', APP.QUEUE_HTML)
def test_search_page_queues_selected_title_without_result_index(self):
self.assertIn('query: state.selected.title,', APP.INDEX_HTML)
self.assertNotIn('index: state.selected.index,', APP.INDEX_HTML)
+1
View File
@@ -11,6 +11,7 @@ WATCHLIST_HTML = r"""<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ani-cli web - watchlist</title>
<link rel="icon" type="image/png" sizes="32x32" href="/favicon.png">
<style>
:root {
color-scheme: dark;