Compare commits
11
Commits
332ec670fc
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bec0e068a | ||
|
|
604265c44f | ||
|
|
ba408877b5 | ||
|
|
34c77ed9bb | ||
|
|
292bbedd6b | ||
|
|
0257924785 | ||
|
|
bcf9e15d40 | ||
|
|
0c17499efa | ||
|
|
e84ef16f7d | ||
|
|
4e980220b1 | ||
|
|
d8ed64bd64 |
@@ -0,0 +1,6 @@
|
||||
- always bump up the VERSION unless its changes to Dockerfile, *.md files
|
||||
- always document changes in simple CHANGELOG.md unless modifiing Dockerfile, *.md, VERSION
|
||||
- when needed you may install any tools using pip if the project reqires it
|
||||
- you can freely acces any LAN URL and github.com URL.
|
||||
- always update README.md to reflect current project.
|
||||
- always commit changes with commentary
|
||||
@@ -1,5 +1,30 @@
|
||||
# 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`.
|
||||
|
||||
## 0.47.0 - 2026-07-09
|
||||
|
||||
- Added an optional `anipy-cli` fallback toggle on the Config page so failed `ani-cli` queue jobs can automatically retry once with `anipy-cli`.
|
||||
- Exposed `anipy-cli` availability and version in Config page runtime checks, and updated queue processing so fallback downloads still finalize into the same TV or movie library layout.
|
||||
|
||||
## 0.46.0 - 2026-06-14
|
||||
|
||||
- Changed manual Jellyfin handoff to run as a persisted background job instead of a single blocking request, so the Config page can show live progress while files are being moved.
|
||||
|
||||
+7
-1
@@ -3,12 +3,14 @@ FROM python:3.12-slim
|
||||
ARG ANI_CLI=https://github.com/pystardust/ani-cli.git
|
||||
ARG ANI_CLI_BRANCH=master
|
||||
ARG ANI_CLI_WEB=https://gitea.coreplay.eu/Dymas/ani-cli-web.git
|
||||
ARG ANI_CLI_WEB_BRANCH=main
|
||||
ARG YT_DLP_RELEASE_URL=https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
ANI_CLI_REPO=${ANI_CLI} \
|
||||
ANI_CLI_BRANCH=${ANI_CLI_BRANCH} \
|
||||
ANI_CLI_WEB_REPO=${ANI_CLI_WEB} \
|
||||
ANI_CLI_WEB_BRANCH=${ANI_CLI_WEB_BRANCH} \
|
||||
ANI_CLI_BIN=ani-cli \
|
||||
ANI_CLI_DOWNLOAD_DIR=/downloads \
|
||||
ANI_CLI_WEB_HOST=0.0.0.0 \
|
||||
@@ -20,6 +22,7 @@ ENV DEBIAN_FRONTEND=noninteractive \
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
aria2 \
|
||||
botan \
|
||||
ca-certificates \
|
||||
curl \
|
||||
ffmpeg \
|
||||
@@ -46,7 +49,10 @@ RUN curl -fL "${YT_DLP_RELEASE_URL}" -o /usr/local/bin/yt-dlp \
|
||||
&& chmod 0755 /usr/local/bin/yt-dlp \
|
||||
&& yt-dlp --version
|
||||
|
||||
RUN git clone --depth 1 "${ANI_CLI_WEB}" /app \
|
||||
RUN python3 -m pip install --no-cache-dir anipy-cli \
|
||||
&& anipy-cli --version
|
||||
|
||||
RUN git clone --depth 1 --branch "${ANI_CLI_WEB_BRANCH}" "${ANI_CLI_WEB}" /app \
|
||||
&& rm -rf /app/.git \
|
||||
&& rm -f \
|
||||
/app/.dockerignore \
|
||||
|
||||
@@ -2,32 +2,35 @@
|
||||
|
||||
Local web UI for a system-wide `ani-cli` install.
|
||||
|
||||
Current version: `0.46.0`
|
||||
Current version: `0.48.3`
|
||||
|
||||
## What it does
|
||||
|
||||
- Search anime in `sub` or `dub`, with poster-style results shown below the selection panel and the first English alternate title when available
|
||||
- Queue downloads with folder, quality, media type, season, and episode controls
|
||||
- Optionally retry failed `ani-cli` downloads with `anipy-cli`
|
||||
- Track shows in a watchlist with `Watching`, `Planned`, `Finished`, and `Dropped` categories
|
||||
- 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, schedule refreshes, configure Jellyfin and Discord, monitor Jellyfin handoff progress, and view runtime info and the changelog
|
||||
- `/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
|
||||
|
||||
## Quick start
|
||||
|
||||
Requirements:
|
||||
|
||||
- `ani-cli` installed and available in `PATH`
|
||||
- Common runtime tools used by `ani-cli`, especially `curl`, `ffmpeg`, `fzf`, `grep`, `openssl`, `sed`, `aria2c`, and `yt-dlp`
|
||||
- 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`, `botan`, and `yt-dlp`
|
||||
|
||||
Run locally:
|
||||
|
||||
@@ -47,6 +50,7 @@ Useful flags and env:
|
||||
- `ANI_CLI_WEB_HOST=0.0.0.0`
|
||||
- `ANI_CLI_WEB_PORT=8421`
|
||||
- `ANI_CLI_BIN=/path/to/ani-cli`
|
||||
- `ANIPY_CLI_BIN=/path/to/anipy-cli`
|
||||
|
||||
## Docker
|
||||
|
||||
@@ -56,6 +60,14 @@ Build:
|
||||
docker build -t ani-cli-web .
|
||||
```
|
||||
|
||||
Build a specific `ani-cli-web` branch:
|
||||
|
||||
```sh
|
||||
docker build \
|
||||
--build-arg ANI_CLI_WEB_BRANCH=anipy_backup \
|
||||
-t ani-cli-web .
|
||||
```
|
||||
|
||||
Run:
|
||||
|
||||
```sh
|
||||
@@ -81,6 +93,9 @@ Docker notes:
|
||||
- App state is stored under `/app/.ani-cli-web`
|
||||
- `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
|
||||
|
||||
@@ -99,6 +114,18 @@ Docker notes:
|
||||
- Uses the per-show language, quality, `Source name` search override, season, library name, and optional episode offset settings
|
||||
- Can queue backlog episodes that were already available before the show was first tracked
|
||||
|
||||
### Download fallback
|
||||
|
||||
- Optional and configured from `/config`
|
||||
- When enabled, a failed `ani-cli` queue job retries once with `anipy-cli`
|
||||
- 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`
|
||||
@@ -135,6 +162,7 @@ The Config page runtime panel shows:
|
||||
|
||||
- `ani-cli-web` version loaded from `VERSION`
|
||||
- Installed `ani-cli` version
|
||||
- Installed `anipy-cli` version and dependency status
|
||||
- A `Changelog` button that opens a scrollable viewer backed by `CHANGELOG.md`
|
||||
|
||||
## Remote access
|
||||
@@ -182,6 +210,7 @@ ANI_CLI_DOWNLOAD_DIR/movie/Movie Name/Movie Name.mp4
|
||||
Most users only need these environment variables:
|
||||
|
||||
- `ANI_CLI_BIN`
|
||||
- `ANIPY_CLI_BIN`
|
||||
- `ANI_CLI_WEB_HOST`
|
||||
- `ANI_CLI_WEB_PORT`
|
||||
- `ANI_CLI_WEB_ALLOW_REMOTE`
|
||||
|
||||
+64
-7
@@ -23,6 +23,7 @@ from uuid import uuid4
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent
|
||||
ANI_CLI = os.environ.get("ANI_CLI_BIN") or shutil.which("ani-cli") or "ani-cli"
|
||||
ANIPY_CLI = os.environ.get("ANIPY_CLI_BIN") or shutil.which("anipy-cli") or "anipy-cli"
|
||||
APP_NAME = "ani-cli-web"
|
||||
VERSION_FILE = PROJECT_ROOT / "VERSION"
|
||||
CHANGELOG_FILE = PROJECT_ROOT / "CHANGELOG.md"
|
||||
@@ -290,6 +291,7 @@ DEFAULT_CONFIG = {
|
||||
"download_dir": default_download_dir(),
|
||||
"mode": os.environ.get("ANI_CLI_MODE", "sub"),
|
||||
"quality": os.environ.get("ANI_CLI_QUALITY", "best"),
|
||||
"anipy_cli_fallback_enabled": False,
|
||||
"watchlist_auto_refresh_enabled": False,
|
||||
"watchlist_auto_refresh_minutes": WATCHLIST_AUTO_REFRESH_DEFAULT_MINUTES,
|
||||
"watchlist_refresh_delay_seconds": WATCHLIST_REFRESH_DELAY_DEFAULT_SECONDS,
|
||||
@@ -445,6 +447,7 @@ def normalize_config(data):
|
||||
if quality.endswith("p") and quality[:-1].isdigit():
|
||||
quality = quality[:-1]
|
||||
download_dir = str(config.get("download_dir") or DEFAULT_CONFIG["download_dir"])
|
||||
anipy_cli_fallback_enabled = config.get("anipy_cli_fallback_enabled")
|
||||
auto_refresh_enabled = config.get("watchlist_auto_refresh_enabled")
|
||||
auto_refresh_minutes = config.get("watchlist_auto_refresh_minutes")
|
||||
refresh_delay_seconds = config.get("watchlist_refresh_delay_seconds")
|
||||
@@ -461,6 +464,10 @@ def normalize_config(data):
|
||||
auth_username = str(config.get("auth_username") or "").strip()
|
||||
auth_password = str(config.get("auth_password") or "").strip()
|
||||
|
||||
if isinstance(anipy_cli_fallback_enabled, str):
|
||||
anipy_cli_fallback_enabled = anipy_cli_fallback_enabled.strip().lower() in {"1", "true", "yes", "on"}
|
||||
else:
|
||||
anipy_cli_fallback_enabled = bool(anipy_cli_fallback_enabled)
|
||||
if isinstance(auto_refresh_enabled, str):
|
||||
auto_refresh_enabled = auto_refresh_enabled.strip().lower() in {"1", "true", "yes", "on"}
|
||||
else:
|
||||
@@ -494,6 +501,7 @@ def normalize_config(data):
|
||||
config["mode"] = mode if mode in MODE_CHOICES else "sub"
|
||||
config["quality"] = quality if quality in QUALITY_CHOICES else "best"
|
||||
config["download_dir"] = str(Path(download_dir).expanduser())
|
||||
config["anipy_cli_fallback_enabled"] = anipy_cli_fallback_enabled
|
||||
config["watchlist_auto_refresh_enabled"] = auto_refresh_enabled
|
||||
config["watchlist_auto_refresh_minutes"] = auto_refresh_minutes
|
||||
config["watchlist_refresh_delay_seconds"] = refresh_delay_seconds
|
||||
@@ -961,6 +969,13 @@ def strip_control(value):
|
||||
return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", str(value)).replace("\r", "\n")
|
||||
|
||||
|
||||
def cli_executable_exists(command):
|
||||
text = str(command or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
return bool(shutil.which(text) or (Path(text).exists() and os.access(text, os.X_OK)))
|
||||
|
||||
|
||||
def printable_command(command):
|
||||
return " ".join(sh_quote(part) for part in command)
|
||||
|
||||
@@ -1061,6 +1076,26 @@ def extract_episode_from_filename(path):
|
||||
return match.group(1) if match else None
|
||||
|
||||
|
||||
def episode_values_from_spec(value):
|
||||
spec = str(value or "").strip()
|
||||
if not spec:
|
||||
return []
|
||||
values = []
|
||||
for part in re.split(r"\s+", spec):
|
||||
if not part:
|
||||
continue
|
||||
if "-" in part:
|
||||
start_text, end_text = [piece.strip() for piece in part.split("-", 1)]
|
||||
if start_text.isdigit() and end_text.isdigit():
|
||||
start = int(start_text, 10)
|
||||
end = int(end_text, 10)
|
||||
if start <= end:
|
||||
values.extend(str(number) for number in range(start, end + 1))
|
||||
continue
|
||||
values.append(part)
|
||||
return values
|
||||
|
||||
|
||||
def unique_destination(path):
|
||||
if not path.exists():
|
||||
return path
|
||||
@@ -1081,18 +1116,24 @@ def finalize_library_files(job):
|
||||
episode_offset = normalize_episode_offset(job.get("episode_offset"))
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
files = sorted(
|
||||
[path for path in staging_dir.iterdir() if path.is_file()],
|
||||
key=lambda path: (path.stat().st_mtime, path.name),
|
||||
[path for path in staging_dir.rglob("*") if path.is_file()],
|
||||
key=lambda path: (path.stat().st_mtime, str(path.relative_to(staging_dir)).lower()),
|
||||
)
|
||||
if not files:
|
||||
raise RuntimeError("No downloaded files were found in the staging folder")
|
||||
|
||||
moved = []
|
||||
fallback_episode = 1
|
||||
requested_episode_values = episode_values_from_spec(job.get("episodes"))
|
||||
backend = str(job.get("download_backend") or "").strip().lower()
|
||||
for source in files:
|
||||
if media_type == "movie":
|
||||
final_name = f"{library_name}{source.suffix}"
|
||||
else:
|
||||
ep = None
|
||||
if backend == "anipy-cli" and requested_episode_values:
|
||||
ep = requested_episode_values.pop(0)
|
||||
if ep is None:
|
||||
ep = extract_episode_from_filename(source)
|
||||
if ep is None:
|
||||
ep = str(fallback_episode)
|
||||
@@ -1103,10 +1144,7 @@ def finalize_library_files(job):
|
||||
shutil.move(str(source), str(destination))
|
||||
moved.append(str(destination))
|
||||
|
||||
try:
|
||||
staging_dir.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
shutil.rmtree(staging_dir, ignore_errors=True)
|
||||
return moved
|
||||
|
||||
|
||||
@@ -1153,7 +1191,26 @@ def build_job(payload, config):
|
||||
}
|
||||
|
||||
|
||||
def command_for_job(job):
|
||||
def anipy_search_spec(job):
|
||||
query = re.sub(r"\s+", " ", str(job.get("query") or "").replace(":", " ")).strip()
|
||||
mode = "dub" if str(job.get("mode") or "").strip().lower() == "dub" else "sub"
|
||||
return f"{query}:{job['episodes']}:{mode}"
|
||||
|
||||
|
||||
def command_for_job(job, backend="ani-cli", download_path=None):
|
||||
normalized_backend = str(backend or "ani-cli").strip().lower()
|
||||
if normalized_backend == "anipy-cli":
|
||||
command = [
|
||||
ANIPY_CLI,
|
||||
"-D",
|
||||
"-s",
|
||||
anipy_search_spec(job),
|
||||
"-q",
|
||||
job["quality"],
|
||||
]
|
||||
if download_path:
|
||||
command.extend(["-l", str(download_path)])
|
||||
return command
|
||||
command = [
|
||||
ANI_CLI,
|
||||
"-d",
|
||||
|
||||
@@ -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;
|
||||
@@ -461,6 +462,7 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
<div class="stack muted">
|
||||
<p id="versionLine">Loading version...</p>
|
||||
<p id="aniCliVersionLine">Detecting ani-cli version...</p>
|
||||
<p id="anipyCliVersionLine">Detecting anipy-cli fallback...</p>
|
||||
<p>Saved settings live in `.ani-cli-web/config.json` inside this project.</p>
|
||||
</div>
|
||||
<button class="ghost wide-button" id="openChangelogBtn" type="button">Changelog</button>
|
||||
@@ -506,6 +508,24 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
<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="settings settings-main">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h2>Download fallback</h2>
|
||||
<p class="muted">If a queued `ani-cli` download fails, optionally retry it once with `anipy-cli`.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<label>Automatic retry with anipy-cli
|
||||
<select id="anipyCliFallbackEnabled">
|
||||
<option value="false">Disabled</option>
|
||||
<option value="true">Enabled</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="field-hint">This only kicks in after an `ani-cli` failure. Install `anipy-cli` separately and keep it in `PATH` if you enable this option.</div>
|
||||
</section>
|
||||
|
||||
<section class="settings settings-main">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
@@ -666,6 +686,7 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
mode: "sub",
|
||||
quality: "best",
|
||||
download_dir: "",
|
||||
anipy_cli_fallback_enabled: false,
|
||||
watchlist_auto_refresh_enabled: false,
|
||||
watchlist_auto_refresh_minutes: 60,
|
||||
watchlist_refresh_delay_seconds: 5,
|
||||
@@ -732,6 +753,7 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
download_dir: $("downloadDir").value,
|
||||
mode: $("configMode").value,
|
||||
quality: $("configQuality").value,
|
||||
anipy_cli_fallback_enabled: $("anipyCliFallbackEnabled").value === "true",
|
||||
watchlist_auto_refresh_enabled: $("watchlistAutoRefreshEnabled").value === "true",
|
||||
watchlist_auto_refresh_minutes: $("watchlistAutoRefreshMinutes").value,
|
||||
watchlist_refresh_delay_seconds: $("watchlistRefreshDelaySeconds").value,
|
||||
@@ -751,6 +773,7 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
$("downloadDir").value = data.download_dir;
|
||||
$("configMode").value = data.mode;
|
||||
$("configQuality").value = data.quality;
|
||||
$("anipyCliFallbackEnabled").value = String(Boolean(data.anipy_cli_fallback_enabled));
|
||||
$("watchlistAutoRefreshEnabled").value = String(Boolean(data.watchlist_auto_refresh_enabled));
|
||||
$("watchlistAutoRefreshMinutes").value = data.watchlist_auto_refresh_minutes;
|
||||
$("watchlistRefreshDelaySeconds").value = data.watchlist_refresh_delay_seconds;
|
||||
@@ -960,6 +983,7 @@ CONFIG_HTML = r"""<!doctype html>
|
||||
const data = await api("/api/version");
|
||||
$("versionLine").textContent = `${data.name} ${data.version}`;
|
||||
$("aniCliVersionLine").textContent = `ani-cli ${data.ani_cli_version || "Unavailable"}`;
|
||||
$("anipyCliVersionLine").textContent = `anipy-cli ${data.anipy_cli_version || "Unavailable"}`;
|
||||
}
|
||||
|
||||
async function openChangelog() {
|
||||
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 2.3 KiB |
+104
-6
@@ -21,17 +21,20 @@ from urllib.parse import parse_qs, unquote, urlencode, urlparse, urlunparse
|
||||
|
||||
from app_support import (
|
||||
ANI_CLI,
|
||||
ANIPY_CLI,
|
||||
APP_NAME,
|
||||
CHANGELOG_FILE,
|
||||
CLIENT_DISCONNECT_ERRORS,
|
||||
MAX_JSON_BODY_BYTES,
|
||||
MODE_CHOICES,
|
||||
PROJECT_ROOT,
|
||||
VERSION,
|
||||
client_address_is_local,
|
||||
configured_remote_path_roots,
|
||||
debug_enabled,
|
||||
debug_log,
|
||||
load_project_text_file,
|
||||
cli_executable_exists,
|
||||
normalize_config,
|
||||
path_is_within_roots,
|
||||
remote_access_allowed,
|
||||
@@ -44,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
|
||||
@@ -87,7 +92,8 @@ def build_handler_class(context):
|
||||
def dependency_status():
|
||||
checks = ["curl", "sed", "grep", "openssl", "fzf", "aria2c", "ffmpeg", "yt-dlp"]
|
||||
result = {name: bool(shutil.which(name)) for name in checks}
|
||||
result["ani-cli"] = bool(shutil.which(ANI_CLI) or (Path(ANI_CLI).exists() and os.access(ANI_CLI, os.X_OK)))
|
||||
result["ani-cli"] = cli_executable_exists(ANI_CLI)
|
||||
result["anipy-cli"] = cli_executable_exists(ANIPY_CLI)
|
||||
return result
|
||||
|
||||
|
||||
@@ -150,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:
|
||||
@@ -166,6 +232,22 @@ def installed_ani_cli_version():
|
||||
return version or "Unavailable"
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def installed_anipy_cli_version():
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
[ANIPY_CLI, "--version"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=6,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return "Unavailable"
|
||||
version = str(completed.stdout or completed.stderr or "").strip()
|
||||
return version or "Unavailable"
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "AniCliWeb/1.0"
|
||||
remote_session_cookie_name = "ani_cli_web_session"
|
||||
@@ -363,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;
|
||||
@@ -526,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":
|
||||
@@ -535,7 +623,14 @@ class Handler(BaseHTTPRequestHandler):
|
||||
elif parsed.path == "/api/config":
|
||||
self.json(sanitize_public_config(Handler._context(self).get_config_snapshot()))
|
||||
elif parsed.path == "/api/version":
|
||||
self.json({"name": APP_NAME, "version": VERSION, "ani_cli_version": installed_ani_cli_version()})
|
||||
self.json(
|
||||
{
|
||||
"name": APP_NAME,
|
||||
"version": VERSION,
|
||||
"ani_cli_version": installed_ani_cli_version(),
|
||||
"anipy_cli_version": installed_anipy_cli_version(),
|
||||
}
|
||||
)
|
||||
elif parsed.path == "/api/changelog":
|
||||
self.json({"content": load_project_text_file(CHANGELOG_FILE, default="Changelog unavailable.")})
|
||||
elif parsed.path == "/api/dependencies":
|
||||
@@ -584,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("/")
|
||||
@@ -592,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()
|
||||
@@ -677,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("/")
|
||||
@@ -688,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")
|
||||
|
||||
+230
-30
@@ -13,12 +13,14 @@ import time
|
||||
import re
|
||||
|
||||
from app_support import (
|
||||
ANIPY_CLI,
|
||||
MAX_LOG_LINES,
|
||||
PROJECT_ROOT,
|
||||
QUEUE_PATH,
|
||||
STATE_DB_PATH,
|
||||
WORKER_SHUTDOWN_TIMEOUT_SECONDS,
|
||||
build_job,
|
||||
cli_executable_exists,
|
||||
command_for_job,
|
||||
debug_log,
|
||||
finalize_library_files,
|
||||
@@ -645,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:
|
||||
@@ -1134,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:
|
||||
@@ -1141,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
|
||||
@@ -1219,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
|
||||
|
||||
@@ -1289,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()
|
||||
@@ -1373,6 +1489,36 @@ class DownloadQueue:
|
||||
self._save_job_locked(job)
|
||||
self._cleanup_staging_dir(job)
|
||||
|
||||
def _command_attempts(self, job, staging_dir):
|
||||
config = normalize_config(self.config_getter() or {})
|
||||
attempts = [
|
||||
{
|
||||
"backend": "ani-cli",
|
||||
"command": command_for_job(job, backend="ani-cli"),
|
||||
"env": {
|
||||
**os.environ.copy(),
|
||||
"ANI_CLI_DOWNLOAD_DIR": str(staging_dir),
|
||||
"ANI_CLI_MODE": job["mode"],
|
||||
"ANI_CLI_QUALITY": job["quality"],
|
||||
"TERM": os.environ.get("TERM", "xterm-256color"),
|
||||
},
|
||||
}
|
||||
]
|
||||
fallback_enabled = bool(config.get("anipy_cli_fallback_enabled"))
|
||||
fallback_available = cli_executable_exists(ANIPY_CLI)
|
||||
if fallback_enabled and fallback_available:
|
||||
attempts.append(
|
||||
{
|
||||
"backend": "anipy-cli",
|
||||
"command": command_for_job(job, backend="anipy-cli", download_path=staging_dir),
|
||||
"env": {
|
||||
**os.environ.copy(),
|
||||
"TERM": os.environ.get("TERM", "xterm-256color"),
|
||||
},
|
||||
}
|
||||
)
|
||||
return attempts, fallback_enabled, fallback_available
|
||||
|
||||
def _run(self):
|
||||
while not self.stop_event.is_set():
|
||||
job = self._next_pending()
|
||||
@@ -1383,42 +1529,62 @@ class DownloadQueue:
|
||||
self._run_job(job)
|
||||
|
||||
def _run_job(self, job):
|
||||
command = command_for_job(job)
|
||||
staging_dir = job_staging_dir(job)
|
||||
target_dir = job_output_dir(job)
|
||||
env = os.environ.copy()
|
||||
env.update(
|
||||
{
|
||||
"ANI_CLI_DOWNLOAD_DIR": str(staging_dir),
|
||||
"ANI_CLI_MODE": job["mode"],
|
||||
"ANI_CLI_QUALITY": job["quality"],
|
||||
"TERM": env.get("TERM", "xterm-256color"),
|
||||
}
|
||||
)
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
attempts, fallback_enabled, fallback_available = self._command_attempts(job, staging_dir)
|
||||
primary_command = attempts[0]["command"]
|
||||
|
||||
with self.lock:
|
||||
job["status"] = "running"
|
||||
job["started_at"] = now_iso()
|
||||
job["updated_at"] = job["started_at"]
|
||||
job["command"] = printable_command(command)
|
||||
job["command"] = printable_command(primary_command)
|
||||
job["staging_dir"] = str(staging_dir)
|
||||
job["target_dir"] = str(target_dir)
|
||||
job["download_backend"] = "ani-cli"
|
||||
job["fallback_used"] = False
|
||||
job["log"] = [
|
||||
f"Starting: {job['command']}",
|
||||
f"Staging in: {job['staging_dir']}",
|
||||
f"Final folder: {job['target_dir']}",
|
||||
]
|
||||
if fallback_enabled and fallback_available:
|
||||
job["log"].append("anipy-cli fallback is enabled and will retry automatically if ani-cli fails.")
|
||||
elif fallback_enabled:
|
||||
job["log"].append("anipy-cli fallback is enabled, but anipy-cli is not installed or not executable.")
|
||||
job["cancel_requested"] = False
|
||||
job["_dirty_log_lines"] = 0
|
||||
self._save_job_locked(job)
|
||||
|
||||
try:
|
||||
exit_code = 1
|
||||
successful_backend = None
|
||||
finalize_error = None
|
||||
moved_files = []
|
||||
watchlist_sync_error = None
|
||||
synced_watchlist_item = None
|
||||
cleanup_staging = False
|
||||
for index, attempt in enumerate(attempts):
|
||||
backend = attempt["backend"]
|
||||
command = attempt["command"]
|
||||
should_fallback = index + 1 < len(attempts)
|
||||
with self.lock:
|
||||
job["download_backend"] = backend
|
||||
job["command"] = printable_command(command)
|
||||
if index > 0:
|
||||
job["fallback_used"] = True
|
||||
job["pid"] = None
|
||||
job["updated_at"] = now_iso()
|
||||
if index > 0:
|
||||
job.setdefault("log", []).append(f"Retrying with {backend}: {job['command']}")
|
||||
self._save_job_locked(job)
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
cwd=str(PROJECT_ROOT),
|
||||
env=env,
|
||||
env=attempt["env"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
@@ -1426,6 +1592,12 @@ class DownloadQueue:
|
||||
start_new_session=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
if should_fallback:
|
||||
self._append_log(job, f"ani-cli could not start: {exc}")
|
||||
self._append_log(job, "Retrying with anipy-cli fallback.")
|
||||
self._cleanup_staging_dir(job)
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
continue
|
||||
self._fail_job_startup(job, exc)
|
||||
return
|
||||
with self.lock:
|
||||
@@ -1435,27 +1607,51 @@ class DownloadQueue:
|
||||
job["pid"] = process.pid
|
||||
self._save_job_locked(job)
|
||||
|
||||
try:
|
||||
assert process.stdout is not None
|
||||
for line in process.stdout:
|
||||
self._append_log(job, line)
|
||||
exit_code = process.wait()
|
||||
finalize_error = None
|
||||
moved_files = []
|
||||
watchlist_sync_error = None
|
||||
synced_watchlist_item = None
|
||||
cleanup_staging = False
|
||||
if exit_code == 0 and not job.get("cancel_requested"):
|
||||
with self.lock:
|
||||
job["pid"] = None
|
||||
self.current_process = None
|
||||
self.current_job_id = None
|
||||
self.current_job = None
|
||||
self._save_job_locked(job)
|
||||
|
||||
if job.get("cancel_requested"):
|
||||
break
|
||||
|
||||
if backend == "ani-cli" and exit_code != 0 and should_fallback:
|
||||
self._append_log(job, f"ani-cli failed with exit code {exit_code}.")
|
||||
self._append_log(job, "Retrying with anipy-cli fallback.")
|
||||
self._cleanup_staging_dir(job)
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
continue
|
||||
|
||||
if exit_code == 0:
|
||||
try:
|
||||
moved_files = finalize_library_files(job)
|
||||
except Exception as exc:
|
||||
finalize_error = exc
|
||||
no_files_downloaded = "No downloaded files were found in the staging folder" in str(exc)
|
||||
if backend == "ani-cli" and no_files_downloaded and should_fallback:
|
||||
self._append_log(
|
||||
job,
|
||||
"ani-cli exited without downloading any files. Retrying with anipy-cli fallback.",
|
||||
)
|
||||
self._cleanup_staging_dir(job)
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
finalize_error = None
|
||||
continue
|
||||
else:
|
||||
successful_backend = backend
|
||||
if self.watchlist_sync_fn is not None:
|
||||
try:
|
||||
synced_watchlist_item = self.watchlist_sync_fn(job)
|
||||
except Exception as exc:
|
||||
watchlist_sync_error = exc
|
||||
break
|
||||
break
|
||||
|
||||
with self.lock:
|
||||
canceled = job.get("cancel_requested")
|
||||
@@ -1471,13 +1667,15 @@ class DownloadQueue:
|
||||
message = str(finalize_error).strip()
|
||||
if "No downloaded files were found in the staging folder" in message:
|
||||
job.setdefault("log", []).append(
|
||||
"ani-cli exited without downloading any files. The selected result or episodes may not be downloadable."
|
||||
f"{job.get('download_backend') or 'Downloader'} exited without downloading any files. The selected result or episodes may not be downloadable."
|
||||
)
|
||||
else:
|
||||
job.setdefault("log", []).append(f"Library rename failed: {finalize_error}")
|
||||
cleanup_staging = True
|
||||
elif exit_code == 0:
|
||||
job["status"] = "done"
|
||||
if successful_backend == "anipy-cli":
|
||||
job.setdefault("log", []).append("Fallback download completed with anipy-cli.")
|
||||
for path in moved_files:
|
||||
job.setdefault("log", []).append(f"Saved: {path}")
|
||||
job.setdefault("log", []).append("Download completed.")
|
||||
@@ -1490,7 +1688,9 @@ class DownloadQueue:
|
||||
job.setdefault("log", []).append("Watchlist download state synced.")
|
||||
else:
|
||||
job["status"] = "failed"
|
||||
job.setdefault("log", []).append(f"Download failed with exit code {exit_code}.")
|
||||
job.setdefault("log", []).append(
|
||||
f"{job.get('download_backend') or 'Download'} failed with exit code {exit_code}."
|
||||
)
|
||||
cleanup_staging = True
|
||||
if canceled:
|
||||
cleanup_staging = True
|
||||
|
||||
+18
-2
@@ -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() {
|
||||
|
||||
@@ -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;
|
||||
|
||||
+312
-2
@@ -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(
|
||||
{
|
||||
@@ -589,6 +749,36 @@ class QueueApiTests(unittest.TestCase):
|
||||
self.assertTrue(Path(moved[0]).exists())
|
||||
self.assertTrue(Path(moved[1]).exists())
|
||||
|
||||
def test_tv_finalizer_uses_requested_episode_numbers_for_anipy_fallback(self):
|
||||
with tempfile.TemporaryDirectory() as temp_root:
|
||||
job = APP.app_support.build_job(
|
||||
{
|
||||
"query": "Fallback Show",
|
||||
"title": "Fallback Show",
|
||||
"anime_name": "Fallback Show",
|
||||
"media_type": "tv",
|
||||
"mode": "sub",
|
||||
"quality": "best",
|
||||
"episodes": "11",
|
||||
"download_dir": temp_root,
|
||||
"season": "2",
|
||||
},
|
||||
{"mode": "sub", "quality": "best", "download_dir": temp_root},
|
||||
)
|
||||
job["download_backend"] = "anipy-cli"
|
||||
staging_dir = APP.app_support.job_staging_dir(job)
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
source = staging_dir / "Fallback Show - S02E01.mp4"
|
||||
source.write_bytes(b"fallback")
|
||||
|
||||
moved = APP.app_support.finalize_library_files(job)
|
||||
|
||||
self.assertEqual(
|
||||
moved,
|
||||
[f"{temp_root}/tv/Fallback Show/Season 02/Fallback Show - S02E11.mp4"],
|
||||
)
|
||||
self.assertTrue(Path(moved[0]).exists())
|
||||
|
||||
def test_shutdown_wait_cancels_active_process_for_deterministic_teardown(self):
|
||||
queue = object.__new__(APP.DownloadQueue)
|
||||
queue.lock = threading.RLock()
|
||||
@@ -771,6 +961,51 @@ class DownloadQueueWorkerFailureTests(unittest.TestCase):
|
||||
self.assertIn("Watchlist sync skipped for detached job.", stored["log"])
|
||||
self.assertNotIn("Watchlist download state synced.", stored["log"])
|
||||
|
||||
def test_failed_ani_cli_retries_with_anipy_when_enabled(self):
|
||||
queue = APP.DownloadQueue(
|
||||
lambda: {
|
||||
"mode": "sub",
|
||||
"quality": "best",
|
||||
"download_dir": "/tmp/example",
|
||||
"anipy_cli_fallback_enabled": True,
|
||||
},
|
||||
start_worker=False,
|
||||
)
|
||||
job = queue.add({"query": "Queue Show", "title": "Queue Show", "season": "1", "episodes": "1"})
|
||||
commands = []
|
||||
|
||||
class FakeProc:
|
||||
def __init__(self, pid, stdout, exit_code):
|
||||
self.pid = pid
|
||||
self.stdout = stdout
|
||||
self._exit_code = exit_code
|
||||
|
||||
def wait(self):
|
||||
return self._exit_code
|
||||
|
||||
processes = [
|
||||
FakeProc(4321, ["ani-cli attempt\n"], 1),
|
||||
FakeProc(5432, ["anipy-cli attempt\n"], 0),
|
||||
]
|
||||
|
||||
def fake_popen(command, **kwargs):
|
||||
commands.append(command)
|
||||
return processes.pop(0)
|
||||
|
||||
with mock.patch.object(queue_jobs, "cli_executable_exists", return_value=True), mock.patch.object(
|
||||
queue_jobs.subprocess, "Popen", side_effect=fake_popen
|
||||
), mock.patch.object(
|
||||
queue_jobs, "finalize_library_files", return_value=["/tmp/example/Queue Show - S01E01.mp4"]
|
||||
):
|
||||
queue._run_job(job)
|
||||
|
||||
stored = queue._find(job["id"])
|
||||
self.assertEqual(stored["status"], "done")
|
||||
self.assertTrue(stored["fallback_used"])
|
||||
self.assertEqual(commands[0][0], APP.app_support.ANI_CLI)
|
||||
self.assertEqual(commands[1][0], APP.app_support.ANIPY_CLI)
|
||||
self.assertIn("Fallback download completed with anipy-cli.", stored["log"])
|
||||
|
||||
|
||||
class WatchlistRefreshAllTests(unittest.TestCase):
|
||||
def test_refresh_all_iterates_only_watching_and_planned_show_ids(self):
|
||||
@@ -1597,6 +1832,23 @@ class WatchlistCompletionTests(unittest.TestCase):
|
||||
|
||||
self.assertNotIn("-S", command)
|
||||
|
||||
def test_command_for_job_builds_anipy_fallback_search_spec(self):
|
||||
command = APP.app_support.command_for_job(
|
||||
{
|
||||
"query": "Re:Zero",
|
||||
"quality": "720",
|
||||
"episodes": "1-3",
|
||||
"mode": "dub",
|
||||
},
|
||||
backend="anipy-cli",
|
||||
download_path="/tmp/anipy-staging",
|
||||
)
|
||||
|
||||
self.assertEqual(command[0], APP.app_support.ANIPY_CLI)
|
||||
self.assertEqual(command[1:5], ["-D", "-s", "Re Zero:1-3:dub", "-q"])
|
||||
self.assertIn("-l", command)
|
||||
self.assertEqual(command[-1], "/tmp/anipy-staging")
|
||||
|
||||
def test_download_watchlist_item_queues_full_episode_range_for_selected_mode(self):
|
||||
item = {
|
||||
"show_id": "show-42",
|
||||
@@ -2077,6 +2329,7 @@ class ConfigSnapshotTests(unittest.TestCase):
|
||||
self.assertFalse(config["watchlist_auto_refresh_enabled"])
|
||||
self.assertEqual(config["watchlist_auto_refresh_minutes"], 60)
|
||||
self.assertEqual(config["watchlist_refresh_delay_seconds"], 5)
|
||||
self.assertFalse(config["anipy_cli_fallback_enabled"])
|
||||
self.assertFalse(config["auto_download_enabled"])
|
||||
self.assertEqual(config["auto_download_mode"], "dub")
|
||||
self.assertEqual(config["auto_download_quality"], "best")
|
||||
@@ -2089,6 +2342,7 @@ class ConfigSnapshotTests(unittest.TestCase):
|
||||
def test_normalize_config_parses_watchlist_schedule_fields(self):
|
||||
config = APP.normalize_config(
|
||||
{
|
||||
"anipy_cli_fallback_enabled": "true",
|
||||
"watchlist_auto_refresh_enabled": "true",
|
||||
"watchlist_auto_refresh_minutes": "15",
|
||||
"watchlist_refresh_delay_seconds": "7",
|
||||
@@ -2100,6 +2354,7 @@ class ConfigSnapshotTests(unittest.TestCase):
|
||||
"jellyfin_movie_dir": "~/jellyfin/movies",
|
||||
}
|
||||
)
|
||||
self.assertTrue(config["anipy_cli_fallback_enabled"])
|
||||
self.assertTrue(config["watchlist_auto_refresh_enabled"])
|
||||
self.assertEqual(config["watchlist_auto_refresh_minutes"], 15)
|
||||
self.assertEqual(config["watchlist_refresh_delay_seconds"], 7)
|
||||
@@ -2692,10 +2947,11 @@ class HandlerRouteTests(unittest.TestCase):
|
||||
APP.initialize_runtime(start_workers=False)
|
||||
|
||||
def test_config_post_accepts_watchlist_schedule_fields(self):
|
||||
body = b'{"download_dir":"/tmp/example","mode":"sub","quality":"best","watchlist_auto_refresh_enabled":true,"watchlist_auto_refresh_minutes":"25","watchlist_refresh_delay_seconds":"9","auto_download_enabled":true,"auto_download_mode":"dub","auto_download_quality":"720","jellyfin_sync_enabled":true,"jellyfin_tv_dir":"/tmp/jellyfin-tv","jellyfin_movie_dir":"/tmp/jellyfin-movies"}'
|
||||
body = b'{"download_dir":"/tmp/example","mode":"sub","quality":"best","anipy_cli_fallback_enabled":true,"watchlist_auto_refresh_enabled":true,"watchlist_auto_refresh_minutes":"25","watchlist_refresh_delay_seconds":"9","auto_download_enabled":true,"auto_download_mode":"dub","auto_download_quality":"720","jellyfin_sync_enabled":true,"jellyfin_tv_dir":"/tmp/jellyfin-tv","jellyfin_movie_dir":"/tmp/jellyfin-movies"}'
|
||||
handler = DummyHandler("/api/config", body=body, content_length=len(body))
|
||||
APP.Handler.do_POST(handler)
|
||||
self.assertEqual(handler.json_status, HTTPStatus.OK)
|
||||
self.assertTrue(handler.json_payload["anipy_cli_fallback_enabled"])
|
||||
self.assertTrue(handler.json_payload["watchlist_auto_refresh_enabled"])
|
||||
self.assertEqual(handler.json_payload["watchlist_auto_refresh_minutes"], 25)
|
||||
self.assertEqual(handler.json_payload["watchlist_refresh_delay_seconds"], 9)
|
||||
@@ -2706,13 +2962,47 @@ class HandlerRouteTests(unittest.TestCase):
|
||||
self.assertEqual(handler.json_payload["jellyfin_tv_dir"], "/tmp/jellyfin-tv")
|
||||
self.assertEqual(handler.json_payload["jellyfin_movie_dir"], "/tmp/jellyfin-movies")
|
||||
|
||||
def test_version_route_includes_ani_cli_version(self):
|
||||
def test_version_route_includes_cli_versions(self):
|
||||
handler = DummyHandler("/api/version")
|
||||
APP.Handler.do_GET(handler)
|
||||
self.assertEqual(handler.json_status, HTTPStatus.OK)
|
||||
self.assertEqual(handler.json_payload["name"], APP.APP_NAME)
|
||||
self.assertEqual(handler.json_payload["version"], APP.VERSION)
|
||||
self.assertIn("ani_cli_version", handler.json_payload)
|
||||
self.assertIn("anipy_cli_version", handler.json_payload)
|
||||
|
||||
def test_dependencies_route_reports_anipy_cli_status(self):
|
||||
handler = DummyHandler("/api/dependencies")
|
||||
APP.Handler.do_GET(handler)
|
||||
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")
|
||||
@@ -3237,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)
|
||||
@@ -3244,7 +3541,10 @@ class TemplateHelperTests(unittest.TestCase):
|
||||
self.assertIn("@media (max-width: 1080px)", APP.CONFIG_HTML)
|
||||
self.assertIn("justify-items: stretch;", APP.CONFIG_HTML)
|
||||
self.assertIn('id="aniCliVersionLine"', APP.CONFIG_HTML)
|
||||
self.assertIn('id="anipyCliVersionLine"', APP.CONFIG_HTML)
|
||||
self.assertIn('ani-cli ${data.ani_cli_version || "Unavailable"}', APP.CONFIG_HTML)
|
||||
self.assertIn('anipy-cli ${data.anipy_cli_version || "Unavailable"}', APP.CONFIG_HTML)
|
||||
self.assertIn('id="anipyCliFallbackEnabled"', APP.CONFIG_HTML)
|
||||
self.assertIn('id="openChangelogBtn"', APP.CONFIG_HTML)
|
||||
self.assertIn('id="changelogOverlay"', APP.CONFIG_HTML)
|
||||
self.assertIn('const data = await api("/api/changelog");', APP.CONFIG_HTML)
|
||||
@@ -3260,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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user