From 604265c44fb916f51f4826feb55a27f291cf173c Mon Sep 17 00:00:00 2001 From: Dymas Date: Fri, 17 Jul 2026 12:30:23 +0200 Subject: [PATCH] Show Jellyfin handoff jobs in queue --- CHANGELOG.md | 4 +++ README.md | 6 ++--- VERSION | 2 +- http_handler.py | 70 +++++++++++++++++++++++++++++++++++++++++++++---- queue_jobs.py | 68 +++++++++++++++++++++++++++++++++++++++++++++++ queue_page.py | 17 ++++++++++-- test_app.py | 42 +++++++++++++++++++++++++++++ 7 files changed, 198 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9292f1c..5aa26bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 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. diff --git a/README.md b/README.md index cfba89b..a51b01a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Local web UI for a system-wide `ani-cli` install. -Current version: `0.48.2` +Current version: `0.48.3` ## What it does @@ -13,14 +13,14 @@ Current version: `0.48.2` - 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, avoid duplicate re-queues for the same failed download, clear failed jobs, and 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 diff --git a/VERSION b/VERSION index e85205d..c373fc9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.48.2 +0.48.3 diff --git a/http_handler.py b/http_handler.py index 7445726..de26f70 100644 --- a/http_handler.py +++ b/http_handler.py @@ -156,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: @@ -619,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("/") @@ -627,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() @@ -712,10 +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(runtime["download_queue"].clear_failed()) + self.json(queue_clear_failed(runtime)) elif parsed.path.startswith("/api/queue/"): runtime = Handler._runtime(self) parts = parsed.path.strip("/").split("/") @@ -726,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") diff --git a/queue_jobs.py b/queue_jobs.py index bff323c..375a80c 100644 --- a/queue_jobs.py +++ b/queue_jobs.py @@ -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: diff --git a/queue_page.py b/queue_page.py index bd14ec6..0b7f481 100644 --- a/queue_page.py +++ b/queue_page.py @@ -390,6 +390,13 @@ QUEUE_HTML = r""" } 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}`; @@ -403,6 +410,12 @@ QUEUE_HTML = r""" 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; @@ -416,14 +429,14 @@ QUEUE_HTML = r""" 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; } diff --git a/test_app.py b/test_app.py index b8716c7..da3e22b 100644 --- a/test_app.py +++ b/test_app.py @@ -389,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( @@ -429,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( { @@ -3528,6 +3565,11 @@ class TemplateHelperTests(unittest.TestCase): 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)