"""Manage endpoints and authentication for Zimi. Handles /manage/* routes: library status, downloads, catalog, settings, history, stats, and admin authentication. Called from ZimHandler in http.py. """ import functools import hashlib import hmac import ipaddress import json import logging import os import re import shlex import sys import secrets import threading import time import urllib.parse import urllib.request from datetime import datetime, timezone import zimi.server as _srv from zimi import libfolders, nomadapi, outbound from zimi.safety import join_inside, loggable log = logging.getLogger("zimi") # ============================================================================ # Password & Authentication # ============================================================================ _PW_ITERATIONS = 600_000 # OWASP 2023 recommendation for PBKDF2-SHA256 def _hash_pw(pw, salt=None): """Hash password with PBKDF2-SHA256 + random salt. Returns 'salt$hash'.""" if salt is None: salt = os.urandom(16) else: salt = bytes.fromhex(salt) dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt, _PW_ITERATIONS) return salt.hex() + "$" + dk.hex() def _is_legacy_hash(stored): """Check if stored hash is a v1.5 unsalted SHA-256 hex string.""" return stored and "$" not in stored and len(stored) == 64 def _verify_legacy(candidate, stored): """Verify a password against a v1.5 unsalted SHA-256 hash.""" legacy = hashlib.sha256(candidate.encode()).hexdigest() return hmac.compare_digest(legacy, stored) def _upgrade_legacy_hash(candidate): """Re-hash a verified password from v1.5 format to PBKDF2. Called after successful legacy verification to transparently migrate the password file. Best-effort: on read-only media the write fails soft and the legacy hash simply keeps verifying on every login — migration retries next time.""" if _set_manage_password(candidate): log.info("Migrated password from v1.5 SHA-256 to PBKDF2") def _atomic_write_text(path, content): """Write a small credential file via tmp + os.replace. True on success. Same error discipline as server._atomic_write_json: never raises. These were the last two write paths that threw a traceback on read-only media — the HTTP callers turn a False into a generic 500 JSON, and the real OSError stays in the server log (repo rule: no str(e) in responses).""" tmp = path + ".tmp" try: # 0600 from creation, whatever the umask: these are credentials. fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(content) os.replace(tmp, path) return True except OSError as e: log.warning("Cannot write %s: %s", path, e) try: os.remove(tmp) except OSError: pass return False _env_pw_hash_cache = None # cached hash for ZIMI_MANAGE_PASSWORD env var # Where libtorrent publishes a wheel. Kept in step with the marker in # pyproject.toml, and lowercase because platform.machine() is not: it says # AMD64 on Windows and x86_64 on everything else that means the same thing. _BT_WHEEL_ARCHES = ("x86_64", "amd64", "aarch64", "arm64", "x86") def _password_file(): return os.path.join(_srv.ZIMI_DATA_DIR, "password") def _get_manage_password_hash(): """Get password hash from env var or file. The password file holds the hash on its first line; an OPTIONAL username may follow on the second line (see _file_username). Only the first line is the hash, so legacy single-line files keep working unchanged.""" global _env_pw_hash_cache # Env var takes priority (Docker deployments) pw = os.environ.get("ZIMI_MANAGE_PASSWORD", "") if pw: if _env_pw_hash_cache is None: _env_pw_hash_cache = _hash_pw(pw) return _env_pw_hash_cache # Fall back to password file (set via UI) try: with open(_password_file(), encoding="utf-8") as f: stored = f.readline().strip() # first line only — line 2 is username # Empty or too-short to be a valid hash — treat as no password if not stored or len(stored) < 10: return "" return stored except (FileNotFoundError, OSError): return "" def _file_username(): """Optional username stored on the second line of the password file, or ''. A plain identifier (not a secret) — legacy files have no second line and return ''. Env var ZIMI_MANAGE_USER (see _get_manage_user) overrides this.""" try: with open(_password_file(), encoding="utf-8") as f: lines = f.read().split("\n") if len(lines) >= 2: return lines[1].strip() except (FileNotFoundError, OSError): pass return "" def _get_manage_user(): """Configured management username, or '' if none. Env var wins over file. OPTIONAL: when '' the login accepts any username (pure keychain UX); when set, the login username must match it case-insensitively. Original case is preserved for display; matching is done case-folded by callers.""" env_user = os.environ.get("ZIMI_MANAGE_USER", "").strip() if env_user: return env_user return _file_username() def _set_manage_password(pw, username=None): """Save hashed password to file (line 1) with an optional username (line 2), or clear the file. Uses atomic write. username semantics: None preserves whatever username the file already had (so a plain password change never wipes it); '' clears it; a non-empty string sets it. Clearing the password (pw falsy) clears username too. Returns True on success, False when the file cannot be written (read-only media) — in which case nothing below (session drop, log) happens either, because the old password is still the one in force.""" pf = _password_file() if not pw: content = "" # cleared — no hash, no username else: if username is None: username = _file_username() # preserve existing on a bare pw change content = _hash_pw(pw) if username and username.strip(): content += "\n" + username.strip() if not _atomic_write_text(pf, content): return False # A password rotation must revoke old admin session cookies immediately (the # pre-cookie model, where the Bearer WAS the password, did so implicitly). The # rotating admin's own Bearer still authenticates and /whoami re-mints a fresh # cookie, so this never locks out the person making the change. try: from zimi import users as _users _users.drop_admin_sessions() except Exception: pass log.info("Manage password %s", "set" if pw else "cleared") return True # ── first-run setup key (GHSA-5mw2-53vv-9pw6) ─────────────────────────────── # # Bootstrap trust used to be "any private-tier client sets the first admin # password". On a LAN, a Docker bridge, or a tailnet that is too many hands: # an adjacent device could race the owner to claim admin. The fix splits the # bootstrap door in two — the HOST itself (loopback) needs no secret, and any # REMOTE client must present this setup key, which the server generates on # first start and prints to its own log. No third door: LAN and tailnet peers # without the key get the same locked response a public client does. def _setup_key_file(): return os.path.join(_srv.ZIMI_DATA_DIR, "setup-key") def _read_setup_key(): try: with open(_setup_key_file(), encoding="utf-8") as f: return f.readline().strip() except (FileNotFoundError, OSError): return "" def ensure_setup_key(): """Guarantee a setup key exists while the instance is passwordless, and return it. A no-op (returns '') once a password is set — the key's whole life is the bootstrap window. Idempotent: the same key persists across restarts until it is spent, so a printed code stays valid.""" if _get_manage_password_hash(): return "" existing = _read_setup_key() if existing: return existing key = "-".join( secrets.token_hex(2).upper() for _ in range(3) ) # e.g. 7Q2K-9F4M-XR8T shape, from a real CSPRNG # 0600, best-effort: a key only the server and root can read. _atomic_write_text(_setup_key_file(), key + "\n") try: os.chmod(_setup_key_file(), 0o600) except OSError: pass return key def _clear_setup_key(): try: os.remove(_setup_key_file()) except (FileNotFoundError, OSError): pass def manage_open(): """Whether the operator has turned management authentication off. The one answer to "I do not want a password" that does not reason about network position. Every other one does, and that is what has failed twice: a LAN rule cannot see a client behind a reverse proxy, and a proxy rule cannot tell that client from the internet. This asks nothing, so there is nothing to get wrong. The environment (or config file, published into it at startup) wins when set; else the password switched off in Settings (_handle_access). Read on each call so a test's value and a Settings change both land; the prefs read is the cached one manage_external already pays for.""" env = manage_open_env() if env is not None: return env if _read_app_update_prefs().get("manage_open") is not True: return False # Set in Settings, it gives way to an environment set since that forbids # it (a password there, outside access off, the LAN not trusted), and is # cleared, so removing that variable later does not quietly reopen it. if _open_env_forbids(): _write_app_update_prefs(manage_open=False) return False return True def _open_env_forbids(): return bool( os.environ.get("ZIMI_MANAGE_PASSWORD", "") or _env_flag("ZIMI_MANAGE_EXTERNAL") is False or _lan_admin_env() is False ) def open_from_settings(): """The password switched off in Settings (not by ZIMI_MANAGE_OPEN): while it is on, nothing that outlives it can be made (an API token, an account, a password), and the BitTorrent client and private captures are fenced.""" return manage_open() and not manage_open_env() def manage_open_env(): """ZIMI_MANAGE_OPEN when someone set it, else None. Set either way, it locks the Settings switch.""" return _env_flag("ZIMI_MANAGE_OPEN") def _lan_client(handler): """A client `lan_admin` may treat as the owner: on the private network and reaching Zimi directly. Not simply `_is_private_client`. Behind a reverse proxy on the same host the resolved address falls back to the proxy's own loopback one, so every client of that proxy resolves as private no matter where on the internet it came from — and `lan_admin` would hand each of them the admin of a passwordless instance. The setting says the LAN is the boundary; this is that sentence, asked exactly.""" direct = getattr(handler, "_is_direct_private_client", None) return bool(direct() if direct else handler._is_private_client()) def _env_flag(name): """A boolean env var (or config-file setting, published into the environment at startup) when someone set it, else None.""" raw = os.environ.get(name) if raw is None: return None return raw.strip().lower() in ("1", "true", "yes", "on") def _lan_admin_env(): return _env_flag("ZIMI_LAN_ADMIN") def _lan_admin_allowed(): """Whether the operator has said their LAN is their trust boundary. The env var or config file when set; else the first-run choice "Anyone on my network" (/manage/access), which only the host or the setup key's holder can make: the same two doors GHSA-5mw2-53vv-9pw6 left for the first password, so no adjacent device can make it for them. Read fresh rather than cached at import: `zimi config` publishes file settings into the environment at startup, and a test that sets it wants it to take effect.""" env = _lan_admin_env() if env is not None: return env return _read_app_update_prefs().get("lan_admin") is True def access_mode(): """Who may change settings: open (ZIMI_MANAGE_OPEN), password, lan (anyone directly on the network), or unset (first run: the host, or the setup key, decides).""" if manage_open(): return "open" if _get_manage_password_hash(): return "password" return "lan" if _lan_admin_allowed() else "unset" def manage_external(): """Whether settings may be changed from outside the private network. ZIMI_MANAGE_EXTERNAL (config manage_external) when set, else on. The page no longer asks: a wall drawn by where a request seems to come from locked owners out behind their own proxies, and the password is the wall. A saved answer from the old switch is not read. Without a password it means nothing: `lan` and `unset` keep the outside out on their own.""" env = _env_flag("ZIMI_MANAGE_EXTERNAL") return True if env is None else env def settings_reachable(handler): """False for a client outside the network when the owner said settings stay inside it. Asked of the resolved client, so the LAN behind a reverse proxy is inside and a Cloudflare visitor is not. A wall on top of the password, never instead of it: a proxy that strips every forwarding header still leaves the password to pass.""" return manage_open() or handler._is_private_client() or manage_external() # A fresh self-hosted install is unusable until its owner has answered the # setup page (who can change settings). Held in memory: every request asks. _setup_gate = False def setup_pending(): return _setup_gate def init_setup_gate(host, ran_before=False): """At `zimi serve` start, before the setup key is made. Gates a FRESH install (nothing in its data dir yet) that other devices can reach and whose environment does not already answer the question. An install that ran before never gets the gate: its readers keep reading, and a passwordless one is offered the page in Settings instead. ``ran_before`` is the caller's word that a metadata cache existed before this start's first scan wrote one: all an old passwordless install that never opened settings leaves behind (`zimi serve` asks before load_cache).""" global _setup_gate prefs = _read_app_update_prefs() if "setup_gate" in prefs: _setup_gate = bool(prefs["setup_gate"]) and access_mode() == "unset" return _setup_gate from zimi import users as _users seen = ( _setup_key_file(), _password_file(), _app_update_prefs_path(), _users._users_path(), ) fresh = not ran_before and not any(os.path.exists(p) for p in seen) loopback = host in ("localhost", "::1") or host.startswith("127.") _setup_gate = fresh and not loopback and access_mode() == "unset" if _setup_gate: _write_app_update_prefs(setup_gate=True, setup_started=time.time()) log.info("First-run setup: Zimi opens once its owner chooses who can manage it") return _setup_gate def _end_setup_gate(): global _setup_gate _setup_gate = False if "setup_gate" in _read_app_update_prefs(): _write_app_update_prefs(setup_gate=False) # The home networks a fresh install's setup page may be answered from without # the setup key: 10/8, 192.168/16 and IPv6 ULA. Not 172.16/12 (Docker's bridge # networks live there, and a neighbouring container is the advisory's # attacker), not 100.64/10 (tailnets), not link-local, and not Tailscale's # IPv6 range inside ULA. FIRST_RUN_LAN_NETS = tuple( ipaddress.ip_network(n) for n in ("10.0.0.0/8", "192.168.0.0/16", "fc00::/7") ) FIRST_RUN_NOT_LAN = (ipaddress.ip_network("fd7a:115c:a1e0::/48"),) # How long after a fresh install's first start the home network may answer # its page without the key. A proxy that adds no header (nginx proxy_pass # alone, a TCP forward, ssh -R) makes the internet look like the LAN; the # window bounds what that can cost. Recorded once; a restart does not reset it. FIRST_RUN_LAN_SECONDS = 3600 def _first_run_lan_client(handler): """A device on the home network answering a fresh install's setup page. GHSA-5mw2-53vv-9pw6 was an install that worked unclaimed for good, so the first-password door stood open on the LAN for months. Since 1.13.1 a fresh install does nothing until its setup page is answered, so that door is open only between first start and the owner's first visit, as in every other self-hosted app, and the owner on their own network answers it without the key. Only while the page is up and for its first FIRST_RUN_LAN_SECONDS, only directly (no proxy in front), only from FIRST_RUN_LAN_NETS, and never from the server's own container networks (netguard.own_networks). An install that ran before the page existed never shows it, and its LAN still needs the key.""" from zimi import netguard if not _first_run_window_open() or netguard.orchestrated(): return False direct = getattr(handler, "_is_direct_private_client", None) if not direct or not direct(): return False peer = getattr(handler, "_socket_peer_ip", None) try: ip = ipaddress.ip_address(peer() if peer else handler.client_address[0]) except (ValueError, IndexError, TypeError): return False if ip.version == 6 and ip.ipv4_mapped: ip = ip.ipv4_mapped # A neighbouring container can sit inside a home-looking range (Docker # Desktop's networks are 192.168.x), so the server's own container # networks are never the home network. return ( any(ip in net for net in FIRST_RUN_LAN_NETS) and not any(ip in net for net in FIRST_RUN_NOT_LAN) and not netguard.on_own_network(ip) ) def _first_run_window_open(): """A fresh install's setup page is up, inside its first hour. The hour is recorded once, when a fresh data dir first starts; a page without it (an older build's) counts as expired.""" if not setup_pending(): return False started = _read_app_update_prefs().get("setup_started") return ( isinstance(started, (int, float)) and time.time() - started <= FIRST_RUN_LAN_SECONDS ) def _owner_proof(handler): """Who may act for the owner of a passwordless install: the host itself, the holder of the setup key, or the home network while the first-run page is up (_first_run_lan_client).""" # getattr fallback is for test doubles only: the real ZimHandler always # carries _is_loopback_client, so production always takes the strict # loopback path, and test_bootstrap_takeover pins that. is_local = getattr(handler, "_is_loopback_client", handler._is_private_client) return ( (_host_is_owner() and is_local()) or _bootstrap_key_ok(handler) or _first_run_lan_client(handler) ) def _host_is_owner(): """Whether the machine running Zimi proves ownership by being it. Always, except on a fresh install whose page has outlived its first hour: a proxy on the same host that adds no header (nginx proxy_pass alone, socat, ssh -R, a Funnel) makes the internet look like loopback, and whoever is really on the host can read the setup key from the log. An install without the page (the desktop app, one already set up) is unchanged.""" return not setup_pending() or _first_run_window_open() def _bootstrap_key_ok(handler): """True when a remote bootstrap request carries the valid setup key, in the Authorization: Bearer header or an X-Zimi-Setup-Key header. Constant- time compared. Absent key file (already spent) → nothing matches.""" want = _read_setup_key() if not want: return False got = (handler.headers.get("X-Zimi-Setup-Key") or "").strip() if not got: auth = handler.headers.get("Authorization") or "" if auth.lower().startswith("bearer "): got = auth[7:].strip() return bool(got) and hmac.compare_digest(got, want) def _api_token_file(): """API token file path inside ZIMI_DATA_DIR.""" return os.path.join(_srv.ZIMI_DATA_DIR, "api_token") def _get_api_token(): """Get stored API token (plaintext, for constant-time comparison).""" env_token = os.environ.get("ZIMI_API_TOKEN", "") if env_token: return env_token try: with open(_api_token_file(), encoding="utf-8") as f: return f.read().strip() except (FileNotFoundError, OSError): return "" def _generate_api_token(): """Generate a new random API token, save to disk, return it. Returns None when the token cannot be persisted (read-only media): a token handed out but not on disk would stop authenticating at the next restart, which is worse than a clean refusal now.""" import secrets token = secrets.token_urlsafe(32) if not _atomic_write_text(_api_token_file(), token): return None log.info("API token generated") return token def _revoke_api_token(): """Delete the API token file.""" try: os.remove(_api_token_file()) log.info("API token revoked") except FileNotFoundError: pass def _verify_pbkdf2(candidate, stored_pw): if not stored_pw or "$" not in stored_pw: return False salt = stored_pw.split("$")[0] return hmac.compare_digest(_hash_pw(candidate, salt), stored_pw) def _verify_password(candidate, stored_pw): """Verify a password against the stored hash. Handles legacy and PBKDF2.""" if _is_legacy_hash(stored_pw): if _verify_legacy(candidate, stored_pw): _upgrade_legacy_hash(candidate) return True return False return _verify_pbkdf2(candidate, stored_pw) def _verify_current(candidate, stored_pw): """The current password, asked again before a change. Only a PBKDF2 hash can answer: signing in already moved a v1.5 hash to PBKDF2, so the legacy check (and its SHA-256) stays on the sign-in path alone.""" return _verify_pbkdf2(candidate, stored_pw) def verify_admin_credentials(username, password): """Verify a (username, password) pair against the ADMIN account, header-free. Used by the unified /login endpoint so admin creds entered in the same modal as user creds still authenticate. Mirrors _check_manage_auth's password + optional-username gate, but takes explicit values instead of reading headers. Returns False on a passwordless instance (nothing to log into as admin). """ stored_pw = _get_manage_password_hash() if not stored_pw: return False if not _verify_password(password, stored_pw): return False configured_user = _get_manage_user() if configured_user: return (username or "").strip().casefold() == configured_user.strip().casefold() return True #: Returned by _check_manage_auth when the only reason a request is denied is #: that the instance has NO password and the client is non-private. There is no #: password to enter, so the UI must explain rather than prompt (see issue #36). PUBLIC_LOCKED = "public_locked" #: The refusal when a password exists but the owner keeps settings inside the #: network, and this client is outside it. No password would help, so the UI #: explains instead of prompting. OUTSIDE_LOCKED = "outside_network" def _primary_admin_authorized(handler): """True if the request carries PRIMARY-admin credentials: the password-file account (password hash or configured username+password) or the API token, OR a private client on a passwordless instance (legacy open admin). The primary admin is the top of the hierarchy — the only account that can manage other admins and that no secondary admin can delete or demote. """ if manage_open(): return True # everyone is the admin here, by the operator's choice stored_pw = _get_manage_password_hash() if not stored_pw: # Passwordless: the host itself, or any private client when the # operator has opted into trusting the LAN (see _lan_admin_allowed). if _lan_admin_allowed(): return _lan_client(handler) return _owner_proof(handler) # A primary-admin SESSION token (users.create_admin_session): minted when the # admin password verified, delivered as the HttpOnly zimi_session cookie so # header-less transports carry admin identity — the /w/ reader iframe (a # browser navigation that can't send Authorization) and the plain-fetch data # endpoints (/list, /search, …). Without this, a private/limited-mode admin # loads an EMPTY library and blank article iframes. Checked FIRST (before the # Bearer-format gate below) so a cookie-only request with no Authorization # header still resolves as admin. Accepted from either the cookie (browsers) # or the Bearer header (an API client may present it). As unforgeable as the # password Bearer: a random token, hashed at rest. from zimi import users as _users if _users.is_admin_session(_users._cookie_token(handler)): return True if _users.is_admin_session(_users._bearer_token(handler)): return True auth = handler.headers.get("Authorization", "") if not auth.startswith("Bearer "): return False candidate = auth[7:] # API token — a machine credential, carries no username gate (keeps # existing scripts/agents working unchanged). stored_token = _get_api_token() if stored_token and hmac.compare_digest(candidate, stored_token): return True # Password — plus, when a username is configured, it must match. if _verify_password(candidate, stored_pw): configured_user = _get_manage_user() if configured_user: provided = handler.headers.get("X-Zimi-User", "") if provided.strip().casefold() != configured_user.strip().casefold(): # Wrong/missing username reads exactly like a wrong password: # generic denial, no username-enumeration signal. return False return True return False def _secondary_admin_authorized(handler): """True if the request is a SECONDARY admin: a users.json account with role=admin, authenticated by its session token (Bearer or cookie). They get manage powers, but the hierarchy in ``_handle_users_post`` still bars them from touching the primary admin or managing other admins.""" from zimi import users as _users name = _users.resolve_request_user(handler) return bool(name) and _users.is_admin_user(name) def admin_kind(handler): """Classify an authorized manage request: ``'primary'`` (password-file / API-token / passwordless-private), ``'secondary'`` (role=admin session), or ``None`` (not an admin). Drives the primary-only hierarchy checks.""" if _primary_admin_authorized(handler): return "primary" if _secondary_admin_authorized(handler): return "secondary" return None def _check_manage_auth(handler): """Check authorization for manage endpoints. Returns a truthy value if unauthorized (``True`` for a genuine password/token requirement, ``PUBLIC_LOCKED`` for the passwordless-but-non-private case), ``None`` if authorized. Auth model: - No password set → open access for private clients; non-private clients are locked (PUBLIC_LOCKED) until a password is set from the LAN - Password set → Bearer token must match password or API token (PRIMARY admin), OR a role=admin session token (SECONDARY admin) - API token is optional (requires password to be set first) - manage_open → nobody is asked for anything, at all """ # First, and without looking at anything else. The operator said no. if manage_open(): return None stored_pw = _get_manage_password_hash() if not stored_pw: # Bootstrap window (GHSA-5mw2-53vv-9pw6). The host, the setup key's # holder, or the home network while a fresh install's setup page is up # (_owner_proof). Private-tier as such is no free pass: it was wide # enough for an adjacent device to race the owner to the first # password on an install that stayed unclaimed. No password yet means # no admin yet, so this same gate guards ALL of /manage. if _owner_proof(handler): return None # The operator's explicit "my LAN is my trust boundary" (issue #59). # Off unless someone typed it, so the advisory's default stands; on, it # restores the pre-1.9.0 behaviour for the people who ran Zimi that way # deliberately and have no wish to hold an admin password. if _lan_admin_allowed() and _lan_client(handler): return None return PUBLIC_LOCKED if _primary_admin_authorized(handler) or _secondary_admin_authorized(handler): return None return True def _manage_auth_challenge(handler): """Return the ``(status, body)`` to send for a denied manage request, or ``None`` when the client is authorized. Distinguishes the two failure modes that used to both surface as a bare ``401 needs_password`` and left the SPA prompting for a password that does not exist (issue #36): - passwordless instance, non-private client → ``403 public_locked`` with ``needs_password: False`` (nothing to enter; the UI explains instead) - password/token required or wrong → ``401 unauthorized`` with ``needs_password: True`` (the UI prompts, exactly as before) """ # Settings kept inside the network: refused before the password is even # looked at, so the outside has nothing to guess at. Only here, on the # settings routes: an admin outside still reads the library. if _get_manage_password_hash() and not settings_reachable(handler): return (403, {"error": OUTSIDE_LOCKED, "needs_password": False}) result = _check_manage_auth(handler) if result is None: return None if result == PUBLIC_LOCKED: # Passwordless and off-host. A PRIVATE-tier client — a LAN or tailnet # peer who could plausibly read the server log — is told a setup key # exists so the SPA prompts for it. A genuine WAN visitor gets the # opaque lock: no hint a key exists, nothing to brute-force. Being on # the same trust network is the price of even seeing the key prompt. if not _get_manage_password_hash() and handler._is_private_client(): return ( 403, { "error": "needs_setup_key", "needs_password": False, "needs_setup_key": True, # The desktop app issues none (only `zimi serve` prints # one), and a field for a key that does not exist is a # dead end: the page sends the visitor to the host. "setup_key_issued": bool(_read_setup_key()), }, ) return (403, {"error": "public_locked", "needs_password": False}) return (401, {"error": "unauthorized", "needs_password": True}) def _creator_authorized(handler): """True if the request may drive ZIM creation: any authorized admin (primary or secondary, including the passwordless-private legacy admin), or a signed-in named user whose account carries ``can_create``.""" if _check_manage_auth(handler) is None: return True from zimi import users as _users name = _users.resolve_request_user(handler) return bool(name) and _users.user_can_create(name) def _creator_denial(handler): """The ``(status, body)`` refusing a create-surface request, or ``None`` when authorized (see ``_creator_authorized``). A signed-in user WITHOUT the permission gets a plain 403 — they are authenticated, so the admin password prompt (``needs_password``) would be the wrong door to point at. Everyone else gets the standard manage challenge: 401 for anonymous/wrong credentials, ``public_locked`` for the passwordless-public case. """ if _creator_authorized(handler): return None from zimi import users as _users if _users.resolve_request_user(handler): return (403, {"error": "creation is not enabled for this account"}) return _manage_auth_challenge(handler) # ============================================================================ # App update check — is a newer ZIMI APPLICATION release out? # # Deliberately distinct from the ZIM-content "Auto-update" feature # (library.py / /manage/auto-update), which refreshes installed ZIM files. # Keep every name here prefixed "app_update" so the two can never be # conflated in code, endpoints, or UI strings. # ============================================================================ _APP_UPDATE_URL = "https://api.github.com/repos/epheterson/Zimi/releases/latest" _APP_RELEASES_PAGE = "https://github.com/epheterson/Zimi/releases" # Passive reads (opening the Manage server pane) reuse the cached answer for # a day; a failed check backs off only an hour so one DNS hiccup doesn't # blind the row for 24h. "Check now" bypasses both but keeps a short flood # guard — GitHub's anonymous API quota is 60 req/h and a mashed button must # not eat it. There is NO boot-time or background caller by design: the only # trigger is an admin actually looking at (or poking) the Manage row. _APP_UPDATE_TTL = 24 * 3600 _APP_UPDATE_ERROR_TTL = 3600 _APP_UPDATE_FORCE_GUARD = 60 _app_update_lock = threading.Lock() # single-flight: concurrent admins share one fetch # Whether this server looks for new Zimi releases on its own (Eric, # 2026-09-28: "i'm not positive how i feel about unexpected network calls from # zimi"). Automatically, the default and what every install did before, checks # GitHub when an admin opens Server settings (at most daily) and lets the # desktop app's updater check at launch; Ask first checks only on "Check now"; # Never checks nothing. ZIMI_UPDATE_CHECK wins over the saved choice and # ZIMI_OFFLINE forces Never. APP_UPDATE_CHECK_ENV = "ZIMI_UPDATE_CHECK" UPDATE_CHECK = outbound.FetchPolicy( APP_UPDATE_CHECK_ENV, "update_check", outbound.AUTO, "Check for Zimi updates" ) # Update delay: hold a release back until it has been public for N days, so a # fleet can let other people find the sharp edges first. 0 (the default, and # every pre-1.9 install's behavior) offers a release the moment it exists. # The choices the UI offers; any integer in range is still accepted over the # API and the env var, because a fleet policy of "11 days" is nobody's bug. APP_UPDATE_DELAY_ENV = "ZIMI_UPDATE_DELAY_DAYS" APP_UPDATE_DELAY_DEFAULT = 0 APP_UPDATE_DELAY_CHOICES = (0, 1, 3, 7, 14, 30) APP_UPDATE_DELAY_MAX = 365 # a year of deferral is already an eternity # Ordering for pre-release suffixes within one numeric version. Unknown words # land above rc so a novel stream ("1.9.0-preview2") still moves forward, and # ties break on the word itself for determinism. _PRERELEASE_STAGES = {"alpha": 0, "a": 0, "beta": 1, "b": 1, "rc": 2, "c": 2} _PRERELEASE_UNKNOWN_STAGE = 3 _FINAL_STAGE = 9 # a final release outranks every pre-release of its version def _app_update_cache_path(): return os.path.join(_srv.ZIMI_DATA_DIR, "app_update.json") def _app_update_prefs_path(data_dir=None): """The app-update preferences share one small file. The name is the one the channel-era builds wrote, so an existing preference survives. ``data_dir`` is for a reader that runs before this server has one (the desktop app's updater).""" return os.path.join(data_dir or _srv.ZIMI_DATA_DIR, "app_update_channel.json") _prefs_cache = {} # path -> ((inode, mtime_ns, size), prefs); writes replace the inode def _read_app_update_prefs(data_dir=None): """The saved prefs, as a fresh dict. Settings auth asks this on every request (manage_external), so a parse is reused until the file changes.""" path = _app_update_prefs_path(data_dir) try: st = os.stat(path) stamp = (st.st_ino, st.st_mtime_ns, st.st_size) hit = _prefs_cache.get(path) if hit and hit[0] == stamp: return dict(hit[1]) with open(path, "r", encoding="utf-8") as f: saved = json.load(f) except (OSError, ValueError): return {} saved = saved if isinstance(saved, dict) else {} _prefs_cache[path] = (stamp, saved) return dict(saved) def _write_app_update_prefs(**updates): """Merge into the prefs file — writing one preference must never drop another.""" prefs = _read_app_update_prefs() prefs.update(updates) _srv._atomic_write_json(_app_update_prefs_path(), prefs) def normalize_update_delay_days(value): """A whole number of days in [0, APP_UPDATE_DELAY_MAX], or None for anything that isn't one. Strings are accepted so an env var and a JSON body can share this path; booleans are not, because True is not 1 day.""" if isinstance(value, bool) or value is None: return None try: days = int(str(value).strip()) except (TypeError, ValueError): return None return days if 0 <= days <= APP_UPDATE_DELAY_MAX else None def is_update_delay_env_locked(): """True when ZIMI_UPDATE_DELAY_DAYS holds a usable number of days.""" return normalize_update_delay_days(os.environ.get(APP_UPDATE_DELAY_ENV)) is not None def get_update_delay_days(): """The delay in force: env var, then the saved preference, then none.""" from_env = normalize_update_delay_days(os.environ.get(APP_UPDATE_DELAY_ENV)) if from_env is not None: return from_env saved = normalize_update_delay_days(_read_app_update_prefs().get("delay_days")) return APP_UPDATE_DELAY_DEFAULT if saved is None else saved def set_update_delay_days(value): """Persist the update delay. Returns (days, error) — error is a short code the caller turns into an HTTP status.""" days = normalize_update_delay_days(value) if days is None: return None, "invalid_delay" if is_update_delay_env_locked(): return None, "env_locked" _write_app_update_prefs(delay_days=days) return days, None def _parse_app_version(tag): """'v1.9.0' / '1.9' / '1.9.0-beta1' → ((1, 9, 0), 'beta1'), else None. The numeric tuple (padded to three parts so 1.9 == 1.9.0) drives the comparison; the suffix only marks pre-releases. Unparseable tags return None so a garbage GitHub tag can never masquerade as an update.""" m = re.match(r"[vV]?(\d+(?:\.\d+)*)[-+.]?(.*)$", (tag or "").strip()) if not m or not m.group(1): return None nums = tuple(int(p) for p in m.group(1).split(".")) return (nums + (0,) * 3)[: max(3, len(nums))], m.group(2).strip() def _prerelease_rank(suffix): """Sortable rank for a version suffix: '' (a final release) outranks every pre-release of the same numbers, and within pre-releases alpha < beta < rc < anything unrecognized, then by trailing number.""" if not suffix: return (_FINAL_STAGE, 0, "") m = re.match(r"([A-Za-z]*)[.\-_]?(\d*)", suffix) word = (m.group(1) if m else "").lower() num = int(m.group(2)) if m and m.group(2) else 0 stage = _PRERELEASE_STAGES.get(word, _PRERELEASE_UNKNOWN_STAGE) return (stage, num, "" if word in _PRERELEASE_STAGES else word) def _app_version_sort_key(tag): """(numbers, pre-release rank) for a tag, or None if it can't be parsed.""" parsed = _parse_app_version(tag) if not parsed: return None nums, suffix = parsed # Pad to a fixed width so (1, 9) and (1, 9, 0, 1) compare positionally. return (nums + (0,) * 4)[:4], _prerelease_rank(suffix) def _app_version_newer(remote, current): """True only when `remote` is a strictly newer release than `current`. Same-number comparisons are conservative: a final release outranks its own pre-releases, but pre-vs-pre never reports an update — better to miss an edge case than nag someone already current.""" r, c = _app_version_sort_key(remote), _app_version_sort_key(current) if not r or not c: return False if r[0] != c[0]: return r[0] > c[0] r_final, c_final = r[1][0] == _FINAL_STAGE, c[1][0] == _FINAL_STAGE return ( r_final and not c_final ) # a final beats its own pre-release, never the reverse def detect_install_type(): """Best-effort: how was this Zimi installed? Drives which upgrade instruction the Manage UI shows — a wrong guess only yields a suboptimal instruction, so lean conservative and fall through to 'pip'. Order matters: container/package sandboxes outrank the frozen-app flag because the outermost wrapper decides how you upgrade.""" env = os.environ declared = env.get("ZIMI_INSTALL_TYPE", "").strip().lower() if declared: # Escape hatch for packagers (and tests): trust an explicit label. return declared if ( os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv") # podman's marker file or env.get("container") # OCI convention (podman, systemd-nspawn) ): return "docker" if env.get("SNAP") and env.get("SNAP_NAME"): return "snap" if env.get("APPIMAGE"): return "appimage" if getattr(sys, "frozen", False) or getattr(sys, "_MEIPASS", None): if sys.platform == "darwin": return "desktop-mac" if sys.platform.startswith("win"): return "desktop-windows" return "desktop" # frozen Linux build outside an AppImage wrapper paths = "%s %s" % (sys.prefix or "", sys.executable or "") if "/Cellar/" in paths or "/opt/homebrew/" in paths or "/home/linuxbrew/" in paths: # Heuristic only: a plain pip install into a brew-owned Python # matches too. The brew instruction is still the closest fit we can # detect from inside the process. return "homebrew" return "pip" def _read_app_update_cache(): try: with open(_app_update_cache_path(), "r", encoding="utf-8") as f: data = json.load(f) return data if isinstance(data, dict) else {} except (OSError, ValueError): return {} def _github_json(url): """GET a GitHub API URL and decode it. Raises on anything but success — every caller is inside the check's try/except.""" req = urllib.request.Request( url, headers={ "User-Agent": "Zimi/%s (+%s)" % (_srv.ZIMI_VERSION, _APP_RELEASES_PAGE), "Accept": "application/vnd.github+json", }, ) with urllib.request.urlopen(req, timeout=10, context=_srv.SSL_CTX) as resp: return json.loads(resp.read().decode("utf-8", "replace")) def _parse_release_timestamp(value): """GitHub's `published_at` ('2026-08-01T12:00:00Z') → epoch seconds, or None when it is missing or unparseable. A release with no usable stamp can't be aged, and is treated as mature everywhere downstream: an update must never become permanently invisible because a field went missing.""" text = (value or "").strip() if isinstance(value, str) else "" if not text: return None try: stamp = datetime.fromisoformat(text.replace("Z", "+00:00")) except ValueError: return None if stamp.tzinfo is None: stamp = stamp.replace(tzinfo=timezone.utc) # GitHub always sends UTC return stamp.timestamp() def _update_hold_until(published_ts, delay_days, now=None): """The epoch second an update this fresh becomes offerable, or None when it already is (no delay set, no publish date, or the wait is over). Evaluated on every read rather than baked into the cache, so a verdict of "too fresh" ages out on its own instead of being frozen for a day by the cached check that produced it.""" if not delay_days or not published_ts: return None ready_at = published_ts + delay_days * 86400 return ready_at if (now or time.time()) < ready_at else None def check_app_update(force=False): """Return {latest, checked_at, url, error?}, hitting GitHub only when the cached answer is stale (or `force`, for the Check-now button). ZIMI_OFFLINE outranks everything including force — zero network calls. Network failures are silent by contract: one debug line, the last good answer keeps serving, and the failure is stamped so passive reads back off instead of re-probing a dead link on every pane visit. "Check for Zimi updates" decides the rest: Ask first answers a passive read from the cache alone and fetches only for `force`; Never fetches for nothing.""" from zimi import p2p # is_offline() — the single air-gap switch if p2p.is_offline(): return dict(_read_app_update_cache(), offline=True) mode = UPDATE_CHECK.mode()[0] if mode == outbound.NEVER or (mode == outbound.ASK and not force): return _read_app_update_cache() now = time.time() def _fresh(entry): age = now - entry.get("checked_at", 0) if force: return age < _APP_UPDATE_FORCE_GUARD return age < (_APP_UPDATE_ERROR_TTL if entry.get("error") else _APP_UPDATE_TTL) cached = _read_app_update_cache() if _fresh(cached): return cached with _app_update_lock: cached = _read_app_update_cache() # a concurrent caller may have won if _fresh(cached): return cached try: # /releases/latest is already "newest final release" — one # request, and GitHub does the pre-release filtering. rel = _github_json(_APP_UPDATE_URL) if not isinstance(rel, dict): raise ValueError("no usable release in feed") entry = { "checked_at": now, # Tags arrive as "v1.9.0" — store the bare version the UI shows. "latest": (rel.get("tag_name") or "").strip().lstrip("vV"), "url": rel.get("html_url") or _APP_RELEASES_PAGE, # Kept raw (epoch) so the update delay is re-evaluated on every # read instead of the cache freezing a "too fresh" verdict. "published_ts": _parse_release_timestamp(rel.get("published_at")), } except Exception as e: log.debug("app-update check failed: %s", e) entry = dict(cached, checked_at=now, error=True) _srv._atomic_write_json(_app_update_cache_path(), entry) return entry def _app_update_payload(force=False): """The /manage/app-update response: check state + install-type routing. A newer release that hasn't been public long enough for the configured delay reports `update_held` + `held_until` instead of `update_available`, so the UI can say "1.9.1 is out, offering it in 3 days" rather than pretending the release doesn't exist.""" from zimi import p2p delay_days = get_update_delay_days() state = check_app_update(force=force) latest = state.get("latest") or None newer = bool(latest and _app_version_newer(latest, _srv.ZIMI_VERSION)) held_until = ( _update_hold_until(state.get("published_ts"), delay_days) if newer else None ) check_mode, check_locked = UPDATE_CHECK.mode() return { "current": _srv.ZIMI_VERSION, "latest": latest, "update_available": newer and held_until is None, "update_held": held_until is not None, "held_until": held_until, "delay_days": delay_days, "delay_days_locked": is_update_delay_env_locked(), "delay_env": APP_UPDATE_DELAY_ENV, "delay_choices": list(APP_UPDATE_DELAY_CHOICES), "checked_at": state.get("checked_at") or None, "error": bool(state.get("error")), "offline": p2p.is_offline(), "install_type": detect_install_type(), "releases_url": state.get("url") or _APP_RELEASES_PAGE, # "Check for Zimi updates": ask, auto or never, and what locks it. "check_mode": check_mode, "check_locked": check_locked, "check_modes": list(outbound.MODES), "check_env": APP_UPDATE_CHECK_ENV, } def _search_background_work(): from zimi.search import background_work return background_work() def _search_background_failures(): from zimi.search import background_failures return background_failures() def _catalog_copies(): """The catalog copies Zimi keeps on disk and can fetch again, as paths: the cached catalog pages and their validators, and the .torrent kept for each catalog item that is not installed (mirror mode holds one for every item, tens of MB). A .torrent for an installed ZIM stays: seeding it and checking its pieces need it.""" from zimi import library as _lib data_dir = _srv.ZIMI_DATA_DIR paths = [_lib._catalog_cache_path(), _lib._validators_path()] tdir = os.path.join(data_dir, "bt", "torrents") try: names = os.listdir(tdir) except OSError: names = [] # Installed anywhere the library reads (subfolders, other folders), not only at the top of ZIM_DIR. installed = {os.path.basename(p) for p in _srv.get_zim_files().values()} for name in names: zim = name[: -len(".torrent")] if name.endswith(".torrent") and zim not in installed and not os.path.exists(os.path.join(_srv.ZIM_DIR, zim)): paths.append(os.path.join(tdir, name)) return [p for p in paths if os.path.isfile(p)] def _purge_catalog_copies(): """Delete _catalog_copies(); how many bytes that freed.""" freed = 0 for path in _catalog_copies(): try: size = os.path.getsize(path) os.remove(path) freed += size except OSError as e: log.debug("catalog copy not removed: %s", e) return freed def _cache_info_payload(): """Size breakdown of the Zimi data dir (indexes + caches, NOT the ZIM library). Walks only the small-file-count data dir — never the ZIM files. Returns the original {caches, total_bytes} shape (backward compatible) plus: - data_dir_total_bytes: everything under the data dir - breakdown: ordered segments for the stacked bar (title/qid indexes, catalog caches, staging, other) — each {key, size_bytes[, count]} - top_zims: largest per-ZIM title-index contributors, largest first """ import glob as _glob data_dir = _srv.ZIMI_DATA_DIR def _dir_size(path): total = 0 for f in _glob.glob(os.path.join(path, "**"), recursive=True): if os.path.isfile(f): try: total += os.path.getsize(f) except OSError: pass return total def _file_size(path): try: return os.path.getsize(path) except OSError: return 0 def _index_dir_stats(path): """(total bytes, .db file count) for an index directory, (0, 0) if absent.""" if not os.path.isdir(path): return 0, 0 return _dir_size(path), len(_glob.glob(os.path.join(path, "*.db"))) titles_dir = os.path.join(data_dir, "titles") title_bytes, title_count = _index_dir_stats(titles_dir) qid_bytes, qid_count = _index_dir_stats(os.path.join(data_dir, "qids")) metadata_bytes = _file_size(os.path.join(data_dir, "cache.json")) suggest_bytes = _file_size(os.path.join(data_dir, "suggest_cache.json")) # Catalog caches = the JSON metadata/catalog files at the data-dir root # (metadata cache, suggest cache, offline catalog, history, layout, …). catalog_bytes = 0 if os.path.isdir(data_dir): for f in _glob.glob(os.path.join(data_dir, "*.json")): catalog_bytes += _file_size(f) # Staging = in-progress downloads. May live outside the data dir (env # override), so track whether it's already counted in the dir walk. from zimi import p2p as _p2p staging_dir = _p2p.get_staging_dir(data_dir) staging_bytes = _dir_size(staging_dir) if os.path.isdir(staging_dir) else 0 staging_in_data = os.path.abspath(staging_dir).startswith( os.path.abspath(data_dir) + os.sep ) data_total = _dir_size(data_dir) if os.path.isdir(data_dir) else 0 accounted = ( title_bytes + qid_bytes + catalog_bytes + (staging_bytes if staging_in_data else 0) ) other_bytes = max(0, data_total - accounted) # Top per-ZIM contributors: title-index files are one .db per ZIM. top_zims = [] if os.path.isdir(titles_dir): sizes = [] for f in _glob.glob(os.path.join(titles_dir, "*.db")): name = os.path.basename(f)[: -len(".db")] sizes.append({"name": name, "size_bytes": _file_size(f)}) sizes.sort(key=lambda s: s["size_bytes"], reverse=True) top_zims = sizes[:6] caches = { "title_indexes": { "path": "titles/", "size_bytes": title_bytes, "count": title_count, }, "qid_indexes": {"path": "qids/", "size_bytes": qid_bytes, "count": qid_count}, "metadata_cache": {"path": "cache.json", "size_bytes": metadata_bytes}, "suggest_cache": {"path": "suggest_cache.json", "size_bytes": suggest_bytes}, } breakdown = [ {"key": "title_indexes", "size_bytes": title_bytes, "count": title_count}, {"key": "qid_indexes", "size_bytes": qid_bytes, "count": qid_count}, {"key": "catalog_caches", "size_bytes": catalog_bytes}, {"key": "staging", "size_bytes": staging_bytes}, {"key": "other", "size_bytes": other_bytes}, ] bar_total = sum(seg["size_bytes"] for seg in breakdown) copies = _catalog_copies() return { "caches": caches, "catalog_copies": {"count": len(copies), "size_bytes": sum(_file_size(p) for p in copies)}, "total_bytes": sum(c["size_bytes"] for c in caches.values()), "data_dir_total_bytes": bar_total, "breakdown": breakdown, "top_zims": top_zims, } # ============================================================================ # Library layout — shared validate/apply (used by /manage/library-layout POST # and the backup importer so the two never drift). # ============================================================================ def _validate_library_layout(overrides, order, sections=None): """Return an error string if `overrides`/`section_order`/`sections` are malformed, else None. Any may be None (that half is simply skipped).""" if overrides is not None: if ( not isinstance(overrides, dict) or len(overrides) > _srv._LAYOUT_MAX_OVERRIDES ): return "invalid overrides" for k, v in overrides.items(): if ( not isinstance(k, str) or not isinstance(v, str) or len(k) > _srv._LAYOUT_STR_MAX or len(v) > _srv._LAYOUT_STR_MAX ): return "invalid overrides" if order is not None: if not isinstance(order, list) or len(order) > _srv._LAYOUT_MAX_ORDER: return "invalid section_order" for s in order: if ( not isinstance(s, str) or len(s) > _srv._LAYOUT_STR_MAX or not _srv._SECTION_KEY_RE.match(s) ): return "invalid section_order" if sections is not None: if not isinstance(sections, list) or len(sections) > _srv._LAYOUT_MAX_SECTIONS: return "invalid sections" for s in sections: if not isinstance(s, str) or not s or len(s) > _srv._LAYOUT_STR_MAX: return "invalid sections" return None def _apply_library_layout(overrides, order, sections=None): """Merge-patch the persisted layout. `overrides` merges key-by-key (empty value clears an entry); `section_order` and `sections` fully replace when present. Returns the saved layout. Caller must have validated first.""" with _srv._library_layout_lock: layout = _srv._load_library_layout() if overrides is not None: merged = dict(layout.get("overrides", {})) for k, v in overrides.items(): if v == "": merged.pop(k, None) # empty value = revert to heuristic else: merged[k] = v layout["overrides"] = merged if order is not None: layout["section_order"] = list(order) if sections is not None: # De-dupe case-insensitively, first spelling wins, so a declared # empty section can't accumulate near-duplicate rows. seen, deduped = set(), [] for name in sections: key = name.strip().lower() if key and key not in seen: seen.add(key) deduped.append(name) layout["sections"] = deduped _srv._save_library_layout(layout) return layout # ============================================================================ # Backup bundle — export/import a Zimi setup. # # SCHEMA (zimi-backup, version 3). Two scopes: # • "device" — everyone's backup: the installed library list, collections/ # favorites, and the home layout. The client folds its own per-browser # state (bookmarks/history/preferences) in on top; that never touches the # server. This is the v1 shape plus a `scope` field. (The redesigned SPA # splits this: the "My data" card round-trips the per-browser half through # /userdata for a signed-in user; the "Server backup" card owns everything # below. The device bundle stays for API clients and back-compat.) # • "server" — ADMIN-ONLY. Everything the server owns: the device fields # PLUS users.json (WITH password hashes — it's the admin's own backup), # the anonymous-access policy, the download schedule, the BitTorrent/ # sharing prefs, the seed-intent ledger, and (v3) the hot-cache list, the # auto-update config, the server-side event history, and every named # user's server-stored My-data blob (user_data). # # Import MERGES by default (union by identity, incoming wins on conflict) and # is a two-step: a "preview" pass returns a diff summary and applies nothing; # only an explicit "apply" writes. An `overwrite` flag replaces wholesale where # the caller wants that. Keep `_BACKUP_SCHEMA_VERSION` in lockstep with the # client's `_BACKUP_SCHEMA_VERSION`. # ============================================================================ _BACKUP_SCHEMA = "zimi-backup" _BACKUP_SCHEMA_VERSION = 3 # Every restorable state key a bundle can carry, in plan order. The headless # CLI (`zimi restore`) reports "skipped" as the bundle keys the apply plan did # not touch (env-locked settings, server keys riding on a device-scope # bundle), so this list must stay in lockstep with the labels that # _compute_backup and _plan_server_scope emit. _BUNDLE_STATE_KEYS = ( "collections", "library_layout", "users", "public_access", "schedule", "bt_prefs", "seed_intents", "hot_zims", "auto_update", "history", "user_data", ) def _bundle_scope(data): """The scope a bundle declares. Missing (v1 bundles) → 'device'. Anything other than 'server' is treated as 'device' so server-only keys can never be processed off a device bundle.""" return ( "server" if (isinstance(data, dict) and data.get("scope") == "server") else "device" ) def _build_backup_bundle(scope="device"): """Assemble a backup bundle. ``scope='server'`` adds the admin-only server state on top of the device fields (caller enforces the admin gate).""" library = [ { "name": z["name"], "file": z.get("file"), "date": z.get("date", ""), "language": z.get("language", ""), "article_count": z.get("article_count"), "size_bytes": z.get("size_bytes"), "title": z.get("title", z["name"]), } for z in _srv.list_zims() ] bundle = { "schema": _BACKUP_SCHEMA, "schema_version": _BACKUP_SCHEMA_VERSION, "scope": "device", "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "zimi_version": _srv.ZIMI_VERSION, "library": library, "collections": _srv._load_collections(), "library_layout": _srv._load_library_layout(), } if scope == "server": from zimi import library as _lib from zimi import p2p from zimi import users as _users sched = _lib._load_download_schedule() mode, allow, _ = _users._load_access() au_enabled, au_freq = _lib._load_auto_update_config() bundle["scope"] = "server" bundle["users"] = _users._load_users() # WITH hashes — admin's own backup bundle["public_access"] = {"mode": mode, "allowlist": allow} bundle["schedule"] = { "enabled": sched["enabled"], "start": sched["start"], "end": sched["end"], "upload_restrict": sched["upload_restrict"], "upload_trickle_kb": sched["upload_trickle_kb"], } bundle["bt_prefs"] = p2p.all_prefs() bundle["seed_intents"] = _lib.seed_ledger_snapshot() # v3 additions — the rest of what a full restore needs to resurrect an # instance: the hot-cache list, the auto-update config, the server-side # event history, and every named user's server-stored My-data blob. bundle["hot_zims"] = _srv.get_hot_zims() bundle["auto_update"] = {"enabled": au_enabled, "frequency": au_freq} bundle["history"] = _srv._load_history() bundle["user_data"] = _users.all_user_data() return bundle # ── Merge primitives (pure — compute the merged value + counts, persist later) ── def _collection_newer(incoming, current): """Conflict winner for a same-named collection. Honors an optional ``updated`` epoch when both carry one; otherwise incoming wins (it's the backup the admin chose to restore).""" try: inc_t = float(incoming.get("updated")) cur_t = float(current.get("updated")) except (TypeError, ValueError): return True return inc_t >= cur_t def _merge_collections(cur, incoming, overwrite): """Union favorites (dedupe) and named collections (by name, newest-wins). Returns (merged, counts).""" inc_fav = [f for f in incoming.get("favorites", []) if isinstance(f, str)] inc_cols = incoming.get("collections", {}) if overwrite: fav = list(dict.fromkeys(inc_fav))[:100] merged = {"version": 1, "favorites": fav, "collections": dict(inc_cols)} counts = { "fav_added": len(fav), "fav_dupes": 0, "col_added": len(inc_cols), "col_replaced": 0, } return merged, counts fav = list(cur.get("favorites", [])) dupes = 0 for f in inc_fav: if f in fav: dupes += 1 else: fav.append(f) cols = dict(cur.get("collections", {})) added = replaced = 0 for name, obj in inc_cols.items(): if name in cols: if _collection_newer(obj, cols[name]): cols[name] = obj replaced += 1 else: cols[name] = obj added += 1 merged = {"version": 1, "favorites": fav[:100], "collections": cols} counts = { "fav_added": max(0, len(fav[:100]) - len(cur.get("favorites", []))), "fav_dupes": dupes, "col_added": added, "col_replaced": replaced, } return merged, counts def _merge_layout(cur, incoming, overwrite): """Merge the home layout: overrides union (incoming wins per ZIM), sections union, section_order replaced when present (an ordering — merging is meaningless). Returns (overrides, order, sections, counts).""" inc_over = incoming.get("overrides") or {} inc_order = incoming.get("section_order") inc_sections = incoming.get("sections") or [] cur_over = cur.get("overrides") or {} cur_sections = cur.get("sections") or [] if overwrite: over = dict(inc_over) order = inc_order if isinstance(inc_order, list) else cur.get("section_order") sections = list(inc_sections) counts = { "over_added": len(inc_over), "over_changed": 0, "order_changed": inc_order is not None, "sections_added": len(inc_sections), } return over, order, sections, counts over = dict(cur_over) added = changed = 0 for k, v in inc_over.items(): if k in over: if over[k] != v: changed += 1 over[k] = v else: over[k] = v added += 1 sections = list(cur_sections) sec_added = 0 seen = {s.strip().lower() for s in cur_sections if isinstance(s, str)} for s in inc_sections: if isinstance(s, str) and s.strip().lower() not in seen: seen.add(s.strip().lower()) sections.append(s) sec_added += 1 order = inc_order if isinstance(inc_order, list) else cur.get("section_order") counts = { "over_added": added, "over_changed": changed, "order_changed": isinstance(inc_order, list) and inc_order != cur.get("section_order"), "sections_added": sec_added, } return over, order, sections, counts def _merge_users(cur, incoming, overwrite): """Union users by casefold key; incoming wins on conflict (or replace all when overwrite). Returns (merged, counts).""" from zimi import users as _users inc = { _users._key(v.get("name", k)): v for k, v in incoming.items() if isinstance(v, dict) } if overwrite: return inc, {"added": len(inc), "replaced": 0} merged = dict(cur) added = replaced = 0 for k, v in inc.items(): if k in merged: if merged[k] != v: replaced += 1 merged[k] = v else: merged[k] = v added += 1 return merged, {"added": added, "replaced": replaced} def _compute_backup(data, overwrite): """Diff an incoming bundle against current server state WITHOUT persisting. Returns (plan, preview, error). ``plan`` is a list of (label, thunk) pairs the apply pass runs in order; ``preview`` is the diff summary the client shows before the admin confirms. Server-only keys are considered only for a ``server``-scope bundle, so a device bundle can never carry server changes. """ if not isinstance(data, dict): return None, None, "invalid backup" schema = data.get("schema") if schema is not None and schema != _BACKUP_SCHEMA: return None, None, "not a Zimi backup" scope = _bundle_scope(data) plan = [] preview: dict = {"scope": scope} coll = data.get("collections") if coll is not None: if not isinstance(coll, dict): return None, None, "invalid collections" fav = coll.get("favorites", []) cols = coll.get("collections", {}) if not isinstance(fav, list) or not isinstance(cols, dict): return None, None, "invalid collections" merged, counts = _merge_collections(_srv._load_collections(), coll, overwrite) preview["collections"] = counts plan.append(("collections", lambda m=merged: _persist_collections(m))) layout = data.get("library_layout") if layout is not None: if not isinstance(layout, dict): return None, None, "invalid library_layout" over, order, sections, counts = _merge_layout( _srv._load_library_layout(), layout, overwrite ) err = _validate_library_layout(over, order, sections) if err: return None, None, err preview["layout"] = counts plan.append( ( "library_layout", lambda o=over, r=order, s=sections: _apply_library_layout(o, r, s), ) ) lib = data.get("library") if isinstance(lib, list): installed = set(_srv.get_zim_files().keys()) preview["missing_zims"] = sum( 1 for z in lib if isinstance(z, dict) and z.get("name") not in installed ) if scope == "server": err = _plan_server_scope(data, overwrite, plan, preview) if err: return None, None, err return plan, preview, None def _persist_collections(merged): with _srv._collections_lock: _srv._save_collections(merged) def _plan_server_scope(data, overwrite, plan, preview): """Extend the plan/preview with the admin-only server state. Returns an error string or None.""" from zimi import library as _lib from zimi import p2p from zimi import users as _users users = data.get("users") if users is not None: if not isinstance(users, dict): return "invalid users" merged, counts = _merge_users(_users._load_users(), users, overwrite) preview["users"] = counts plan.append(("users", lambda m=merged: _users._save_users(m))) settings_changed = [] pa = data.get("public_access") if isinstance(pa, dict): mode = pa.get("mode") allow = pa.get("allowlist", []) cur_mode, cur_allow, _ = _users._load_access() if mode != cur_mode or allow != cur_allow: settings_changed.append("public_access") plan.append( ("public_access", lambda m=mode, a=allow: _users.set_public_access(m, a)) ) sched = data.get("schedule") if isinstance(sched, dict): cur = _lib._load_download_schedule() keys = ("enabled", "start", "end", "upload_restrict", "upload_trickle_kb") if any(sched.get(k) != cur.get(k) for k in keys if k in sched): settings_changed.append("download_schedule") plan.append(("schedule", lambda s=sched: _restore_schedule(s))) bt = data.get("bt_prefs") if isinstance(bt, dict): if bt != p2p.all_prefs(): settings_changed.append("sharing_prefs") plan.append(("bt_prefs", lambda b=bt: _restore_bt_prefs(b, overwrite))) intents = data.get("seed_intents") if isinstance(intents, dict): cur = _lib.seed_ledger_snapshot() preview["seed_intents"] = { "added": sum(1 for k, v in intents.items() if cur.get(k) != v) } plan.append( ("seed_intents", lambda i=intents: _lib.restore_seed_intents(i, overwrite)) ) # v3 server state — hot list, auto-update, history, per-user data. hot = data.get("hot_zims") if isinstance(hot, list): # Env-locked hot list (ZIMI_HOT_ZIMS) is authoritative — never clobber it. if "ZIMI_HOT_ZIMS" not in os.environ: if hot != _srv.get_hot_zims(): settings_changed.append("hot_zims") plan.append( ( "hot_zims", lambda h=[s for s in hot if isinstance(s, str)]: _srv.set_hot_zims( h ), ) ) au = data.get("auto_update") if isinstance(au, dict) and "enabled" in au and "frequency" in au: # Env-locked auto-update (ZIMI_AUTO_UPDATE) wins — skip the restore. if not getattr(_srv, "_auto_update_env_locked", False): cur_en, cur_fr = _lib._load_auto_update_config() if bool(au["enabled"]) != cur_en or au["frequency"] != cur_fr: settings_changed.append("auto_update") plan.append(("auto_update", lambda a=au: _restore_auto_update(a))) history = data.get("history") if isinstance(history, list): preview["history"] = {"events": len(history)} plan.append(("history", lambda h=history: _restore_history(h, overwrite))) ud = data.get("user_data") if isinstance(ud, dict): preview["user_data"] = {"users": len(ud)} plan.append(("user_data", lambda u=ud: _users.restore_user_data(u, overwrite))) if settings_changed: preview["settings"] = settings_changed return None def _restore_auto_update(au): from zimi import library as _lib enabled, freq = bool(au.get("enabled")), au.get("frequency", "weekly") _lib._save_auto_update_config(enabled, freq) # Reflect into the live server namespace so /manage/status reads true without # a restart (the loop reads these via _srv — see library._auto_update_loop). _srv._auto_update_enabled = enabled _srv._auto_update_freq = freq def _restore_history(entries, overwrite): """Restore server-side event history. Replace when overwrite; otherwise fill only when the current log is empty (a resurrected instance) so a normal merge into a running server never duplicates or reorders its real event stream.""" if overwrite or not _srv._load_history(): _srv._save_history(entries) def _restore_schedule(sched): from zimi import library as _lib cur = _lib._load_download_schedule() _lib._save_download_schedule( sched.get("enabled", cur["enabled"]), sched.get("start", cur["start"]), sched.get("end", cur["end"]), sched.get("upload_restrict", cur["upload_restrict"]), sched.get("upload_trickle_kb", cur["upload_trickle_kb"]), ) def _restore_bt_prefs(bt, overwrite): from zimi import p2p p2p.replace_prefs(bt, overwrite=overwrite) p2p.apply_rate_limits() def _apply_backup_bundle(data, overwrite=False): """Apply a backup bundle (MERGE by default). Returns (result, error). Prefer the two-step route contract (preview then apply); this runs the whole plan in one shot for direct callers/tests. ``result`` carries the applied keys plus the preview summary.""" plan, preview, err = _compute_backup(data, overwrite) if err or plan is None: return None, err applied = [] for label, thunk in plan: thunk() applied.append(label) return {"status": "ok", "applied": applied, "preview": preview}, None # ============================================================================ # The activity journal — what happened to this library, and who did it # # Every kind of change already left a trace SOMEWHERE: downloads and updates in # history.json, creation runs in create_jobs.json, health checks and exports in # a status dict that a restart forgets. None of them recorded WHO, which is the # question an operator actually asks of a shared server — a ZIM updated by the # auto-updater and the same ZIM updated by a person are the same row in the old # history, and only one of them means someone made a decision. # # So: one line per thing that happened, stamped where it happens, carrying the # actor with it. Downloads learn their actor at submission and carry it to the # finish line (the stamp fires in a background thread minutes later, long after # the request that asked for it is gone). # # The discipline is the create journal's: bounded, atomic, and soft — a journal # that cannot be written costs a log line, never the operation. Nothing in here # may raise into a caller's success path. # ============================================================================ ACTIVITY_FILE = "activity.json" # Deep enough to cover a busy week of a real library, shallow enough that the # whole file is one small read and the view never needs paging. ACTIVITY_RECORDS = 200 # The kinds of thing that happen to a library. A type outside this set is still # recorded — the client renders it with the generic icon — but everything Zimi # itself stamps is named here, and the filter is built from what is present. ACTIVITY_TYPES = ( "download", "update", "create", "export", "delete", "health", "restore", "import", ) ACTIVITY_OUTCOMES = ("ok", "failed", "cancelled", "interrupted") # Both are display fields; a runaway error string must not be able to grow the # journal past the size that keeps it a cheap read. ACTIVITY_SUBJECT_MAX = 160 ACTIVITY_DETAIL_MAX = 200 # The name a request gets when it is authenticated as the primary admin — the # account with a password rather than a user record, so there is no username to # borrow. Secondary admins and ordinary users keep their own names. ACTIVITY_ADMIN = "admin" # Work nobody asked for in the moment: the auto-updater, the download scheduler, # resumes after a restart. `name` stays null — "server" is the whole identity. ACTIVITY_SERVER_ACTOR = {"kind": "server", "name": None} # Pre-1.9 history has no actor, and guessing one would be worse than saying so. ACTIVITY_UNKNOWN_ACTOR = {"kind": "unknown", "name": None} # How the pre-1.9 event names map into activity types when the old history is # folded in (see _activity_seed). _ACTIVITY_FROM_HISTORY = { "download": ("download", "ok"), "updated": ("update", "ok"), "download_failed": ("download", "failed"), "deleted": ("delete", "ok"), } _activity_lock = threading.Lock() _activity = None # list of records, oldest first; loaded once per process def _activity_path(): return os.path.join(_srv.ZIMI_DATA_DIR, ACTIVITY_FILE) def activity_actor(handler=None): """Who is responsible for what is about to happen. ``handler`` is the request that asked for it, or None for work the server started by itself. Every caller with a request passes it — these routes are admin-gated, so a request that got this far is *somebody*, and the only question is whether that somebody has a name of their own. """ if handler is None: return dict(ACTIVITY_SERVER_ACTOR) name = None try: from zimi import users as _users name = _users.resolve_request_user(handler) except Exception as e: # An unreadable session store must not cost the operation its actor # line, let alone the operation. log.debug("Could not resolve the actor for an activity record: %s", e) return {"kind": "user", "name": name or ACTIVITY_ADMIN} def _activity_clean_actor(actor): """A stored actor dict, whatever shape the caller handed us.""" if not isinstance(actor, dict): return dict(ACTIVITY_SERVER_ACTOR) kind = actor.get("kind") if kind not in ("user", "server", "unknown"): kind = "server" name = actor.get("name") if kind != "user" or not isinstance(name, str) or not name.strip(): return {"kind": kind, "name": None} return {"kind": "user", "name": name.strip()[:ACTIVITY_SUBJECT_MAX]} def _activity_seed(): """The journal a fresh install of 1.9 is born with: the old history. An upgrade must not look like data loss. Everything the pre-1.9 history recorded is an activity record missing exactly one field — who — so it converts cleanly, and the actor it converts to is ``unknown`` rather than a guess. Runs once: after this the file exists and the stamps take over. """ seeded = [] try: events = _srv._load_history() except Exception as e: log.debug("No history to seed the activity journal from: %s", e) return seeded # History is newest first and this journal is oldest first. for event in reversed(events if isinstance(events, list) else []): if not isinstance(event, dict): continue mapped = _ACTIVITY_FROM_HISTORY.get(str(event.get("event") or "")) if not mapped: continue event_type, outcome = mapped subject = ( event.get("title") or event.get("name") or str(event.get("filename") or "").removesuffix(".zim") ) seeded.append( _activity_record( event_type, subject, outcome=outcome, detail=str(event.get("error") or "")[:ACTIVITY_DETAIL_MAX], actor=dict(ACTIVITY_UNKNOWN_ACTOR), size_bytes=event.get("size_bytes"), ts=event.get("ts"), ) ) return seeded[-ACTIVITY_RECORDS:] def _activity_load(): """The journal, loaded once per process. Caller holds ``_activity_lock``.""" global _activity if _activity is not None: return _activity records = None try: with open(_activity_path(), encoding="utf-8") as fh: loaded = json.load(fh) if isinstance(loaded, list): records = [r for r in loaded if isinstance(r, dict)] except FileNotFoundError: pass # fresh install, or the first boot after the upgrade except (OSError, ValueError) as e: # Corrupt or unreadable degrades to empty: the view is a nicety, and # nothing else in the server may fail because of it. log.warning("Cannot read the activity journal: %s", e) records = [] fresh = records is None if fresh: records = _activity_seed() trimmed = len(records) > ACTIVITY_RECORDS if trimmed: # Trimmed on the way in as well as out — the bound is what the file is # allowed to be, not merely what this process appends to it. del records[: len(records) - ACTIVITY_RECORDS] _activity = records if (fresh and records) or trimmed: _activity_save() return records def _activity_save(): """Caller holds ``_activity_lock``. Never raises: a thing that happened still happened when the disk says no.""" _srv._atomic_write_json(_activity_path(), _activity or []) def _activity_record( event_type, subject, outcome="ok", detail="", actor=None, size_bytes=None, count=None, ts=None, ): """One journal record. Every field is already visible to the admin who is reading it — subjects are library names and titles, never server paths. ``detail`` is a locale-neutral FRAGMENT, not a sentence: a source URL, a ratio, an error the transport handed us. The verb around it ("Downloaded", "Update installed") is an i18n key on the client, because a sentence written here would be the one line of the UI that cannot be translated. ``bytes`` and ``count`` travel as numbers for the same reason — the client formats them in the reader's locale. What ``count`` counts is fixed per type: bookmarks for an export, restored sections for a restore. """ record = { "ts": round(float(ts if ts is not None else time.time()), 3), "type": str(event_type or "")[:40], "actor": _activity_clean_actor(actor), "subject": str(subject or "")[:ACTIVITY_SUBJECT_MAX], "outcome": outcome if outcome in ACTIVITY_OUTCOMES else "ok", "detail": str(detail or "")[:ACTIVITY_DETAIL_MAX], } if isinstance(size_bytes, (int, float)) and size_bytes > 0: record["bytes"] = int(size_bytes) if isinstance(count, int) and count > 0: record["count"] = count return record def record_activity( event_type, subject, outcome="ok", detail="", actor=None, size_bytes=None, count=None, ): """Append one line to the activity journal. Never raises. Called from request handlers, from download threads long after their request ended, and from the create watchdog — so it takes its own lock and holds no other. """ try: record = _activity_record( event_type, subject, outcome=outcome, detail=detail, actor=actor, size_bytes=size_bytes, count=count, ) with _activity_lock: records = _activity_load() records.append(record) if len(records) > ACTIVITY_RECORDS: del records[: len(records) - ACTIVITY_RECORDS] _activity_save() return record except Exception as e: log.warning("Could not journal a %s activity record: %s", event_type, e) return None # Two operations answer their caller immediately and finish on a worker thread: # the library health check and the bookmark export. Both report through a status # dict the client polls, and neither should learn about this journal — one of # them writes ZIMs for a living. So the route that started the work watches that # status instead, and files the line when it settles. ACTIVITY_WATCH_TICK = 1.0 # Long enough for a health check over a 600 GB library on a spinning NAS disk, # short enough that a wedged worker does not leave a thread waiting forever. ACTIVITY_WATCH_MAX = 6 * 3600 def _activity_after(state_fn, finish): """Watch a background job's status dict; call ``finish(state)`` once it leaves the running phase. Runs on its own daemon thread and never raises into it.""" def _wait(): deadline = time.time() + ACTIVITY_WATCH_MAX while time.time() < deadline: time.sleep(ACTIVITY_WATCH_TICK) try: state = state_fn() or {} except Exception as e: log.debug("Activity watch could not read a job's state: %s", e) return if state.get("phase") == "running": continue try: finish(state) except Exception as e: log.warning("Activity watch could not file its record: %s", e) return # Past the deadline the honest thing is silence: a record saying "ok" # would be a guess, and one saying "failed" would be a lie about work # that may still be running. log.info("Activity watch gave up waiting for a background job to settle") threading.Thread(target=_wait, daemon=True, name="zimi-activity-watch").start() def _activity_health_finish(actor): """Journal a finished library health check under whoever asked for it.""" def _finish(state): summary = state.get("summary") or {} total = summary.get("total") or 0 healthy = summary.get("healthy") or 0 record_activity( "health", "", # the whole library — the client names it in the reader's language outcome="ok" if state.get("phase") == "done" else "failed", detail=f"{healthy}/{total}" if total else "", actor=actor, ) return _finish def _activity_export_finish(actor, total): """Journal a finished bookmark export. ``total`` is what was handed to the writer — the count the person chose, which is the count they'll recognize even if a source article turned out to be unreadable.""" def _finish(state): files = [str(f) for f in (state.get("files") or []) if f] record_activity( "export", ", ".join(f.removesuffix(".zim") for f in files), outcome="ok" if state.get("phase") == "done" else "failed", detail=str(state.get("error") or ""), actor=actor, count=total, ) return _finish def _activity_actor_key(record): """The filter value for a record's actor: a username, or the kind.""" actor = record.get("actor") or {} if actor.get("kind") == "user" and actor.get("name"): return actor["name"] return actor.get("kind") or "server" def activity_payload(type_filter=None, actor_filter=None): """The activity view's data: records newest first, plus the vocabulary the filter is built from. The type and actor lists are always computed over the WHOLE journal, never over the filtered slice — a filter whose own options disappear the moment you use one is a filter you cannot get back out of. """ with _activity_lock: records = list(_activity_load()) types = sorted({str(r.get("type") or "") for r in records} - {""}) actors = sorted({_activity_actor_key(r) for r in records}) if type_filter: records = [r for r in records if r.get("type") == type_filter] if actor_filter: records = [r for r in records if _activity_actor_key(r) == actor_filter] records.reverse() # newest first, the way it is read return {"records": records, "types": types, "actors": actors} # ============================================================================ # ZIM creation jobs — the web face of `zimi create` / `zimi import` # # ONE job RUNS at a time, deliberately. The hardware floor for Zimi is a Pi # that is also serving the library; a second concurrent crawl would not go # twice as fast, it would make reading the library miserable while both crawl # badly. What a second submission gets is a place in a short FIFO queue, not a # refusal — "start it, I'll come back" is what people actually mean when they # fill the form twice, and a queue says that honestly where a 409 made them # babysit the tab. # # The engines (zimi.creator / crawler / video / importer) stay almost # untouched: each already takes a per-line progress callback, and this module # wires that into a bounded ring buffer the browser polls with a cursor. # Cancellation is cooperative through that same callback — it raises out of # the engine at the next line, which unwinds through ``atomic_zim_creator`` so # no partial ZIM is ever left under a real name. Folder mode is the one engine # with no callback, so it cannot be interrupted mid-run and the status says so # rather than pretending. # # Three things the round-3 field test asked for, and where each lives: # # "is it stable if I close the page?" — the job runs in a server thread and # its state is server-side, so closing the tab changes nothing. What was # missing is what happens when the SERVER goes away mid-job: the journal # below records every job to disk, and a record still marked running at # the next boot becomes an honest "interrupted", not a ghost that polls # forever. The atomic writer has already removed its partial output. # "can I find in-progress ones?" — ``/manage/create/status?history=1`` # hands back the last CREATE_JOURNAL_RECORDS jobs, so a returning admin # finds what happened while they were gone. # "do multiple queue?" — yes; see CREATE_QUEUE_MAX. # # Alongside the human log lines, the poll carries STRUCTURED events (phase / # node / count) on their own cursor. They are DERIVED here by reading the same # lines the engines already emit — the engines do not learn a second output # format they would then have to keep in step, and a line this adapter cannot # read costs one event, never a crash. # ============================================================================ # "folder" is back on the web (Eric, 2026-09-30: "let's actually offer # folder ... show the whole tree and allow selecting any subset"), as a # picker over the create root like import's: no path is ever typed, and # every path the page sends is a relative one checked to stay inside. CREATE_MODES = ("folder", "page", "site", "video", "import", "reddit") # The modes that write a ZIM of their own and so take its description, author, # publisher and tags. CREATE_DETAIL_MODES = ("folder", "page", "site", "video", "import") # Which engine captures a web page. Mirrors creator.OFFERED_ENGINES — every # name a person may ASK for, which is a wider set than the ones that build a # capture object. Held here as a literal for the same reason CREATE_MAX_PAGE_URLS # is: validating a request must not drag the writer stack into the request # thread. The test below pins the two together. # # zimit IS offered here now. It wants a docker daemon, and the old reasoning was # that a web form is the wrong place to discover that — but a readiness probe # is exactly the right place, so _create_engine refuses it with the reason # instead of hiding a working engine from everyone who does have Docker. CREATE_ENGINES = ("builtin", "rendered", "alive", "singlefile", "zimit") # The engines that can refuse a request before it is made — the ones that drive # a browser. Mirrors creator.BLOCKING_ENGINES, held here for the same reason # CREATE_ENGINES is, and pinned to it by the same test. CREATE_BLOCKING_ENGINES = ("rendered", "alive") # What ad blocking does when the form says nothing. Mirrors # renderer.BLOCK_ADS_DEFAULT: the checkbox arrives checked, so a request with no # opinion in it is one where the field never rendered at all. CREATE_BLOCK_ADS = True # The engines that sweep up the image sizes THIS screen did not ask for. Only # the recording engine does: a rendered capture keeps one candidate per srcset # and has no archive to put the others in, so offering the switch alongside it # would be offering a switch over nothing. Mirrors the gate in # renderer.RenderedSession._record_variants, pinned by a test. CREATE_VARIANT_ENGINES = ("alive",) # The engines whose pages Zimi writes, so "Remove links that lead outside the ZIM" can # reach them. alive and zimit hand back an archive another program packaged. CREATE_UNLINK_ENGINES = ("builtin", "rendered", "singlefile") # What the variant sweep does when the form says nothing. Mirrors # renderer.VARIANT_SWEEP_DEFAULT — checked by default, so silence means the # field never rendered rather than "the admin unticked it". CREATE_CAPTURE_VARIANTS = True # ── Stored capture defaults ────────────────────────────────────────────────── # The two module constants above (CREATE_BLOCK_ADS / CREATE_CAPTURE_VARIANTS) # are the FACTORY defaults — what the engines do on a machine nobody has # configured. An admin may override either from Manage → Creator, and that # choice persists in the data dir like every other manage-set preference (see # _write_app_update_prefs for the pattern). Every reader of a default goes # through _create_default so a stored choice wins everywhere at once: the # validator applying it to a silent request, and the payload reporting it. def _read_create_defaults(): """The stored defaults as the file holds them, bad values and all: what a write merges into. Readers that act on a value use ``_create_default``.""" from zimi.crawler import create_defaults_path try: with open(create_defaults_path(), "r", encoding="utf-8") as f: saved = json.load(f) except (OSError, ValueError): return {} return saved if isinstance(saved, dict) else {} def _create_default(key, fallback): """The stored default for ``key``, or ``fallback`` when nobody ever set one. What counts as a valid value is the capture-option table's to say (crawler.CAPTURE_OPTIONS): a hand-edited "yes" or a time limit nobody can read falls back rather than being guessed at.""" from zimi.crawler import stored_defaults return stored_defaults().get(key, fallback) def _write_create_defaults(**updates): """Merge into the defaults file — setting one switch must never drop the other's stored answer. A value of None clears that default.""" prefs = _read_create_defaults() for key, value in updates.items(): if value is None: prefs.pop(key, None) else: prefs[key] = value from zimi.crawler import create_defaults_path _srv._atomic_write_json(create_defaults_path(), prefs) def _create_defaults_view(): """The stored defaults for a form: the values, and each as the text a placeholder shows. ``allow_private`` is the admin's alone and is not sent to the Create page (see ``_create_defaults_payload``).""" from zimi.crawler import ( default_placeholders, factory_text, storable_keys, stored_defaults, ) stored = stored_defaults() return { "defaults": stored, "defaults_text": default_placeholders(stored), "factory_text": factory_text(), "storable_keys": storable_keys(), } def _create_allows_private(): """Whether an admin has allowed web captures of private addresses. Never while the password is off in Settings: then anyone on the internet is the admin, and this would let them read the operator's own network through Zimi. An operator who opened Zimi with ZIMI_MANAGE_OPEN made that call in their own config and keeps the choice.""" if open_from_settings(): return False return bool(_create_default("allow_private", False)) def _private_rule(): """The context a web capture (or its preview) runs in: held to public addresses unless an admin allowed otherwise. The command line never comes through here and is never held.""" import contextlib from zimi.creator import private_addresses_refused return ( contextlib.nullcontext() if _create_allows_private() else private_addresses_refused() ) def _under_private_rule(fn): @functools.wraps(fn) def run(*args, **kwargs): with _private_rule(): return fn(*args, **kwargs) return run # Ring-buffer depth for job output. A long crawl emits a line per page, so the # buffer is a live tail, not a transcript — the browser polls faster than it # fills and keeps everything it has already seen. CREATE_LOG_LINES = 500 CREATE_MAX_SOURCE = 2048 # a path or URL longer than this is not a real one # Mirrors creator.MAX_PAGE_URLS. Held here as a constant rather than imported at # module scope so validating a request never drags in the writer stack; the # test below pins the two together. CREATE_MAX_PAGE_URLS = 20 # Which jobs can actually be interrupted. Cancellation is cooperative — it # raises out of the engine's progress callback — so a mode belongs here exactly # when its engine takes one. Every mode the web runs qualifies (folder gained # its progress callback when it came back), but the list and the `cancellable` # field stay: the client's button should keep answering to the server's word # rather than to an assumption a future mode could break. CREATE_CANCELLABLE_MODES = ("page", "site", "video", "import", "reddit", "folder") # Which jobs can FINISH EARLY — stop fetching at the next page boundary and # package everything captured so far, exactly what SIGINT does to a CLI crawl. # Site capture alone: it is the one mode whose work is an open-ended frontier # with something worth keeping at every prefix. A page list or a playlist is a # finite order (cancel covers changing your mind), and an import has no # fetching to stop. CREATE_FINISHABLE_MODES = ("site",) # The phases in which finishing early still means anything: the network pass. # From `package`/`convert` on, the fetching is over and the button would stop # nothing — the client hides it the moment the server stops saying so. CREATE_FINISHABLE_PHASES = ("probe", "fetch", "assets") CREATE_MAX_TITLE = 200 # Site crawls: the page limit and the size budget have no ceiling. The page # ceiling was 5,000 ("past this, use the CLI"), then 50,000 when the first # Windows user to make a ZIM asked (r/Kiwix, 2026-09-19), and the same person # outgrew that five days later; on the desktop app the form IS the CLI. Any # number is taken, and 0 is none. With both at 0 only the depth and the disk # bound a crawl, and the job log says so. # These two mirror crawler.MAX_DEPTH_CEILING and crawler.MAX_DELAY, which check a # STORED default; this module cannot import the crawler at load (the writer # stack), and a test holds the pairs equal. CREATE_MAX_DEPTH_CEILING = 50 CREATE_MAX_DELAY = 60.0 # seconds between page requests # Video jobs: a playlist cap, same reasoning. CREATE_VIDEO_LIMIT_CEILING = 500 CREATE_MAX_SIZE_TEXT = 32 # "512MiB" is 6; nothing real is longer than this _CREATE_LANGUAGE_RE = re.compile(r"^[a-z]{2,3}$") # The video quality the web form may ask for, as named presets mapped to yt-dlp # selectors. A preset name is the ONLY thing accepted over HTTP: yt-dlp's format # argument is an expression language, and an arbitrary expression arriving from # a browser is not a preference, it is an instruction to a downloader. The full # selector stays on `zimi create --format`, where the person typing it is at a # shell on the machine already. CREATE_VIDEO_FORMATS = { "720p": None, # the engine's own default "1080p": "best[height<=1080][ext=mp4]/best[height<=1080]/best", "480p": "best[height<=480][ext=mp4]/best[height<=480]/best", "best": "best", } # How many submissions may wait behind the running one. Five is a queue an # admin can hold in their head; past that the honest answer is "come back # later" (429) rather than a backlog nobody remembers filing. CREATE_QUEUE_MAX = 5 # Structured events, bounded exactly like the log lines. A long crawl emits # one per page twice over (fetched, then packaged), so this is a live tail too. CREATE_EVENT_BUFFER = 2000 # A job that has not said anything for this long is not working, it is wedged — # a host that accepted a connection and never answered, a subprocess that never # wrote another line. Ten minutes is longer than any single legitimate step: # every engine reports per page, per entry or per subprocess line, and the # slowest of those is one HTTP fetch at DEFAULT_FETCH_TIMEOUT (30s). CREATE_STALL_SECONDS = 600 CREATE_STALL_TICK = 15.0 # how often the watchdog looks # The on-disk job journal: how a returning admin finds out what happened while # they were away, and how a job that was running when the server died stops # being a job that is running forever. CREATE_JOURNAL_FILE = "create_jobs.json" CREATE_JOURNAL_RECORDS = 20 # A job that did not end well keeps its last lines in the journal, so the log # can still be read after the page was left or the server restarted (asked in # discussion #105: "How can I view the logs? I left the page while it was # running"). Also written to the server's own log when it fails. CREATE_JOURNAL_LOG_LINES = 200 CREATE_SERVER_LOG_LINES = 40 # The phases a job moves through, in order. The client renders them; the # adapter below decides when each begins by reading the engines' own lines. # ``convert`` is the warc2zim subprocess: the phase where a recording (alive) # or an archive somebody brought (import) becomes a ZIM. It sits beside # ``package`` rather than replacing it because they are alternatives — a job # does one or the other, never both — and the client folds them onto the same # visible step, which is the right answer for a person watching: both of them # are "it is writing the file now". CREATE_PHASES = ("probe", "fetch", "assets", "package", "convert", "register", "done") # Where a mode's work starts. The URL modes fetch first; import has nothing to # fetch, it goes straight to writing a ZIM. CREATE_START_PHASE = { "import": "package", "folder": "package", "page": "fetch", "site": "fetch", "video": "fetch", } _create_lock = threading.Lock() _create_job = None # the one _CreateJob running (or the last one to finish) _create_queue = [] # [(job, opts)] waiting their turn, FIFO class _CreateCancelled(Exception): """Raised out of a job's progress callback when the admin cancels.""" class _CreateJob: """One creation run: its identity, its output tail, and its outcome.""" def __init__(self, mode, source, title): # Short, random, and only ever compared for equality: the client uses it # to tell "my job" from "the job that started after mine finished", and # the journal uses it to update a record in place. self.id = os.urandom(6).hex() self.mode = mode self.source = source self.title = title # Whoever submitted it, for the activity journal. A job created outside # a request (the CLI, a test) belongs to the server. self.actor = dict(ACTIVITY_SERVER_ACTOR) self.lines = [] # tail, trimmed to CREATE_LOG_LINES self.emitted = 0 # total lines ever produced — the cursor space self.events = [] # tail, trimmed to CREATE_EVENT_BUFFER self.events_emitted = 0 # the events' own cursor space self.phase = CREATE_START_PHASE.get(mode, "fetch") self.queued_at = time.time() self.started = None # set when it actually leaves the queue self.finished = None # Last sign of life, for the watchdog. A job that has never emitted a # line is measured from the moment it started, not from creation, or a # long wait in the queue would count against it. self.progressed = None self.done = False self.ok = False # The phase a failed job was in when it failed. ``phase`` itself # reads "done" afterwards, like any finished job's, so without this # the run pane could only mark Ready as the step that went wrong. self.failed_phase = None self.cancelled = False self.cancel_requested = False self.stalled = False # The watchdog's verdict, published the moment it decides and BEFORE it # kills anything, because killing the browser is what un-wedges the # worker thread and sends it here with an error of its own. Whoever # closes the job out, this is the sentence the operator gets: see the # precedence rule in _create_finish. self.stall_error = "" self.error = "" self.result = None # Finish-early (site mode): the admin asked the crawl to stop fetching # and package what it has. `stop_flag` is the crawler's own stop flag, # attached by _create_run once the crawl exists; the boolean is set # first so a request that lands in the gap is honored when it does. self.finish_requested = False self.stop_flag = None # A transient caption ("starting a headless browser…") is on the run # pane and the next real progress event should take it down. Only ever # touched from the job's own thread, inside _create_derive. self.transient_detail = False # Set the moment the job is closed out, whoever closes it. The watchdog # waits on this rather than on a clock, so it wakes exactly once per # tick while the job runs and not at all after it ends — no thread # loitering behind a finished job with a sleep still to serve. self.settled = threading.Event() # The picture of the live page, as soon as an engine has one — seconds # into a job that can run for minutes. Held here rather than sent down # the poll: it is hundreds of kilobytes of JPEG and the poll is JSON, # so the event says it exists and the page fetches it once. self.shot = None # -- output ------------------------------------------------------------ def note(self, message): """Progress sink handed to the engines. Doubles as the cancellation checkpoint: a pending cancel raises here, at a line boundary. Takes a line of text, as every engine sends today, or a ready-made event dict for a caller that has something structured to say and no sentence to go with it. Engines only ever send text — the CLI's sink prints whatever it is handed, and a dict on a terminal is not progress. """ if self.cancel_requested: raise _CreateCancelled() now = time.time() if isinstance(message, dict): event = dict(message) # The bytes come off the event before it is filed: the event tail # is serialized to the client on every poll, and a JPEG in it would # be both unserializable and enormous. jpeg = event.pop("jpeg", None) from zimi import zimwriter as _zw with _create_lock: self.progressed = now if jpeg: self.shot = jpeg # A picture is not progress: the page learns of it from # has_shot, and the stream carries only phase/node/count # events, which a bare {"event": "shot"} was not. if event.get("event") != _zw.SHOT_EVENT: self._push_events([event]) return text = str(message).rstrip("\n") # Derived outside the lock: it parses a string and may import a module, # and the sink is called from the job thread on every line. events, phase = _create_derive(self, text) with _create_lock: self.progressed = now self.lines.append(text) self.emitted += 1 if len(self.lines) > CREATE_LOG_LINES: del self.lines[: len(self.lines) - CREATE_LOG_LINES] self._push_events(events) if phase: # A phase change is rare (four or five in a whole job) and is # exactly what a returning admin wants to see, so it is worth a # journal write where a per-page line would not be. self.phase = phase _create_journal_put(self) def _push_events(self, events): """Stamp each event with its sequence number and file it. Caller holds ``_create_lock``.""" for event in events: event["i"] = self.events_emitted self.events_emitted += 1 self.events.append(event) if len(self.events) > CREATE_EVENT_BUFFER: del self.events[: len(self.events) - CREATE_EVENT_BUFFER] def tail(self, cursor): """Lines from ``cursor`` onward plus the new cursor. A cursor older than the buffer silently snaps forward — dropped lines are gone, and replaying nothing beats replaying the wrong window.""" with _create_lock: first = self.emitted - len(self.lines) start = max(0, cursor - first) return self.lines[start:], self.emitted def event_tail(self, cursor): """The same contract as ``tail``, in the events' own cursor space.""" with _create_lock: first = self.events_emitted - len(self.events) start = max(0, cursor - first) return list(self.events[start:]), self.events_emitted # ── structured progress events ────────────────────────────────────────────── # # The engines speak in sentences meant for a human reading a log. The Create # page wants a shape: which phase, which node, how many of how many. Rather # than teach five engines a second output format — one more thing to keep in # step, and one more way for a CLI sink to print a dict at somebody — this # reads the lines that already exist and derives the shape from them. # # Three event kinds, all carrying an ``i`` sequence number stamped on the way # into the buffer: # # {"i", "t":"phase", "phase": , "detail": } # {"i", "t":"node", "kind":"page|asset|entry", "id", "parent", "label", # "state":"pending|active|done|failed"} # {"i", "t":"count", "what":"entries|bytes|assets", "n", "total"} # # ``count`` is scoped to the phase in force when it arrives: entries during # ``fetch`` are pages pulled off the network, entries during ``package`` are # pages written into the ZIM. # # ``parent`` is set on ASSET nodes and null on page nodes, and the difference # is what the engine actually knows. The crawler fetches an asset because a # named page referenced it, so that parentage is measured. It reports which # page it captured but never which page linked to it, so page parentage would # have to be invented — and a tree the engine did not measure is a prettier lie # than a flat list. The client derives page parentage from the site's own # address space and lets a server-supplied parent win, so if the crawler ever # does report link provenance nothing downstream has to change. # "[12/200] ", or "[12/no limit] " for a crawl with no page limit: # 1.10.3 made 0 mean none, and this read no lines of such a crawl, so its # counter and page list stood still for the whole run. _CREATE_RE_STEP = re.compile(r"^\[(\d+)/(\d+|no limit)\]\s+(.+)$") _CREATE_RE_CRAWL_TAIL = re.compile(r"\s*\((\d+) queued(?:, (.+?) fetched)?\)$") _CREATE_RE_PACKAGED = re.compile(r"^packaged (\d+)/(\d+)\s+(.+)$") _CREATE_RE_PACKAGING_MANY = re.compile(r"^packaging (\d+) pages?\b") _CREATE_RE_FETCHING = re.compile(r"^fetching (\S+)$") _CREATE_RE_PACKAGING_ONE = re.compile(r"^packaging (\S+)$") _CREATE_RE_SKIPPED = re.compile(r"^skipped (\S+):") _CREATE_RE_ASSET = re.compile(r"^asset (done|failed) (\S+) for (\S+)$") # The Fast engine's running carry total, emitted at most once a second while it # fetches a page's images during the write pass. Turns the packaging phase from # a blank pane into live counters (Eric: "this view is still empty and lame"). _CREATE_RE_CARRIED = re.compile(r"^carried (\d+) assets, (\d+) bytes$") _CREATE_RE_TITLE = re.compile(r"^title: (.+)$") # Both doors into warc2zim announce themselves the same way — the alive engine # handing over its recording, and `zimi import` handing over an archive # somebody else made. _CREATE_RE_CONVERTING = re.compile(r"^converting\b") # The renderer's one line between "job started" and its first page: Chromium # can take many seconds to boot, and without this the run pane sat silent for # all of them (Eric: "show something right now — I need to open the log thing # to see what's happening"). _CREATE_RE_BROWSER = re.compile(r"^starting a headless browser") _CREATE_LABEL_MAX = 80 def _create_short_label(target): """The bit of a URL or article path worth showing in a node: the path (and the query that paginates it), or the host when the path is just ``/``.""" text = str(target).strip() if text.startswith(("http://", "https://")): parts = urllib.parse.urlsplit(text) path = parts.path or "/" if path == "/" and parts.netloc: text = parts.netloc else: text = path + (("?" + parts.query) if parts.query else "") return text[:_CREATE_LABEL_MAX] def _create_parse_bytes(text): """The byte count back out of a size the engines formatted ("759.0 KB"). ``crawler.parse_size`` already reads every spelling the CLI accepts, so it reads this one too — bar the bare "N bytes" form, unwrapped here so the two halves stay one dialect. None when it is not a size at all.""" raw = str(text).strip() if raw.lower().endswith("bytes"): raw = raw[:-5].strip() try: from zimi.crawler import parse_size return parse_size(raw) except Exception: return None def _create_node_event(kind, node_id, state, label=None, parent=None): return { "t": "node", "kind": kind, "id": str(node_id)[:CREATE_MAX_SOURCE], "parent": str(parent)[:CREATE_MAX_SOURCE] if parent else None, "label": _create_short_label(label if label is not None else node_id), "state": state, } def _create_count_event(what, n, total=None): return {"t": "count", "what": what, "n": int(n), "total": total} def _create_derive(job, text): """Events (and the phase they imply) from one line of engine output. Returns ``(events, phase_or_None)``. Never raises: a line this does not recognise is simply a line with no events behind it, which is the right outcome for engine output that is prose.""" try: return _create_derive_line(job, text) except Exception: # a log line must never be able to fail a job log.debug("could not derive create events from %r", text, exc_info=True) return [], None def _create_derive_line(job, text): line = text.strip() events, phase = [], None def enter(name): nonlocal phase # The membership check is the contract, enforced: the client renders a # fixed set of phases, and a name outside it would be a phase that # silently draws nothing. assert name in CREATE_PHASES, name if job.phase != name and phase != name: phase = name job.transient_detail = False # a fresh phase brings its own detail events.append({"t": "phase", "phase": name, "detail": job.mode}) def settle(): """Real progress after a transient caption: re-state the phase with its plain detail — the client blanks detail == mode — so "starting a headless browser…" comes down the moment actual work reports again.""" if job.transient_detail: job.transient_detail = False if not any(e.get("t") == "phase" for e in events): events.append({"t": "phase", "phase": job.phase, "detail": job.mode}) if _CREATE_RE_BROWSER.match(line): # Between a rendered/alive job starting and its first page there are # 5–15 silent seconds of Chromium booting. Re-announcing the CURRENT # phase with this line as its detail puts the sentence on the run pane # the moment it happens — same event vocabulary, no second channel — # and settle() above takes it back down at the next real progress. job.transient_detail = True events.append({"t": "phase", "phase": job.phase, "detail": line}) return events, phase if job.mode == "reddit": # A subreddit build has its own steps (fetching posts, fetching # comments, importing, building the ZIM), none shaped like a page # capture's lines; they map onto the same four steps on the strip. low = line.lower() if low.startswith("fetching "): enter("fetch") elif low.startswith(("importing", "building the zim")): enter("package") elif low.startswith("zim written"): enter("register") elif re.match(r"^[\d,]+ (posts|comments) fetched", low) or low.startswith( ("retrieving ", "adding ", "writing ") ): settle() events.append({"t": "phase", "phase": job.phase, "detail": line}) return events, phase match = _CREATE_RE_PACKAGED.match(line) if match: # site capture, one page written into the ZIM enter("package") settle() events.append(_create_node_event("entry", match.group(3), "done")) events.append( _create_count_event("entries", match.group(1), int(match.group(2))) ) return events, phase match = _CREATE_RE_CARRIED.match(line) if match: # the write pass reporting what it has pulled in so far settle() events.append(_create_count_event("assets", int(match.group(1)))) events.append(_create_count_event("bytes", int(match.group(2)))) return events, phase match = _CREATE_RE_ASSET.match(line) if match: # one image, stylesheet or font, and the page that wanted it state, asset_id, page_id = match.groups() settle() events.append( _create_node_event( "asset", asset_id, state, label=asset_id.rsplit("/", 1)[-1], parent=page_id, ) ) return events, phase match = _CREATE_RE_PACKAGING_MANY.match(line) if match: # site capture, the whole write pass announcing its size enter("package") settle() events.append(_create_count_event("entries", 0, int(match.group(1)))) return events, phase match = _CREATE_RE_STEP.match(line) if match: done, rest = int(match.group(1)), match.group(3) total = int(match.group(2)) if match.group(2).isdigit() else None enter("fetch") settle() tail = _CREATE_RE_CRAWL_TAIL.search(rest) if tail: # a site crawl: the remainder is a URL plus the running totals url = rest[: tail.start()].strip() events.append(_create_node_event("page", url, "done")) fetched = _create_parse_bytes(tail.group(2) or "") if fetched is not None: events.append(_create_count_event("bytes", fetched)) else: # a video playlist: the remainder is a title, not an address events.append(_create_node_event("entry", rest, "done")) events.append(_create_count_event("entries", done, total)) return events, phase match = _CREATE_RE_FETCHING.match(line) if match: enter("fetch") settle() # a page in flight means the browser is up events.append(_create_node_event("page", match.group(1), "active")) return events, phase match = _CREATE_RE_SKIPPED.match(line) if match: events.append(_create_node_event("page", match.group(1), "failed")) return events, phase match = _CREATE_RE_PACKAGING_ONE.match(line) if match: enter("package") target = match.group(1) if target.startswith(("http://", "https://")): # Multi-page capture writes one page at a time and says which. events.append(_create_node_event("page", target, "done")) return events, phase if _CREATE_RE_CONVERTING.match(line): enter("convert") return events, phase match = _CREATE_RE_TITLE.match(line) if match: # The engine has read what the thing it is making is called. Worth # having only when nobody typed a title — an admin's own title is a # decision, not a guess to be improved on. It goes straight onto the # job rather than out as an event: every status reply already carries # `title`, and the job's own thread is the only writer there is. if not job.title: job.title = match.group(1).strip()[:CREATE_MAX_TITLE] return events, phase # The engines' closing "done" line is deliberately NOT read as the done # phase: only the job knows whether it finished, was cancelled or was given # up on, so _create_finish is the single place that says so. return events, phase def _create_emit(job, *events): """File events that did not come from a line — the totals a finished run knows and no sentence carried. Deliberately not ``job.note``: that is the cancellation checkpoint, and a job that has already succeeded must not be turned into a cancelled one by its own closing bookkeeping.""" with _create_lock: job._push_events([dict(event) for event in events]) # ── the job journal ───────────────────────────────────────────────────────── # # Jobs live in memory, which is right for a live log and wrong for the only # question an admin asks after a redeploy: what happened to the thing I # started? The journal is a small JSON file of the last CREATE_JOURNAL_RECORDS # jobs, rewritten at the few moments a job's state actually changes (queued, # started, each phase, finished) — a handful of writes per job, not one per # page. # # On the first read of a new process, any record still marked running or queued # belongs to a server that is no longer here, and becomes "interrupted". That # is not a guess: this process is holding the file, so nothing else is advancing # those jobs. Their partial output is already gone — ``atomic_zim_creator`` # writes to ``.zim.tmp`` and only renames on a clean exit, so a killed # process leaves a tmp file and never a half-written ZIM under a real name. _create_journal_lock = threading.Lock() _create_journal = None # list of records, loaded and reconciled once def _create_journal_path(): return os.path.join(_srv.ZIMI_DATA_DIR, CREATE_JOURNAL_FILE) def _create_job_state(job): """The one word for a job's state that the journal and the history view both use. Ordered by precedence: how it ended beats that it ended.""" if not job.done: return "running" if job.started else "queued" if job.cancelled: return "cancelled" if job.stalled: return "stalled" return "ok" if job.ok else "failed" def _create_job_record(job): """One journal record. Everything here is already visible to the admin who submitted the job — no server paths beyond the source they typed, and the result named the way the library names it.""" return { "id": job.id, "mode": job.mode, "source": job.source[:CREATE_MAX_SOURCE], "title": job.title, "queued": round(job.queued_at, 3), "started": round(job.started, 3) if job.started else None, "finished": round(job.finished, 3) if job.finished else None, "phase": job.phase, "state": _create_job_state(job), "ok": bool(job.ok), "error": job.error, "result": (job.result or {}).get("name"), # What the run counted and whether it stopped short of its bounds. # Without these the journal answers "did my capture finish?" with a # bare ok — a crawl that died at its byte budget after 38 of a site's # pages read exactly like one that got everything (Eric's apple run: # diagnosing it meant re-deriving the budget math by hand). "counts": { k: v for k, v in (job.result or {}).items() if k in ("pages", "assets", "bytes", "files", "videos", "entries") } or None, "stopped": (job.result or {}).get("stopped"), "actor": _activity_clean_actor(getattr(job, "actor", None)), "log": ( list(job.lines[-CREATE_JOURNAL_LOG_LINES:]) if job.done and _create_job_state(job) != "ok" else None ), } # A create job's own word for how it ended, in the activity journal's words. A # stalled job failed — "gave up waiting" is the detail, not a fifth outcome. _CREATE_ACTIVITY_OUTCOME = { "ok": "ok", "failed": "failed", "cancelled": "cancelled", "stalled": "failed", "interrupted": "interrupted", } def _create_activity(job): """File a settled creation run in the activity journal.""" result = job.result or {} state = _create_job_state(job) record_activity( "create", result.get("title") or job.title or result.get("name") or job.source, outcome=_CREATE_ACTIVITY_OUTCOME.get(state, "failed"), # What it was made from is the one fact the subject cannot carry: two # ZIMs called "Docs" are told apart by the site they came from. detail=(job.error or job.source or job.mode), actor=getattr(job, "actor", None), size_bytes=result.get("bytes"), ) def _create_journal_load(): """The journal, reconciled once per process. Caller must hold ``_create_journal_lock``.""" global _create_journal if _create_journal is not None: return _create_journal records = [] try: with open(_create_journal_path(), encoding="utf-8") as fh: loaded = json.load(fh) if isinstance(loaded, list): records = [r for r in loaded if isinstance(r, dict)] except FileNotFoundError: pass except (OSError, ValueError) as e: log.warning("Cannot read the create journal: %s", e) stale = False if len(records) > CREATE_JOURNAL_RECORDS: # Trimmed on the way IN as well as on the way out: the bound is what # this file is allowed to be, not merely what this process appends to # it, and a journal that arrived oversized (an older build, a hand # edit) must not be served or rewritten at that size. del records[: len(records) - CREATE_JOURNAL_RECORDS] stale = True for record in records: state = record.get("state") if state == "running": record["state"] = "interrupted" record["error"] = "interrupted: the server restarted during this job" stale = True elif state == "queued": record["state"] = "interrupted" record["error"] = "not started: the server restarted before this job began" stale = True else: continue # A job the server lost is still something that happened to this # library, and the activity view is where an operator looks to find out # why last night's ZIM never appeared. Recorded once: the reconcile # rewrites the state, so the next boot sees "interrupted" and no longer # matches here. record_activity( "create", record.get("title") or record.get("result") or record.get("source") or "", outcome="interrupted", detail=record.get("error") or "", actor=record.get("actor"), ) _create_journal = records if stale: _create_journal_save() return records def _create_journal_save(): """Caller holds ``_create_journal_lock``. Never raises: a job that cannot be journalled is still a job that ran.""" _srv._atomic_write_json(_create_journal_path(), _create_journal or []) def _create_journal_put(job): """Record this job's current state, replacing its earlier record.""" record = _create_job_record(job) with _create_journal_lock: records = _create_journal_load() for index, existing in enumerate(records): if existing.get("id") == job.id: records[index] = record break else: records.append(record) if len(records) > CREATE_JOURNAL_RECORDS: del records[: len(records) - CREATE_JOURNAL_RECORDS] _create_journal_save() def _create_history(): """The recent jobs, newest first — what a returning admin came back for.""" with _create_journal_lock: records = list(reversed(_create_journal_load())) # The kept log is asked for on its own (/manage/create/log); the list # only says there is one. return [ dict({k: v for k, v in r.items() if k != "log"}, has_log=bool(r.get("log"))) for r in records ] def _create_log(job_id): """A job's kept log lines, or None: the job running now (its live tail), else its journal record.""" job = _create_job if job is not None and job.id == job_id: with _create_lock: return list(job.lines) with _create_journal_lock: for r in _create_journal_load(): if r.get("id") == job_id: return r.get("log") or [] return None def _create_name_of(path): """The library name for a freshly written ZIM: its filename without the extension, which is exactly how the rest of the app addresses it.""" base = os.path.basename(path or "") return base[:-4] if base.lower().endswith(".zim") else base def _create_validate(data): """Validate a create request. Returns ``(mode, source, title, opts)`` or raises ValueError whose message is safe to send to the client — every one of them names something the admin typed, never anything internal.""" mode = str(data.get("mode") or "").strip().lower() if mode not in CREATE_MODES: raise ValueError("unknown creation mode") source = str(data.get("source") or "").strip() if not source: raise ValueError("missing source") # Page mode takes a LIST — one address per line — so its ceiling is the cap # times a URL, not a single URL. ceiling = CREATE_MAX_SOURCE * (CREATE_MAX_PAGE_URLS if mode == "page" else 1) if len(source) > ceiling: raise ValueError("source is too long") title = str(data.get("title") or "").strip()[:CREATE_MAX_TITLE] page_urls = [] # The address says what it is. A reddit.com/r/ address typed under # Web page or Site is a subreddit, and there is no tile for one (Eric: # "let's be coy. You put in the url Reddit.com/r/whatever and we know # what to do"). One address only: a list of pages stays a list. if mode in ("page", "site") and "\n" not in source: from zimi.reddot import looks_like_subreddit if looks_like_subreddit(source): mode = "reddit" only = [] if mode == "folder": # A folder under the create root, by its path from there ("." is the # root itself), and optionally a subset inside it. Both are checked # by real path to stay inside; nothing typed reaches the disk. source, only = _create_folder_selection(source, data.get("only")) elif mode == "reddit": # A subreddit, by name or address. The maker (ArcticZim) is fetched # into a sidecar on first use, like warc2zim. from zimi.reddot import normalize_subreddit sub = normalize_subreddit(source) if not sub: raise ValueError( "not a subreddit name (letters, digits and _, like r/kiwix)" ) source = sub elif mode == "import": # Back on the web (a user: "I'd like a way to convert warc files # within the app's gui"), without the thing that took it off: no # path is typed. The form offers the archives found in the library # folder, the request names one, and the name is checked against the # same listing. `zimi import ` still takes any path. source = _create_archive_path(source) elif mode == "page": # One page or twenty, it is the same gesture: paste what you want kept. # The engine sends a single URL down the single-page path itself, so # nothing here has to decide which kind of capture this is. page_urls = _create_page_urls(source) source = page_urls[0] if len(page_urls) == 1 else "\n".join(page_urls) else: source = _normalize_url_scheme(source) parts = urllib.parse.urlsplit(source) if parts.scheme.lower() not in ("http", "https") or not parts.netloc: raise ValueError("not an http(s) URL") # Options. Numbers clamp (an absurd one means the admin misjudged a bound, # and the nearest legal value is what they meant); anything that is not a # number at all raises, because there is no "nearest" size or language code # and quietly running with a different one is worse than a refusal. opts = {} if mode == "page": opts["urls"] = page_urls if mode == "folder": opts["only"] = only if mode in CREATE_DETAIL_MODES: opts.update(_create_details(data, stored=mode != "folder")) if mode in ("folder", "page", "site", "video"): # A folder reads the stored language itself, after its zimi.txt. opts["language"] = _create_language( data.get("language") or (None if mode == "folder" else _create_default("language", None)) ) if mode in ("page", "site"): # The two modes that capture a web page get to choose HOW. Refused # rather than clamped, like every other named value: silently capturing # the other way is the one outcome nobody asked for. opts["engine"] = _create_engine(data.get("engine")) or _create_stored_engine() # Ad and tracker blocking, but only for an engine that can do it. A # form left open while the engine radio moved back to the fast one can # send this; DROPPING it there is right where the CLI's refusal is # right — nobody typed this, a stale checkbox did, and refusing a whole # capture over a field that describes nothing would be theatre. if _create_blocking_engine(opts["engine"]): opts["block_ads"] = _create_bool( data.get("block_ads"), _create_default("block_ads", CREATE_BLOCK_ADS) ) # The responsive-variant sweep, on the one engine that does it, and # dropped elsewhere for exactly the reason block_ads is dropped: a # stale checkbox from a form whose engine radio has since moved is not # a request anybody made. if _create_variant_engine(opts["engine"]): opts["capture_variants"] = _create_bool( data.get("capture_variants"), _create_default("capture_variants", CREATE_CAPTURE_VARIANTS), ) # "Remove links that lead outside the ZIM" (#99), off unless ticked. Only where # Zimi writes the pages itself: an alive or zimit capture's links are # rewritten at replay, so the box would promise what it cannot do. if _create_unlink_engine(opts["engine"]): opts["strip_links"] = _create_bool(data.get("strip_links"), False) if mode == "page": # How a page capture presents itself and what it sends and leaves out: # the site options that describe one fetch and not a walk. from zimi.crawler import PAGE_OPTION_KEYS, fill_stored_defaults opts.update(_create_capture_options(data, opts.get("engine"), PAGE_OPTION_KEYS)) fill_stored_defaults(opts, opts.get("engine"), keys=PAGE_OPTION_KEYS) if mode == "site": # Any number, and 0 for none: the byte budget bounds the capture. A # negative is a typo, not "no limit", so it falls back to the default. pages = _create_int(data.get("max_pages"), -1, None) opts["max_pages"] = None if pages is None or pages < 0 else pages opts["max_depth"] = _create_int( data.get("max_depth"), 0, CREATE_MAX_DEPTH_CEILING ) opts["max_bytes"] = _create_bytes(data.get("max_bytes")) opts["delay"] = _create_float(data.get("delay"), 0.0, CREATE_MAX_DELAY) opts["ignore_robots"] = bool(data.get("ignore_robots")) opts.update(_create_scope(data)) opts.update(_create_capture_options(data, opts.get("engine"))) # What the form left unsaid is the admin's stored default, then the # engines' own: capture value, stored default, factory. from zimi.crawler import fill_stored_defaults fill_stored_defaults(opts, opts.get("engine")) elif mode == "video": opts["audio_only"] = bool(data.get("audio_only")) opts["limit"] = _create_int(data.get("limit"), 1, CREATE_VIDEO_LIMIT_CEILING) opts["max_bytes"] = _create_bytes(data.get("max_bytes")) opts["fmt"] = _create_video_format(data.get("format"), opts["audio_only"]) return mode, source, title, opts def _normalize_url_scheme(text): """Prepend https:// when someone typed a bare host — cnn.com, example.org/x — the way people actually type an address (Eric: "allow entering sites without https://"). An explicit scheme, a scheme-relative //host, a host:port, or a first segment with no dot (a typo or a local name) is left exactly as given for the validator to judge.""" t = text.strip() if "://" in t or t.startswith("//"): return t head = t.split("/", 1)[0] if ":" in head: # host:port or an unknown scheme — don't second-guess it return t if "." in head and " " not in head: return "https://" + t return t def _create_page_urls(source): """One address per line into the list the multi-page capture takes. Blank lines are skipped and duplicates collapse, because pasting a list is how people produce both. Every entry is checked here so the refusal names the line that is wrong rather than failing an hour later on page eleven.""" urls = [] for line in str(source).splitlines(): text = _normalize_url_scheme(line.strip()) if not text: continue # The whole-field ceiling is the cap times a URL, so it cannot catch a # single absurd line. Each address carries the single-source bound. if len(text) > CREATE_MAX_SOURCE: raise ValueError("one of those addresses is too long") parts = urllib.parse.urlsplit(text) if parts.scheme.lower() not in ("http", "https") or not parts.netloc: raise ValueError(f"not an http(s) URL: {text[:120]}") if text not in urls: urls.append(text) if not urls: raise ValueError("missing source") if len(urls) > CREATE_MAX_PAGE_URLS: raise ValueError( f"that is {len(urls)} addresses; {CREATE_MAX_PAGE_URLS} is the most " "one capture takes. A bigger set is a site crawl." ) return urls def _create_int(value, low, high): """Clamp an optional numeric form field into range; None when absent or unparseable, which every engine reads as "use your own default".""" if value in (None, ""): return None try: n = int(value) except (TypeError, ValueError): return None return max(low, n if high is None else min(high, n)) def _create_patterns(value): """A pattern field as a list: one string, or a list of them (the API's two shapes). Blank entries are not patterns.""" if value in (None, ""): return [] items = value if isinstance(value, list) else [value] return [ str(v).strip() for v in items if isinstance(v, (str, int, float)) and str(v).strip() ] def _create_scope(data): """Which pages a site capture walks into, checked now (an unknown scope or a regex that does not compile is refused here, not an hour into the job). Only what was set goes into the options.""" from zimi.crawler import CrawlScope from zimi.creator import CreateError raw = { "scope": ( (str(data.get("scope")).strip().lower() or None) if data.get("scope") not in (None, "") else None ), "include": _create_patterns(data.get("include")), "exclude": _create_patterns(data.get("exclude")), "extra_hops": _create_int(data.get("extra_hops"), 0, None), } try: CrawlScope(**raw) except CreateError as e: raise ValueError(str(e)) return {k: v for k, v in raw.items() if v not in (None, [], 0)} def _create_capture_options(data, engine, keys=None): """The capture options the table owns (time limit, sitemap, user agent, mobile, page timeout, cookies, what to leave out, workers), checked now like the scope is. An option the chosen engine cannot honor is dropped, as a stale block-ads box is: the form may have been filled before the engine picker moved. Cookies are the exception: dropping them would run the capture signed out, which nobody who typed them asked for.""" from zimi.crawler import NEW_OPTION_KEYS, capture_options from zimi.creator import CreateError keys = keys or NEW_OPTION_KEYS try: options = capture_options(data, engine, strict=False, keys=keys) if data.get("cookies") and "cookies" not in options: capture_options( {"cookies": data["cookies"]}, engine, strict=True, keys=keys ) return options except CreateError as e: raise ValueError(str(e)) def _create_details(data, *, stored): """The ZIM's own description, author, publisher and tags, checked now: the request's value, then the stored default for author and publisher.""" from zimi.crawler import DETAIL_KEYS, zim_details from zimi.creator import CreateError try: return zim_details({k: data.get(k) for k in DETAIL_KEYS}, stored=stored) except CreateError as e: raise ValueError(str(e)) def _create_stored_engine(): """The engine an admin stored as the default, when this machine can run it (an engine that has since gone missing is the fast one, not a refusal of every capture that said nothing).""" try: return _create_engine(_create_default("engine", None)) except ValueError: return None def _create_detail_kwargs(opts): """The ZIM's details in ``opts`` as the keyword arguments of the engines.""" from zimi.crawler import detail_kwargs return detail_kwargs(opts) def _create_float(value, low, high): """The fractional twin of ``_create_int`` — crawl delay is sub-second.""" if value in (None, ""): return None try: n = float(value) except (TypeError, ValueError): return None if n != n or n in (float("inf"), float("-inf")): # NaN / inf are not delays return None return max(low, min(high, n)) def _create_bytes(value): """A size budget typed as ``500M`` or ``2G``, in bytes; 0 is no limit. None when absent. Raises ValueError — which the route turns into a 400 naming the fix — when it is not a size at all, because a budget nobody can read is not a budget to guess at.""" if value in (None, ""): return None text = str(value).strip() if not text: return None if len(text) > CREATE_MAX_SIZE_TEXT: raise ValueError("that is not a byte size") # The crawler's parser is the one that already understands every form the # CLI accepts (512MiB, 2G, 1048576); the web form must not invent a second # dialect of the same field. from zimi.crawler import parse_size from zimi.creator import CreateError try: return parse_size(text) except CreateError as e: raise ValueError(str(e)) def _create_language(value): """An ISO 639-3 content language for the ZIM's metadata and its full-text index. Free text, so it is checked rather than clamped.""" if value in (None, ""): return None code = str(value).strip().lower() if not _CREATE_LANGUAGE_RE.match(code): raise ValueError("language must be a code like eng, fra or ara") return code def _create_engine(value): """Which capture engine a web capture asked for. None when nobody said, which every caller reads as "the fast one" — the default lives in the engines, not in three copies of the word "builtin".""" if value in (None, ""): return None name = str(value).strip().lower() if name not in CREATE_ENGINES: raise ValueError("unknown capture engine") # Refused HERE rather than an hour into a job: both of these are separate # installs, and a form that accepts a choice this machine cannot honour is # a form that lies. if name == "rendered" and not _create_browser_ready(): raise ValueError( "the rendered engine needs a browser this server does not have " "installed" ) if name == "singlefile" and not _create_singlefile_ready(): raise ValueError( "the singlefile engine needs the SingleFile CLI, and this server " "does not have it installed" ) if name == "zimit" and not _create_allows_private(): # Its browser is in Docker, out of the capture proxy's reach. from zimi.crawler import ZIMIT_PRIVATE_REFUSED raise ValueError(ZIMIT_PRIVATE_REFUSED) if name == "zimit" and not _create_zimit_ready(): raise ValueError( "the zimit engine runs openZIM's crawler in Docker, and this " "server has no Docker it can reach" ) if name == "alive" and not _create_alive_ready(): raise ValueError( "the alive engine needs both a browser and the warc2zim sidecar, " "and this server is missing at least one of them" ) return name def _create_blocking_engine(engine): """Whether the chosen engine can block anything. ``None`` is the fast engine — the default lives in the engines, and it does not block.""" return str(engine or "").strip().lower() in CREATE_BLOCKING_ENGINES def _create_variant_engine(engine): """Whether the chosen engine sweeps up responsive image variants, which is to say whether the switch means anything. ``None`` is the fast engine.""" return str(engine or "").strip().lower() in CREATE_VARIANT_ENGINES def _create_unlink_engine(engine): """Whether the chosen engine writes the pages itself, so links to other sites can be left out of them. ``None`` is the fast engine, which does.""" return (str(engine or "").strip().lower() or "builtin") in CREATE_UNLINK_ENGINES def _create_bool(value, default): """A checkbox that is CHECKED by default, read as a real bool. Every other bool on this form is off until someone turns it on, so absence and false are the same statement and ``bool(value)`` is the whole reader. This one is on until someone turns it OFF, which makes absence ambiguous — a client that omits the field means "I never drew this", and only an explicit ``false`` means "I unticked it".""" if value is None: return default if isinstance(value, str): # A form-encoded post has no JSON booleans; "false" from one of those # is a false, not a non-empty string. return value.strip().lower() not in ("", "0", "false", "no", "off") return bool(value) def _create_video_format(value, audio_only): """A named quality preset from the form, as the engine's format selector. Audio-only owns the format entirely, so a preset alongside it is dropped rather than fought over.""" if audio_only or value in (None, ""): return None key = str(value).strip() if key not in CREATE_VIDEO_FORMATS: raise ValueError("unknown video quality — pick one of the offered ones") return CREATE_VIDEO_FORMATS[key] def _create_kwargs(opts, *names): """Only the options the admin actually set. Every engine defaults these itself, and passing None would override the default with nothing.""" return {name: opts[name] for name in names if opts.get(name) is not None} def _create_out_dir(): """Web-created ZIMs land in /created — the folder the library files as its Created section, which is where an admin who just watched a job finish goes looking. A ZIM dropped in the library root instead is filed under its language with everything else and reads as missing (found the hard way: Eric's first real capture "didn't show in the created list"). The CLI keeps the root default; --out keeps winning there.""" return os.path.join(_srv.ZIM_DIR, "created") @_under_private_rule def _create_run(job, opts): """Drive the engine for one job. Imports are deferred to here: the writer stack and yt-dlp are heavy, and a server that never creates a ZIM should never pay for them. (Folder capture never reaches here — the web refuses it at validation; `zimi create ` is its only door.)""" if job.mode == "fieldmanual": from zimi import fieldguide return fieldguide.build_field_manual(progress=job.note) if job.mode == "page": # create_pages_zim hands a single URL to create_page_zim itself, so one # entry point covers both shapes — and it takes a progress callback, # which is what gives page mode a live log and a cancel at all. from zimi.creator import create_pages_zim return create_pages_zim( opts.get("urls") or [job.source], title=job.title or None, out_dir=_create_out_dir(), register=True, progress=job.note, **_create_kwargs( opts, "language", "engine", "block_ads", "capture_variants", "strip_links", "user_agent", "mobile", "page_timeout", "cookies", "skip_types", "max_file_bytes", ), **_create_detail_kwargs(opts), ) if job.mode == "site": from zimi.crawler import _StopFlag, create_site_zim # The finish-early control's handle on the crawl: the same stop flag # the CLI's SIGINT sets, owned by the job so the route can reach it. # Seeded from finish_requested so a request that raced job startup is # not lost in the gap. stop = _StopFlag() stop.hit = job.finish_requested job.stop_flag = stop return create_site_zim( job.source, title=job.title or None, out_dir=_create_out_dir(), register=True, progress=job.note, stop=stop, **_create_kwargs( opts, "max_pages", "max_depth", "max_bytes", "delay", "ignore_robots", "language", "engine", "block_ads", "capture_variants", "strip_links", "scope", "include", "exclude", "extra_hops", "time_limit", "sitemap", "user_agent", "mobile", "page_timeout", "cookies", "skip_types", "max_file_bytes", "workers", ), **_create_detail_kwargs(opts), ) if job.mode == "video": from zimi.video import create_video_zim return create_video_zim( job.source, title=job.title or None, out_dir=_create_out_dir(), audio_only=opts.get("audio_only", False), register=True, progress=job.note, **_create_kwargs(opts, "limit", "max_bytes", "fmt", "language"), **_create_detail_kwargs(opts), ) if job.mode == "reddit": from zimi.crawler import _StopFlag from zimi.reddot import create_reddit_zim stop = _StopFlag() stop.hit = job.finish_requested job.stop_flag = stop return create_reddit_zim( job.source, title=job.title or None, out_dir=_create_out_dir(), register=True, progress=job.note, stop=stop, ) if job.mode == "folder": from zimi.creator import create_folder_zim return create_folder_zim( job.source, title=job.title or None, out_dir=_create_out_dir(), register=True, progress=job.note, only=opts.get("only") or None, exclude=_create_folder_exclude(), **_create_kwargs(opts, "language"), **_create_detail_kwargs(opts), ) if job.mode == "import": from zimi.importer import import_archive return import_archive( job.source, title=job.title or None, out_dir=_create_out_dir(), register=True, sink=job.note, **_create_detail_kwargs(opts), ) # Only these reach here; validation refuses everything else. A job that # arrived with any other mode is a bug in the caller, not an input to run. raise ValueError(f"no web engine for mode {job.mode!r}") def _create_worker(job, opts): """Job thread body. Never raises — every outcome becomes job state.""" from zimi.creator import CreateError outcome: dict = {} try: result = _create_run(job, opts) outcome = { "ok": True, "result": { "name": _create_name_of(result.get("path")), # What the admin asked this ZIM to be called, when they said; # otherwise the title the capture found. The library lists # ZIMs by title, so a done card that only showed the filename # would name it differently from where it just landed # ("sive_rs_n-12" where the library says "Hell Yeah or No"). "title": job.title or str(result.get("title") or ""), "path": result.get("path"), "registered": bool(result.get("registered")), }, } # What the run counted, when it counted anything: every engine returns a # different subset, and a done card that can say "40 pages, 118 assets" # should not have to read it back out of the log. for key in ( "pages", "assets", "bytes", "files", "videos", "entries", "text_chars", ): if isinstance(result.get(key), int): outcome["result"][key] = result[key] # A page with almost no readable text is more likely a login, consent # or paywall gate than the article (medium.com: 227 characters to # every engine). The job log said so; the card says so too, because # nobody opens the log of a job that finished green. if result.get("thin_page"): outcome["result"]["thin_page"] = True if result.get("pictures"): outcome["result"]["pictures"] = dict(result["pictures"]) # The bound that ended a crawl early ("interrupted", "page cap (200)"), # when one did. The done card owes the admin that honesty — a ZIM that # says "40 pages" without saying "and I stopped there on purpose" reads # like a capture that thinks it got everything. if result.get("stopped"): outcome["result"]["stopped"] = str(result["stopped"]) # What the finished ZIM is actually MADE of — on-disk size and the # per-kind split behind it. "382 assets" says nothing about whether that # is mostly pictures or mostly fonts, and a number with no shape is not # information (Eric, on the done card: "show a storage breakdown, total # size of the zim and its components"). Best effort by construction: a # breakdown that cannot be read never costs a finished capture. try: from zimi.zimwriter import zim_content_breakdown shape = zim_content_breakdown(result.get("path")) if shape: outcome["result"]["shape"] = shape # And into the library, where every OTHER surface reads it from. # Without this the done card showed the composition while About # showed no bar at all for the same ZIM, seconds apart, until # the background worker came round — the two disagreeing about # a file that had just been measured. The measurement is in # hand; handing it over costs nothing and re-reading the file # to learn it again would cost the read. name = _create_name_of(result.get("path")) if name: _srv._shape_store({name: shape}) except Exception: log.debug("content breakdown skipped", exc_info=True) # Totals only the finished run knows: no line carried them, so they are # filed straight rather than parsed back out of prose. totals = [ _create_count_event(what, result[key]) for what, key in (("entries", "pages"), ("assets", "assets")) if isinstance(result.get(key), int) ] if totals: _create_emit(job, *totals) if result.get("registered"): _create_emit(job, {"t": "phase", "phase": "register", "detail": job.mode}) job.note("done") except _CreateCancelled: outcome = { "cancelled": True, "error": "cancelled — nothing was added to the library", } except CreateError as e: # The ONE place a caught message reaches the client verbatim, and it is # the point of the exception: CreateError carries the sentence that # names the fix ("capture it with zimit…", "yt-dlp is not installed…"). # Every other exception below stays generic. outcome = {"error": str(e)} except Exception: log.exception("ZIM creation failed (%s)", job.mode) outcome = {"error": "creation failed — see the server log for details"} _create_finish(job, **outcome) def _create_finish(job, **outcome): """Close a job ONCE and hand the slot to whatever is waiting. Both the worker thread and the watchdog can arrive here for the same job — a stalled job that later unwedges, say — so the first one wins and the second is a no-op. Otherwise a job could be finished twice and the queue advanced twice, running two creations at once on a machine chosen for being able to run one.""" with _create_lock: if job.done: return False # A stalled job's verdict outranks whatever the worker thread says next. # # The watchdog cannot kill a Python thread, so it kills the BROWSER — # and that is precisely what un-blocks the wedged worker, which then # raises "Target page, context or browser has been closed" and races # here to close the job with it. It usually won: the operator was told # a browser closed, by the code that closed it, instead of "no progress # for 10 minutes". Whoever arrives first now, the sentence is the one # the watchdog published before it touched anything. if job.stall_error and not outcome.get("stalled"): outcome = dict(outcome, stalled=True, error=job.stall_error) for key, value in outcome.items(): setattr(job, key, value) if not outcome.get("ok") and job.phase != "done": job.failed_phase = job.phase if job.phase != "done": job.phase = "done" job.finished = time.time() # Journal BEFORE done becomes visible: a status poll learns "done" # from the flag, and history must already agree by then — otherwise # one reply can say done while its own history says running. The # journal write is a ~1KB file behind its own lock; paying it inside # this lock is what makes the two truths one truth. job.done = True _create_journal_put(job) # The done event goes up with the flag, under the same lock: a poll that # sees done reads its events next and expects the last one to be done. # Published after the lock, one poll could land in the gap (CI did). job._push_events( [{"t": "phase", "phase": "done", "detail": _create_job_state(job)}] ) tail = list(job.lines[-CREATE_SERVER_LOG_LINES:]) if not job.ok else [] if tail: # The server's log (docker logs) has it too, for whoever reads there. log.warning( "Create %s failed (%s): %s\n %s", job.mode, job.source, job.error, "\n ".join(tail), ) # The create journal serves the Create page; the activity journal serves the # operator asking what has been happening to this library. A settled job is # one line in each; this one is written after the done event is published # and before waiters are released. _create_activity(job) job.settled.set() _create_start_next() return True def _create_watch(job): """Watchdog thread. A job that has not reported for CREATE_STALL_SECONDS is not slow, it is stuck on something that will never answer, and the honest thing is to say so and free the slot rather than spin a progress bar until somebody restarts the server. It cannot KILL the worker — Python threads do not work that way, and the thread is blocked inside a socket read. So it does both things it can: ask for cancellation, which lands if the engine ever reaches another checkpoint, and close the job out. Whatever the wedged step was doing carries on in the background until it times out; it writes to a temp file under a name of its own, so nothing it does can corrupt what the library already has.""" tick = min(CREATE_STALL_TICK, max(0.01, CREATE_STALL_SECONDS)) while not job.settled.wait(tick): since = job.progressed or job.started or job.queued_at if time.time() - since < CREATE_STALL_SECONDS: continue job.cancel_requested = True minutes = int(CREATE_STALL_SECONDS // 60) or 1 verdict = ( f"no progress for {minutes} minutes — giving up on this job. " "Whatever it was waiting for never answered. Nothing has been " "added to the library." ) # Published BEFORE anything is killed, and that order is the whole # point. Killing the browser is what frees the wedged worker to raise # its own error and reach _create_finish first; by then this sentence # is already on the job and _create_finish knows to keep it. job.stall_error = verdict # A cooperative cancel lands at the engine's next progress line, and a # wedged job by definition may never reach one. A browser is the one # thing that can be stopped from out here regardless: it is a child # process, and a signal does not need the job's thread to cooperate. _create_kill_browsers() log.warning( "create job %s (%s) made no progress for %ss — abandoning it", job.id, job.mode, int(CREATE_STALL_SECONDS), ) _create_finish(job, stalled=True, error=verdict) return def _create_launch(job, opts): """Start a claimed job: its worker thread and its watchdog.""" job.started = time.time() job.progressed = job.started # The opening phase, so the event stream describes itself from event 0 and # a client that joined late is never guessing which phase the counts below # belong to. _create_emit(job, {"t": "phase", "phase": job.phase, "detail": job.mode}) _create_journal_put(job) threading.Thread( target=_create_worker, args=(job, opts), daemon=True, name="zimi-create" ).start() threading.Thread( target=_create_watch, args=(job,), daemon=True, name="zimi-create-watch" ).start() def _create_start_next(): """Hand the slot to the head of the queue, if anything is waiting and the slot is actually free. The free check is not belt-and-braces: dropping a QUEUED job also finishes a job, and that must not start a second one on top of the one already running.""" global _create_job with _create_lock: if _create_job is not None and not _create_job.done: return if not _create_queue: return job, opts = _create_queue.pop(0) _create_job = job _create_launch(job, opts) def _create_limits(mode, opts): """The bounds a capture runs with: what was typed, else the engine's own default, so the page can show "1,234 of 10,000 pages" and name the limit that stopped it. 0 is no limit. Only the bounds a mode has.""" from zimi import crawler, video def bound(key, default): value = opts.get(key) return default if value is None else value if mode == "site" and opts.get("engine") == "zimit": # zimit enforces a page limit (browsertrix's --limit) and nothing else # Zimi hands it; a size counter out of 4 GB would be a promise nobody # keeps. return {"pages": bound("max_pages", crawler.DEFAULT_MAX_PAGES)} if mode == "site": return { "pages": bound("max_pages", crawler.DEFAULT_MAX_PAGES), "bytes": bound("max_bytes", crawler.DEFAULT_MAX_BYTES), } if mode == "video": return {"bytes": bound("max_bytes", video.DEFAULT_MAX_ZIM_BYTES)} return {} def _create_start(data, actor=None): """Validate, then either claim the single job slot or take a place in the queue behind whatever holds it. Returns ``(payload, status)`` ready to send. ``actor`` is whoever submitted it — captured here because the job outlives its request by an hour, and the activity journal is written at the end. """ if data.get("mode") == "fieldmanual": if not _srv.fieldguide_enabled(): return {"error": "not found"}, 404 # The Field Guide's own recipe: nothing is typed, so nothing is validated. mode, source, title, opts = "fieldmanual", "Field manual", "Field manual", {} else: try: mode, source, title, opts = _create_validate(data) except ValueError as e: return {"error": str(e)}, 400 global _create_job job = _CreateJob(mode, source, title) job.limits = _create_limits(mode, opts) # What to send again for "capture again with no limits": the request as it # was SUBMITTED, so a rerun is this job with its bounds lifted. Not the # validated opts: those are the engine's spelling (``fmt`` for the form's # ``format``), and a rerun of them lost the chosen video quality. from zimi.crawler import redacted_request job.request = redacted_request(data) if actor: job.actor = actor position = 0 with _create_lock: running = _create_job if (_create_job and not _create_job.done) else None if running is not None: if len(_create_queue) >= CREATE_QUEUE_MAX: return ( { "error": ( f"{CREATE_QUEUE_MAX} jobs are already waiting — " "let some of them finish first" ), "queued": len(_create_queue), }, 429, ) _create_queue.append((job, opts)) position = len(_create_queue) else: _create_job = job if running is not None: _create_journal_put(job) return { "status": "queued", "id": job.id, "mode": mode, "position": position, # What it is waiting behind, so the reply explains itself without a # second round trip. "running": {"id": running.id, "mode": running.mode}, }, 200 _create_launch(job, opts) return {"status": "started", "id": job.id, "mode": mode}, 200 def _fieldmanual_status(fieldguide): """The field-manual build as the Field Guide page polls it: the Create job's state (idle, running, done, error) with the build's own progress. Only text Create already sends the client reaches it.""" out = fieldguide.manual_status() with _create_lock: job = ( _create_job if (_create_job and _create_job.mode == "fieldmanual") else None ) queued = any(j.mode == "fieldmanual" for j, _o in _create_queue) if (job is not None and not job.done) or queued: out["state"] = "running" elif job is not None: out["state"] = "done" if job.ok else "error" out["message"] = "" if job.ok else job.error elif out["state"] == "running": out["state"] = "idle" if job is not None: out["id"] = job.id return out def _create_queue_view(): """The waiting jobs, in the order they will run.""" with _create_lock: waiting = list(_create_queue) return [ { "id": job.id, "mode": job.mode, "source": job.source, "title": job.title, "position": position, } for position, (job, _opts) in enumerate(waiting, 1) ] def _create_status(cursor, probe=False, events_cursor=0, history=False): """Poll payload. ``cursor`` is the client's line count so far and ``events_cursor`` its event count; the reply carries only what is new in each, plus the cursor to send next time.""" job = _create_job payload: dict = {"offline": _is_offline_mode(), "queue": _create_queue_view()} if probe: # Only on the page's first poll: one cheap subprocess, not per-second. payload["import_ready"] = _create_import_ready() # And WHERE this server keeps that sidecar, so the install command the # page offers targets this instance rather than whatever data dir the # operator's shell happens to resolve. `zimi import --setup` run from a # shell without the service's config sets up a perfectly good sidecar # for a different library, and the engine stays greyed out with nothing # on screen to say why (issue #61). payload["sidecar_dir"] = _create_sidecar_dir() # Whether the rendered engine's browser is installed here. Same # contract as import_ready: asked once, on the page's first poll, and # answered from a cache after that. payload["browser_ready"] = _create_browser_ready() payload["browser_install"] = _create_browser_install() payload["reddot_ready"] = _create_reddot_ready() # Archives the import mode may convert: what is in the library # folder, by name. No path is typed anywhere. payload["archives"] = _create_archives() payload["archives_dir"] = _create_archives_root() # And whether BOTH halves of the alive engine are here. Reported as its # own answer rather than left for the client to compute from the other # two: what the alive engine needs is the alive engine's business, and # a client that inferred it would have to be updated the day that # changes. payload["alive_ready"] = _create_alive_ready() # And whether yt-dlp is here. This one was missing, and its absence is # the whole reason the Create page offered a Video mode on an image # that had no yt-dlp in it — the Pillow bug's shape exactly: a # capability advertised by the client and absent from the server, with # nothing in between able to notice. The parity test in # tests/test_create_routes.py now fails if a mode is added without one. payload["video_ready"] = _create_video_ready() payload["singlefile_ready"] = _create_singlefile_ready() payload["zimit_ready"] = _create_zimit_ready() # The instance's stored capture defaults (Manage → Creator toggles), # so the form's checkboxes start where the admin set them instead of # at the factory state — the toggle would otherwise LOOK ignored. payload["capture_defaults"] = { "block_ads": _create_default("block_ads", CREATE_BLOCK_ADS), "capture_variants": _create_default( "capture_variants", CREATE_CAPTURE_VARIANTS ), } # Every stored default, and the text a field shows for it, so the # Advanced fields say what silence means. allow_private is the # admin's and stays out of this page. view = _create_defaults_view() view["defaults"].pop("allow_private", None) view["defaults_text"].pop("allow_private", None) payload.update(view) # None, not "", when no root is configured: the client reads it as a # yes/no about whether server-path capture exists on this instance at # all, and an empty string is a path that happens to be blank. payload["create_root"] = _create_root() or None if job is None: if history: payload["history"] = _create_history() payload.update( { "active": False, "done": False, "lines": [], "cursor": 0, "events": [], "event_cursor": 0, } ) return payload # tail()/event_tail() take _create_lock themselves — call them OUTSIDE # the snapshot block below (the lock is not reentrant). lines, next_cursor = job.tail(max(0, cursor)) events, next_events = job.event_tail(max(0, events_cursor)) # Snapshot the scalar fields UNDER the finish lock, and read history only # after: _create_finish journals before it lets done become visible inside # the same critical section, so this ordering is what guarantees one reply # never says done while its own history still says running. with _create_lock: payload.update( { "id": job.id, "active": not job.done, "mode": job.mode, "source": job.source, "title": job.title, "phase": job.phase, # Not the picture, just whether there is one to ask for. "has_shot": job.shot is not None, "lines": lines, "cursor": next_cursor, "events": events, "event_cursor": next_events, "done": job.done, "ok": job.ok, "cancelled": job.cancelled, "stalled": job.stalled, "failed_phase": job.failed_phase, "cancelling": job.cancel_requested and not job.done, "error": job.error, "result": job.result, "limits": getattr(job, "limits", {}), "request": getattr(job, "request", None), # See CREATE_CANCELLABLE_MODES: a cancel button on a job with # no progress callback to interrupt would be a lie. "cancellable": job.mode in CREATE_CANCELLABLE_MODES, # The finish-early pair: whether the button means anything # right now, and whether it has already been pressed. Both # computed here so the client never has to know the rules. "finishable": _create_finishable(job), "finishing": job.finish_requested and not job.done, "elapsed": round( (job.finished or time.time()) - (job.started or job.queued_at), 1 ), } ) if history: payload["history"] = _create_history() return payload def _create_cancel(job_id=None): """Cancel the running job, or drop a queued one by id. Cancelling the running job is cooperative: it lands at the engine's next progress line, so the reply promises a request, not a stop. Dropping a queued job is immediate — it has not started, so there is nothing to unwind.""" job_id = str(job_id or "").strip() if job_id: with _create_lock: for index, (job, _opts) in enumerate(_create_queue): if job.id == job_id: del _create_queue[index] break else: job = None if job is not None: _create_finish( job, cancelled=True, error="removed from the queue before it started" ) return {"status": "dequeued", "id": job_id}, 200 running = _create_job if running is None or running.done or running.id != job_id: return {"error": "no such creation job is waiting or running"}, 409 job = _create_job if job is None or job.done: return {"error": "no creation job is running"}, 409 job.cancel_requested = True return { "status": "cancelling", "id": job.id, "cancellable": job.mode in CREATE_CANCELLABLE_MODES, }, 200 def _create_finishable(job): """Whether "finish now" would still change anything: a site crawl that is in its network pass, not already being stopped some other way. From ``package``/``convert`` on the fetching is over and the offer would be theatre.""" return ( job.mode in CREATE_FINISHABLE_MODES and not job.done and not job.cancel_requested and job.phase in CREATE_FINISHABLE_PHASES ) def _create_finish_now(): """Stop fetching and package what is captured — the web's SIGINT. Sets the crawl's own stop flag, so the loop ends at the next PAGE boundary and everything already captured proceeds to packaging/conversion exactly as a Ctrl-C'd CLI crawl does. The reply promises a request, not a stop, for the same reason cancel's does: the flag is read between pages, and the page in flight finishes first. Distinct from cancel in the one way that matters — cancel discards, this keeps.""" job = _create_job if job is None or job.done: return {"error": "no creation job is running"}, 409 if job.mode not in CREATE_FINISHABLE_MODES: return {"error": "only a site capture can be finished early"}, 409 if job.cancel_requested: return {"error": "this job is already being cancelled"}, 409 already = job.finish_requested job.finish_requested = True flag = job.stop_flag if flag is not None: flag.hit = True if not already: try: # Through note() so the sentence lands in the log AND the journal's # progress clock moves — this is progress, of the human kind. job.note( "finish requested — completing the page in flight, then " "packaging everything captured so far" ) except _CreateCancelled: pass # a cancel landed in the gap above; it wins return {"status": "finishing", "id": job.id}, 200 def _is_offline_mode(): from zimi import p2p return bool(p2p.is_offline()) # ── the server-path root, now a reported fact only ────────────────────────── # # ``ZIMI_CREATE_ROOT`` is where the import and folder pickers look (the # library folder when unset). Both modes take a name from a listing under it, # never a typed path, and both are the primary admin's alone. CREATE_ROOT_ENV = "ZIMI_CREATE_ROOT" def _create_root(): """The ``ZIMI_CREATE_ROOT`` directory, resolved, or "" when unset. Read at call time, like every other environment-backed setting, so a config file published into the environment at startup is picked up without a second resolution path. The pickers list under it (_create_archives_root).""" raw = os.environ.get(CREATE_ROOT_ENV, "").strip() if not raw: return "" return os.path.realpath(os.path.expanduser(raw)) def _create_sidecar_dir(): """Where THIS server looks for the warc2zim sidecar, or None.""" try: from zimi.importer import sidecar_status return sidecar_status().get("dir") or None except Exception: log.exception("sidecar dir probe failed") return None # Where the import mode looks for archives: ``ZIMI_CREATE_ROOT`` when set, # else the library folder; every subfolder inside, to a depth and a count # that keep a picker a picker (Eric: "Allow defining a create or import # directory instead of that path and support subdirectories within"). CREATE_ARCHIVE_MAX_DEPTH = 8 CREATE_ARCHIVE_MAX_FILES = 500 def _create_archives_root(): return _create_root() or _srv.ZIM_DIR def _create_archives(): """The WARC/WACZ files under the import directory, ``[{name, size_bytes}]``, newest first. ``name`` is the path relative to that directory, with "/", and is the only thing the form ever sends back.""" from zimi.importer import ARCHIVE_EXTS root = _create_archives_root() found = [] for dirpath, dirnames, filenames in os.walk(root): rel_dir = os.path.relpath(dirpath, root) depth = 0 if rel_dir == "." else rel_dir.count(os.sep) + 1 # Hidden folders are the library's own (.zimi, .data) and nobody's # archives; past the depth the walk stops descending. dirnames[:] = ( sorted(d for d in dirnames if not d.startswith(".")) if depth < CREATE_ARCHIVE_MAX_DEPTH else [] ) for n in filenames: if not n.lower().endswith(ARCHIVE_EXTS) or n.startswith("."): continue full = os.path.join(dirpath, n) try: st = os.stat(full) except OSError: continue if not os.path.isfile(full): continue rel = n if rel_dir == "." else os.path.join(rel_dir, n) found.append( { "name": rel.replace(os.sep, "/"), "size_bytes": st.st_size, "mtime": st.st_mtime, } ) if len(found) >= CREATE_ARCHIVE_MAX_FILES: break if len(found) >= CREATE_ARCHIVE_MAX_FILES: break found.sort(key=lambda a: -a["mtime"]) for a in found: del a["mtime"] return found def _create_archive_path(name): """The full path of an archive the picker listed, or ValueError. Only a name the listing would produce is accepted: no separators the listing did not put there, nothing outside the library folder.""" name = (name or "").strip().replace("\\", "/") if not name or name not in {a["name"] for a in _create_archives()}: raise ValueError("choose an archive from the list") path = join_inside(_create_archives_root(), *name.split("/")) if path is None: raise ValueError("choose an archive from the list") return path # ── Folder mode: the tree picker and the selection it sends ──────────────── # # The tree is listed one level per request (never a recursive walk, which on # a NAS share would be the expensive thing), under the same root import uses. # Every path in and out is RELATIVE to that root; folderfiles.resolve refuses # absolute paths, "..", hidden parts and any symlink on the way, then checks # the real path is still inside. Zimi's own data folder is never shown. CREATE_DISK_MODES = ("import", "folder") CREATE_FOLDER_PROBE_ENTRIES = 5000 CREATE_FOLDER_PROBE_SECONDS = 3.0 CREATE_FOLDER_PROBE_EXAMPLES = 6 def _create_folder_exclude(): """What the picker and a build never read: Zimi's data folder (its sidecars and caches live in it).""" return [p for p in (getattr(_srv, "ZIMI_DATA_DIR", None),) if p] def _create_tree(rel, offset): """``(payload, status)`` for one level of the create root.""" from zimi import folderfiles root = _create_archives_root() try: listing = folderfiles.list_level( root, rel, offset=offset, exclude=_create_folder_exclude() ) except folderfiles.OutsideRoot as e: return {"error": str(e)}, 400 except FileNotFoundError: return {"error": "that folder is not there any more"}, 404 except OSError: log.exception("create tree listing failed") return {"error": "that folder cannot be read"}, 500 # The root's own name, so the picker can label its top row; the path # itself is already on the page (archives_dir) for the same viewer. listing["root_name"] = ( os.path.basename(os.path.realpath(root).rstrip(os.sep)) or root ) return listing, 200 def _create_folder_selection(source, only): """``(folder fs path, [relative paths])`` for a folder request, or ValueError with a sentence for the page.""" from zimi import folderfiles if only is not None and not isinstance(only, list): raise ValueError("choose files from the tree") root = _create_archives_root() exclude = folderfiles.real_paths(_create_folder_exclude()) try: fs, _rel = folderfiles.resolve(root, "" if source == "." else source, exclude) if not os.path.isdir(fs): raise ValueError("choose a folder from the tree") picked = folderfiles.normalize_only(fs, [str(p) for p in (only or [])], exclude) except folderfiles.OutsideRoot as e: raise ValueError(str(e)) except FileNotFoundError: raise ValueError("that is no longer in the folder; refresh the tree") return fs, picked def _probe_folder(source, only): """What a build of this selection would hold, bounded by an entry count and a clock: families, bytes, what is left out and why, and the metadata the sidecars name.""" from zimi import folderfiles exclude = folderfiles.real_paths(_create_folder_exclude()) deadline = time.monotonic() + CREATE_FOLDER_PROBE_SECONDS files, truncated = [], False for pair in folderfiles.walk(source, only or None, exclude): if len(files) >= CREATE_FOLDER_PROBE_ENTRIES or time.monotonic() > deadline: truncated = True break files.append(pair) plan = folderfiles.plan(source, only or None, files=files, exclude=exclude) families = {} size = 0 plays_some = 0 for fs, rel, fam in plan["items"]: # A cover or an icon is carried along with what it belongs to; it is # not one of the gallery's pictures. if fam == "image" and rel in plan["belongs"]: fam = "asset" families[fam] = families.get(fam, 0) + 1 try: size += os.path.getsize(fs) except OSError: pass if fam == "video" and not folderfiles.plays_everywhere(rel): plays_some += 1 meta = plan["folder"] return { "ok": bool(plan["items"]), "final_url": "", "title": meta.get("title") or os.path.basename(source.rstrip(os.sep)), "content_type": "", "files": len(plan["items"]), "bytes": size, "families": families, "unsupported": len(plan["unsupported"]), "unsupported_examples": [ {"path": rel, "reason": reason} for rel, reason in plan["unsupported"][:CREATE_FOLDER_PROBE_EXAMPLES] ], "plays_some": plays_some, "metadata": meta, "metadata_file": plan["folder_sidecar"], "described": len(plan["sidecars"]), "truncated": truncated, "warning_key": None if plan["items"] else "create_warn_folder_empty", } def _create_reddot_ready(): """True when the Reddit maker (ArcticZim) is already installed, which decides whether a subreddit can be made offline.""" try: from zimi.reddot import sidecar_status return bool(sidecar_status().get("installed")) except Exception: log.exception("ArcticZim sidecar probe failed") return False def _create_import_ready(): """True when the warc2zim sidecar is already installed — the one thing that decides whether archive import can run on a machine with no internet.""" try: from zimi.importer import sidecar_status return bool(sidecar_status().get("installed")) except Exception: log.exception("warc2zim sidecar probe failed") return False def _reddit_ready(): """Whether the ArcticZim sidecar is installed (``zimi create --setup-reddit``).""" try: from zimi import reddot return bool(reddot.sidecar_status()["installed"]) except Exception: return False def _reddit_version(): """ArcticZim has no releases; Zimi pins it to a commit, which is its version (short), when the sidecar is installed.""" try: from zimi import reddot return reddot.ARCTICZIM_COMMIT[:7] if _reddit_ready() else None except Exception: return None def _create_browser_ready(): """True when the rendered engine can actually run here — Playwright importable AND a Chromium that launches. Finding out costs a browser launch, so the renderer caches the answer for the life of the process and this is a dictionary lookup after the first call. It is asked on the Create page's first poll and when a request names the rendered engine; never per second, and never per page.""" try: from zimi.renderer import browser_available, browser_status_known # The renderer remembers its answer for the life of the process. A # "yes" is a fact about the install and stays; a "no" is the state # before the admin ran the command this pane printed, so it is asked # again (one browser launch, on the probe thread, at most every # CREATOR_PROBE_TTL while someone has the page open). Otherwise an # install made while the server runs never shows until a restart: # "I successfully download what it requires but the app says the # browser engine wasn't installed" (r/Kiwix, 2026-09-19). known = browser_status_known() if known is not None and known[0]: return True return bool(browser_available(refresh=known is not None)) except Exception: log.exception("rendered-engine probe failed") return False def _create_browser_version(): """The rendered engine's Chromium and Playwright, as its probe saw them.""" try: from zimi.renderer import browser_version return browser_version() except Exception: log.exception("rendered-engine version failed") return None def _create_browser_install(): """The command that installs the rendered engine INTO THIS SERVER's Python, or None when there is no such command (a frozen desktop build, the Docker image). "pip install" in the shell that happens to be open lands in whatever Python that shell has; under uv or a venv that is not the one Zimi runs in, and the pane keeps saying not installed.""" if getattr(sys, "frozen", False) or getattr(sys, "_MEIPASS", None): return None exe = sys.executable or "" if not exe: return None norm = exe.replace("\\", "/") if "/uv/tools/" in norm or "/.local/share/uv/" in norm: return "uv tool install --force 'zimi[browser]' && uv tool run --from zimi playwright install chromium" q = shlex.quote(exe) return f"{q} -m pip install 'zimi[browser]' && {q} -m playwright install chromium" def _create_video_ready(): """True when a video capture can run here — yt-dlp is a soft dependency. Its own probe, like the other three, because "can this machine do the thing the form is offering" is a question every mode has to be able to answer for itself. The day video needs a second half (ffmpeg, say), this is where that gets decided and no caller changes.""" try: from zimi.video import video_available return bool(video_available()) except Exception: log.exception("video-engine probe failed") return False def _create_zimit_ready(): """True when a Docker this server can actually talk to exists. zimit is not a library, it is a container, so "installed" means a daemon answering — which is why this asks the CLI rather than checking a path.""" try: from zimi.crawler import _docker_cli return bool(_docker_cli()) except Exception: log.exception("zimit-engine probe failed") return False def _create_singlefile_ready(): """True when the SingleFile CLI is on PATH here. Its own probe, like the other engines'. A form that offers a capture this machine cannot perform is a form that lies — see the parity test.""" try: from zimi.singlefile import singlefile_available return bool(singlefile_available()) except Exception: log.exception("singlefile-engine probe failed") return False def _create_alive_ready(): """True when the alive engine can run here — which needs BOTH halves, the browser to record with and the warc2zim sidecar to convert with. Deliberately its own probe rather than ``browser and import`` computed at the call site: the two halves are independent facts, the engine that owns them is the one that should decide what "ready" means, and the client is told each of the three separately so it can say which one is missing.""" try: from zimi.alive import alive_available return bool(alive_available()) except Exception: log.exception("alive-engine probe failed") return False # ── the Creator inventory: what Zimi has made, by type ────────────────────── # # The provenance a Zimi-made ZIM carries (http.py's kind machinery) names the # MODE it was captured with; the Creator pane groups those modes into the small # set of types a person thinks in. Several modes share a type: the single-page # and multi-page engines both stamp a page capture, and a bookmark export # stamps "bookmarks" — so the type the breakdown counts by is not always the # raw mode string. "edit" is here for the edit engine to fill; nothing stamps it # yet, and a bucket that is always present but sometimes zero is a stabler # contract than one that appears the day the first edit lands. _CREATOR_TYPES = ( "page", "site", "video", "import", "reddit", "folder", "export", "edit", ) _CREATOR_TYPE_BY_MODE = { "page": "page", "pages": "page", "site": "site", "video": "video", "import": "import", "reddit": "reddit", "folder": "folder", "bookmarks": "export", "edit": "edit", "edited": "edit", } def _creator_type(mode, kind=None, basename=""): """The Creator breakdown bucket for a made-here ZIM. The provenance ``mode`` decides it when present; a warc2zim ZIM (alive engine, or an import) carries no X-Zimi-History and so no mode, so we fall back to the scope token the creator wrote into the filename (``..._site``, ``-page``, ``-video``) and then to the recorded engine. Better an honest "Site" than a bare "Zimi" on a ZIM whose own name says what it is.""" if mode: return _CREATOR_TYPE_BY_MODE.get(mode, mode) low = (basename or "").lower() for token, bucket in ( ("video", "video"), ("site", "site"), ("page", "page"), ("folder", "folder"), ): if token in low: return bucket engine = (kind or {}).get("engine") if engine in ("alive", "rendered"): return "site" # a recorded web capture with no history record return "other" def _creator_inventory(): """``(counts, rows)`` for every ZIM Zimi made, wherever it lives. One walk of the library. The per-file provenance memo in http.py answers each ZIM at most once per process, so after the cold pass this is a dict walk. ``counts`` partitions the made-here ZIMs across ``_CREATOR_TYPES`` (every bucket present, zero when nothing of that type exists); ``rows`` carries one entry per ZIM with the raw sortable fields and leaves the ordering to the client.""" from zimi import http as _http counts = {t: 0 for t in _CREATOR_TYPES} rows = [] for entry in _srv.list_zims(): kind = _http._zim_kind_for(entry) if not kind: continue ctype = _creator_type( kind.get("mode"), kind=kind, basename=entry.get("file", "") ) if ctype in counts: counts[ctype] += 1 rows.append( { "name": entry.get("name", ""), "title": entry.get("title") or entry.get("name", ""), "type": ctype, "size_bytes": entry.get("size_bytes", 0), # The creation timestamp the provenance record carries, or None # for a Zimi ZIM old enough to predate the stamp — the client # sorts the dated ones and leaves the rest where they fall. "created_ts": kind.get("ts"), "path_basename": entry.get("file", ""), } ) # What this walk learned, into the cache that survives a restart. Without # it the walk above reopens every archive in the library after each one. _http.flush_zim_kinds() return counts, rows def _creator_payload(): """Everything the Manage view's Creator section shows, in one read. Gathered here rather than left scattered across the create page's own poll because these are SERVER facts — what this machine can capture with, where it is allowed to write, what it refuses by default, what is waiting — and an admin looking for them should not have to open the create form and infer them from which options are greyed. The probes are the reason this is its own endpoint and not a field on the status poll. They are also the reason it never waits for them: finding out whether the rendered engine works means LAUNCHING a browser, which is 2.5s on a NAS, and the sidecar's version is a subprocess of its own. Answered once per process, which sounds fine until you notice a deploy restarts the process — so every deploy, the first admin to open Manage -> Creator sat watching "Loading…" (Eric, 2026-09-11: "still super slow to load"). So the capabilities are probed on a thread and this returns what is known. ``probing`` is True while the answer is still being found out, and the three capability fields are None rather than False — "we have not looked" is not "you cannot do this", and showing the second for the first is how a pane tells an admin their browser is missing when it is not.""" known = _creator_capabilities() return { "browser_ready": known["browser_ready"] if known else None, "browser_version": known.get("browser_version") if known else None, "alive_ready": known["alive_ready"] if known else None, "sidecar": known["sidecar"] if known else None, # ArcticZim, the subreddit engine: two files on disk, no probe. "reddit_ready": _reddit_ready(), "reddit_version": _reddit_version(), "probing": known is None, # None, not "", when no root is configured — the same shape the create # page's probe uses, so both readers treat "unset" the same way. "create_root": _create_root() or None, # For the setup commands the pane prints: `zimi import --setup` from a # terminal without this server's config installs into another data # dir, and the engine stays grey (#61). The pane names this one. "data_dir": _srv.ZIMI_DATA_DIR, "block_ads_default": _create_default("block_ads", CREATE_BLOCK_ADS), "capture_variants_default": _create_default( "capture_variants", CREATE_CAPTURE_VARIANTS ), **_create_defaults_view(), "queue": len(_create_queue_view()), "offline": _is_offline_mode(), # Held off while the password is off (_create_allows_private). "private_locked": open_from_settings(), } # The probed half of the Creator pane: found out on a thread, kept, refreshed # behind the answer already on screen. _creator_probe_lock = threading.Lock() _creator_probed = None # the last finished dict, or None until the first lands _creator_probed_at = 0.0 _creator_probing = False # How stale the last answer may be before a request quietly starts another. # These are installation facts, so they change about as often as somebody runs # an install command — and when they do, the pane is usually the thing they are # looking at, because it is where the command came from. Short enough to notice # that; long enough that clicking around Manage does not launch browsers. CREATOR_PROBE_TTL = 20.0 def _creator_capabilities(): """What this machine can capture with, or None before the first answer. Never blocks. Whatever was last found out is returned at once and a refresh runs behind it when that answer has gone stale, so `zimi import --setup` in another window still shows up in the pane that told the admin to run it — which it did when every request probed, and which a probe-once cache would have quietly taken away.""" global _creator_probing with _creator_probe_lock: answer = _creator_probed fresh = (time.time() - _creator_probed_at) < CREATOR_PROBE_TTL if _creator_probing or (answer is not None and fresh): return answer _creator_probing = True threading.Thread( target=_creator_probe_pass, daemon=True, name="creator-probe" ).start() return answer def _creator_probe_pass(): """One sweep of the capability probes, off the request thread.""" global _creator_probed, _creator_probed_at, _creator_probing answer = None try: answer = { "browser_ready": _create_browser_ready(), "alive_ready": _create_alive_ready(), "sidecar": _creator_sidecar(), } answer["browser_version"] = _create_browser_version() except Exception: log.exception("creator capability probe failed") with _creator_probe_lock: # A failed sweep keeps the last good answer rather than blanking the # pane; only the stamp moves, so the next request tries again. if answer is not None: _creator_probed = answer _creator_probed_at = time.time() _creator_probing = False def _creator_sidecar(): sidecar = {"installed": False, "version": None} try: from zimi.importer import sidecar_status status = sidecar_status() sidecar = { "installed": bool(status.get("installed")), "version": status.get("version"), # WHERE this server looks. The client pastes it into the install # command, because `zimi import --setup` from a shell resolves its # own data dir — and a shell that lacks the service's config # resolves a different one, installs a perfectly good sidecar into # it, and leaves the engine greyed out with no way to see why # (issue #61: set up against the default /zims while the service # served /mnt/nas/ZIM). "dir": status.get("dir"), } except Exception: log.exception("sidecar status probe failed") return sidecar def _creator_inventory_payload(): """The Creator pane's made-here breakdown + sortable list, on its OWN endpoint. Gathering it is a provenance walk of the whole library — the slow, unbounded half of the pane — so it never rides the pane's own fast payload. ``counts`` is a fixed-shape dict over _CREATOR_TYPES; ``list`` is unsorted rows the client orders.""" counts, rows = _creator_inventory() return {"created_counts": counts, "created_list": rows} def _auto_update_view(): """The ZIM auto-updater's state: whether it runs, how often, when it last ran and when it runs next. ``last_check`` is process memory — the updater stamps it at the top of each cycle and nothing persists it — so it is None after a restart, and the client must say "not since this server started" rather than "never". ``next_check`` is derived from it rather than stored, because the loop sleeps a fixed interval after each pass; None when there is nothing to derive it from, which is either disabled or not-yet-run.""" freq = _srv._auto_update_freq last = _srv._auto_update_last_check interval = _srv._FREQ_SECONDS.get(freq) nxt = None if _srv._auto_update_enabled and last and interval: nxt = last + interval return { "enabled": _srv._auto_update_enabled, "frequency": freq, "locked": _srv._auto_update_env_locked, "last_check": last, "next_check": nxt, } def _auto_update_coverage(): """Which installed ZIMs the auto-updater can actually maintain, and why it passes over the rest. Not the opt-out list (set_auto_update_skip keeps that): the updater's real reach, made visible: matching an installed file to a newer edition needs a dated filename (``…_YYYY-MM.zim``), so anything without one is invisible to it. That is most locally created ZIMs, and until now the only way to discover it was to notice a file never updating. Returns ``{"tracked": [names], "skipped": [{"name", "reason"}]}``, sorted, so the client can say the true sentence in the reader's language.""" tracked, skipped = [], [] for name, path in sorted(_srv.get_zim_files().items()): _base, date = _srv._extract_zim_date(os.path.basename(path)) if date: tracked.append(name) else: # One reason today, named rather than implied, so a second reason # is a new value here and not a new shape at the call site. skipped.append({"name": name, "reason": "undated"}) return {"tracked": tracked, "skipped": skipped} def _create_kill_browsers(): """Kill any headless browser a create job left running. Only reached when the watchdog gives up on a job: by then the job's thread is wedged somewhere that will not return, so the engine's own `finally` cannot be relied on to close its browser. Imported by NAME rather than directly, so a server whose jobs never render a page never loads the renderer at all.""" module = sys.modules.get("zimi.renderer") if module is None: return try: module.shutdown_sessions() except Exception: log.exception("could not shut down a rendered capture's browser") # ============================================================================ # Pre-flight probe — look before you leap # # The round-1 verdict on the Create page was "feels like a shot in the dark", # and it was fair: the form asked for a server path you cannot see, a language # code you have to know and a byte budget with no sense of scale, then ran for # an hour on whatever it got. The probe runs the half of each job that only # LOOKS — count a folder, fetch one page, list a playlist — and hands back what # the real run would find, so the answer arrives before the commitment. # (A folder's probe counts what the selection holds: _probe_folder.) # # It writes nothing, downloads no media, and crawls no links. Every mode is # bounded by both a count and a clock, because a preview that outlasts your # patience has failed at being a preview. # # The reply is STRUCTURED, never prose: counts, byte totals and i18n KEYS for # any warning. Server-authored English sentences in a preview would be the one # corner of this app that cannot be translated. # ============================================================================ CREATE_PROBE_TIMEOUT = 12.0 CREATE_PROBE_MAX_EXAMPLES = 6 CREATE_PROBE_VIDEO_LIMIT = 12 _HTML_LANG_RE = re.compile( r"]*\blang\s*=\s*[\"']([a-zA-Z]{2,3}(?:[-_][a-zA-Z0-9]+)*)[\"']", re.IGNORECASE, ) _META_LANG_RE = re.compile( r"]+http-equiv\s*=\s*[\"']content-language[\"'][^>]*" r"content\s*=\s*[\"']([a-zA-Z]{2,3}(?:[-_][a-zA-Z0-9]+)*)", re.IGNORECASE, ) def _iso3_of(tag): """A BCP-47-ish tag from a document (``fr``, ``en-GB``, ``fra``) as the ISO 639-3 code the ZIM metadata and the full-text index both want. Returns None for anything not recognised — a wrong language is worse than none, because it silently stems the index against the wrong rules.""" if not tag: return None primary = re.split(r"[-_]", str(tag).strip())[0].lower() if len(primary) == 3 and primary in _srv._ISO639_3_TO_1: return primary if len(primary) == 2: for three, two in _srv._ISO639_3_TO_1.items(): if two == primary: return three return None def _detect_html_language(text): """The document's own declaration of what language it is in. This is a read of ``, not statistical detection: it is what the author said, it costs one regex, and it is right far more often than a guess over a few hundred words of boilerplate would be.""" for pattern in (_HTML_LANG_RE, _META_LANG_RE): m = pattern.search(text or "") if m: code = _iso3_of(m.group(1)) if code: return code return None @_under_private_rule def _probe_url(source, *, want_robots=False, engine=None): """Fetch ONE page and report what the capture would be working with: where it really landed, what it is called, whether it is an application shell that would produce a ZIM full of loading spinners, and — for a crawl — what the site's robots.txt has to say about the seed. ONE plain HTTP fetch, whichever engine the job will use. Previewing a rendered capture by rendering it would cost a browser launch per keystroke settled, and the answers the preview gives — where the URL lands, what it is called, what language it declares — are the same either way. What the engine changes is the VERDICT: an application shell is a refusal for the fast engine and the entire point of the rendered and alive ones.""" from zimi.creator import ( _decode_page, _fetch_page, _page_title_from_html, looks_like_app, looks_like_spa, ) final_url, data, ctype, clang = _fetch_page( source, timeout=CREATE_PROBE_TIMEOUT, max_redirects=3 ) page = _decode_page(data, ctype) is_html = "html" in (ctype or "").lower() spa = bool(is_html and looks_like_spa(page)) # A page can be server-rendered and still be an application. See # looks_like_app: what the fast engine drops there is invisible until # somebody clicks, which is the worst way to find out. app = bool(is_html and looks_like_app(page)) # Both browser engines answer the SPA question the same way, so they are # one flag rather than two comparisons that could drift apart. rendered = engine in ("rendered", "alive") # The document's own `` first, the Content-Language header # second: the header is server configuration and is often a site-wide # default, while the attribute was written about this page. language = _detect_html_language(page) if is_html else None out = { "ok": is_html and (not spa or rendered), "final_url": final_url, "title": _page_title_from_html(page, "") if is_html else "", "content_type": (ctype or "").split(";")[0].strip(), "bytes": len(data), "spa": spa, "app": app, "language": language or _iso3_of(clang), "warning_key": None, } if is_html: # What the preview can honestly promise. `bytes` above is the DOCUMENT's # weight and the client no longer shows it as a size — CNN's is a sixth # of the finished ZIM. The file count is a fact known without fetching # anything, and the icon is what puts a face on a ninety-second wait. # # Both come from creator's helpers rather than being counted again # here: this endpoint and the CLI probe answering the same question # differently is exactly how one of them ended up never answering it. from zimi.creator import _probe_icon_data_uri, page_asset_refs try: out["assets"] = len(page_asset_refs(page, final_url)) except Exception: log.exception("probe could not count assets for %s", loggable(final_url)) out["icon"] = _probe_icon_data_uri(final_url, CREATE_PROBE_TIMEOUT, page) if not is_html: out["warning_key"] = "create_warn_not_html" elif spa and rendered: # Not a warning: a page built in JavaScript is the case these engines # exist for. Said out loud anyway, because "this page has no # server-rendered text" is the reason the capture will take twenty # seconds instead of one — and the two engines promise different things # about it, so they say different sentences. out["note_key"] = ( "create_note_spa_alive" if engine == "alive" else "create_note_spa_rendered" ) elif spa: # The engine's own refusal, verbatim: it names zimit, which is the fix. from zimi.creator import SPA_REFUSAL out["warning_key"] = "create_warn_spa" out["detail"] = SPA_REFUSAL if want_robots and out["ok"]: out.update(_probe_robots(final_url)) return out def _probe_robots(final_url): """What the site asks crawlers to do. Reported, never enforced here — the crawl itself enforces it, and the override lives in Advanced.""" from zimi.crawler import _origin_of, _robots_allows, load_robots try: robots = load_robots(_origin_of(final_url), timeout=CREATE_PROBE_TIMEOUT) except Exception: log.exception("robots probe failed") return {} allowed = _robots_allows(robots, final_url) if robots else True return { "robots_allowed": bool(allowed), "warning_key": None if allowed else "create_warn_robots", } @_under_private_rule def _probe_video(source, limit): """List the playlist without downloading a frame of it.""" from zimi.video import _flat_entries, _yt_dlp mod = _yt_dlp() if mod is None: from zimi.video import INSTALL_HINT return { "ok": False, "warning_key": "create_warn_no_ytdlp", "detail": INSTALL_HINT, } head, entries = _flat_entries(mod, source, limit or CREATE_PROBE_VIDEO_LIMIT) titles = [ str(e.get("title") or "") for e in entries[:CREATE_PROBE_MAX_EXAMPLES] if isinstance(e, dict) ] return { "ok": bool(entries), "videos": len(entries), "playlist": str(head.get("title") or ""), "uploader": str(head.get("uploader") or head.get("channel") or ""), "examples": titles, "language": _iso3_of(head.get("language")), "warning_key": None if entries else "create_warn_empty_playlist", } # The old folder picker (`/manage/create/browse`, which took a server path) # stays a 410; the tree picker (`/manage/create/tree`, `_create_tree`) takes # only paths relative to the create root. def _probe_claims_video(source): """Whether this address belongs to a video-first host, so the create page can move its own mode chip. False when yt-dlp is absent or the source is a list of addresses. Deliberately NOT `claims_url`, which is true for any yt-dlp extractor: a CNN or BBC article matches one, because those pages embed a player, and the page then refused to capture them as pages at all.""" if not source or "\n" in str(source).strip(): return False try: from zimi.video import claims_video_host, video_available return video_available() and claims_video_host(str(source).strip()) except Exception: log.debug( "video claim check failed for %s", loggable(repr(source)), exc_info=True ) return False def _create_probe(data): """Validate the request exactly as a real run would, then look. Returns ``(payload, status)``.""" # Imported here rather than at module scope: naming the exception is the # only reason this module needs the writer stack, and a server that never # previews a capture should not pay to import it. from zimi.creator import CreateError try: mode, source, _title, opts = _create_validate(data) except ValueError as e: return {"error": str(e)}, 400 job = _create_job if job is not None and not job.done: # The probe competes with the job for the same disk and the same # network. One at a time here too. return {"error": "a ZIM is being created — wait for it to finish"}, 409 try: # The address comes first on the page now and the mode follows from # it: a YouTube or PeerTube address typed under Web page is a video, # and yt-dlp is the authority on that. Answer as the video probe, with # the mode it belongs to; the page moves its chip to match. if mode in ("page", "site") and _probe_claims_video(source): mode = "video" elif mode == "video" and not _probe_claims_video(source): # And back: the chip moved to Video for the last address, and # this one is a page. yt-dlp's catch-all would only fail on it. mode = "page" if mode == "reddit": from zimi.reddot import sidecar_status result = { "ok": True, "final_url": "https://www.reddit.com/r/%s/" % source, "title": "r/%s" % source, "subreddit": source, "content_type": "", "bytes": 0, "warning_key": None, "reddot_ready": bool(sidecar_status().get("installed")), } elif mode == "folder": result = _probe_folder(source, opts.get("only")) elif mode == "import": # The archive is on disk and validation already found it; the # preview is its size and whether the helper is here. result = { "ok": True, "final_url": "", "title": os.path.basename(source), "content_type": "", "bytes": os.path.getsize(source), "warning_key": None, "import_ready": _create_import_ready(), } elif mode == "video": result = _probe_video(source, opts.get("limit")) elif mode == "page": # One fetch, not twenty: the preview answers "is this the kind of # thing that captures well?", and the first address answers it. The # count is what makes the rest of the list visible. urls = opts.get("urls") or [source] result = _probe_url(urls[0], engine=opts.get("engine")) result["urls"] = len(urls) else: result = _probe_url( source, want_robots=(mode == "site"), engine=opts.get("engine") ) except CreateError as e: # Already a user-facing sentence, and the one that names the fix. return {"ok": False, "mode": mode, "detail": str(e)}, 200 except Exception: log.exception("create probe failed (%s)", loggable(mode)) return { "ok": False, "mode": mode, "warning_key": "create_warn_probe_failed", }, 200 result["mode"] = mode result["source"] = source return result, 200 # ============================================================================ # Manage GET Routes # ============================================================================ def _bt_still_downloading(raw): """True when a list_managed() row is an in-flight BT download rather than a seed: total known, not yet complete, and the engine hasn't flagged it a seeder. Shared by the /manage/seeding list (which hides such rows) and the stop_all seeding action (which must not cancel them — their payload lives in staging, where remove(delete_files=True) really deletes).""" completed = int(raw.get("completedLength", 0)) total = int(raw.get("totalLength", 0)) seeder = raw.get("seeder") in ("true", True) return ( raw.get("status", "unknown") not in ("error", "complete") and not seeder and total > 0 and completed < total ) def handle_manage_get(handler, parsed, params): """Handle all GET /manage/* requests. Called from ZimHandler.do_GET.""" def param(key, default=None): return params.get(key, [default])[0] if not _srv.ZIMI_MANAGE: return handler._json( 404, {"error": "Library management is disabled. Set ZIMI_MANAGE=1 to enable."}, ) # Public pre-auth endpoints (no Authorization header available) if parsed.path == "/manage/has-password": return handler._json( 200, { "has_password": bool(_get_manage_password_hash()), "env_controlled": bool(os.environ.get("ZIMI_MANAGE_PASSWORD", "")), **access_answer(handler), }, ) if parsed.path == "/manage/has-token": return handler._json(200, {"has_token": bool(_get_api_token())}) if parsed.path == "/manage/thumb": # Thumbnails are public catalog data; tags can't send Authorization headers url = param("url", "") if not url or not url.startswith("https://library.kiwix.org/"): return handler._json(400, {"error": "invalid thumbnail URL"}) data, ct = _srv._fetch_thumb(url) if data is None: # Already-cached thumbnails still serve offline (no packets); only # a miss is a dead end there, and it is a 404, not an upstream # failure the client should retry. from zimi import p2p as _p2p if _p2p.is_offline(): return handler._json(404, {"error": "thumbnail not available offline"}) return handler._json(502, {"error": "failed to fetch thumbnail"}) handler.send_response(200) handler.send_header("Content-Type", ct) handler.send_header("Content-Length", str(len(data))) handler.send_header( "Cache-Control", "public, max-age=604800" ) # 7 days browser cache handler.end_headers() handler.wfile.write(data) return # The create surfaces gate themselves: a creator account (can_create) is # not an admin, so these two run BEFORE the admin challenge below. # Everything else on /manage/* stays admin-only exactly as before. if parsed.path == "/manage/create/status": denial = _creator_denial(handler) if denial: return handler._json(*denial) # Polled ~2s while a job runs. Everything here is in-memory except the # optional one-shot sidecar probe, so the poll stays cheap on a Pi. return handler._json( 200, _create_status( _create_int(param("since"), 0, 2**31) or 0, probe=param("probe") == "1", events_cursor=_create_int(param("events_since"), 0, 2**31) or 0, # Asked for when the page opens, not every poll: it reads a # file, and what happened yesterday does not change per second. history=param("history") == "1", ), ) if parsed.path == "/manage/create/log": denial = _creator_denial(handler) if denial: return handler._json(*denial) lines = _create_log(param("job") or "") if lines is None: return handler._json(404, {"error": "not found"}) return handler._json(200, {"lines": lines}) if parsed.path == "/manage/create/shot": # The picture of the live page, while the job is still running. Same # gate as the status poll it is announced on, and fetched once per job # rather than ridden down the poll — it is a JPEG, not a status field. denial = _creator_denial(handler) if denial: return handler._json(*denial) job = _create_job # The id is in the URL so each job's picture is its own resource and # can be cached hard. Serving the current job's picture for a stale id # would be the last run's page under this run's name. wanted = param("job") if job is None or (wanted and wanted != job.id): return handler._json(404, {"error": "no picture for this job"}) shot = job.shot if not shot: return handler._json(404, {"error": "no picture for this job"}) handler.send_response(200) handler.send_header("Content-Type", "image/jpeg") handler.send_header("Content-Length", str(len(shot))) # A job's picture never changes once taken, and the job id is in the # URL, so it can be cached hard. A new job is a new URL. handler.send_header("Cache-Control", "private, max-age=3600") handler.end_headers() handler.wfile.write(shot) return if parsed.path == "/manage/create/browse": # The old folder picker's feed, which took a server path. It stays # gone (410); its successor is /manage/create/tree, which takes only # paths relative to the create root. denial = _creator_denial(handler) if denial: return handler._json(*denial) return handler._json( 410, { "error": "this folder picker is gone; the Create page's Folder mode uses /manage/create/tree" }, ) if parsed.path == "/manage/create/tree": # One level of the create root, for the Folder picker. Gated exactly # as import is: an admin or creator session first, then the primary # admin alone, because it lists the server's disk. denial = _creator_denial(handler) if denial: return handler._json(*denial) if not _primary_admin_authorized(handler): return handler._json(403, _DISK_PRIMARY_ONLY) payload, status = _create_tree( param("path", ""), _create_int(param("offset"), 0, 2**31) or 0 ) return handler._json(status, payload) challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) if parsed.path == "/manage/status": zim_count = len(_srv.get_zim_files()) total_gb = sum(z.get("size_gb", 0) for z in (_srv._zim_list_cache or [])) linked_zims = len(set(_srv._domain_zim_map.values())) return handler._json( 200, { "zim_count": zim_count, "total_size_gb": round( total_gb, 6 ), # as each ZIM's size_gb: 0.1 GB read 0 B for small libraries "from_folders": libfolders.shares(), "manage_enabled": True, "linked_zims": linked_zims, "domain_count": len(_srv._domain_zim_map), "auto_update": _auto_update_view(), }, ) elif parsed.path == "/manage/auto-update": # The GET half of the same path the POST below writes. Everything the # auto-update section renders, including the coverage list, which is # the one part that walks the library and so is not on the status poll. payload = _auto_update_view() payload["coverage"] = _auto_update_coverage() return handler._json(200, payload) elif parsed.path == "/manage/creator": return handler._json(200, _creator_payload()) elif parsed.path == "/manage/creator/inventory": return handler._json(200, _creator_inventory_payload()) elif parsed.path == "/manage/stats": metrics = _srv._get_metrics() disk = _srv._get_disk_usage() # The same view /manage/status serves. It used to be a third hand-built # dict here that omitted `locked` and a second one there that omitted # `last_check`, so which facts a caller got depended on which endpoint # it happened to poll. auto_update = _auto_update_view() # The per-index walk opens every title index on disk — far too costly # for the callers that only want disk paths or partial-download info. # ?detail=1 is the opt-in for the one view that renders the index list. title_index = ( _srv._get_title_index_stats() if param("detail") == "1" else _srv._get_title_index_status_brief() ) with _srv._xzim_refs_lock: xzim_refs = sorted( [ {"from": k[0], "to": k[1], "count": v} for k, v in _srv._xzim_refs.items() ], key=lambda x: x["count"], reverse=True, ) linked_zims = len(set(_srv._domain_zim_map.values())) zim_count = len(_srv.get_zim_files()) return handler._json( 200, { "metrics": metrics, "disk": disk, "auto_update": auto_update, "title_index": title_index, "cross_zim_refs": xzim_refs, "linked_zims": linked_zims, "zim_count": zim_count, "domain_count": len(_srv._domain_zim_map), }, ) elif parsed.path == "/manage/usage": return handler._json(200, _srv._get_usage_stats()) elif parsed.path == "/manage/download-schedule": from zimi import library as _lib return handler._json(200, _lib._download_schedule_status()) elif parsed.path == "/manage/backup": # scope=device (default, everyone) or scope=server (admin-only: the full # server state incl. users.json with hashes). The manage gate above is # already admin-only, but the explicit check keeps the server-scope # contract self-evident and independently testable. scope = param("scope", "device") if scope == "server" and admin_kind(handler) is None: return handler._json(403, {"error": "full-server backup requires an admin"}) return handler._json(200, _build_backup_bundle(scope=scope)) elif parsed.path == "/manage/users": # Named user accounts (multi-user v1) — admin-only (gated above). Returns # the roster (no password hashes), the installed ZIM names (legacy field), # the richer picker options (title + language + count) the redesigned # allowlist picker needs, and the public-access policy so the whole Users # panel renders from a single fetch. from zimi import users as _users return handler._json(200, _users_payload(handler)) elif parsed.path == "/manage/public-access": # Anonymous-access policy on its own, with the picker options — a # lightweight refetch target after the admin changes it. from zimi import users as _users return handler._json( 200, { "public_access": _users.public_access_status(), "zim_options": _zim_picker_options(), }, ) elif parsed.path == "/manage/catalog": query = param("q", "") lang = param("lang", "") try: count = min(int(param("count", "20")), 500) except (ValueError, TypeError): count = 20 try: start = max(int(param("start", "0")), 0) except (ValueError, TypeError): start = 0 total, items, err = _srv._fetch_kiwix_catalog(query, lang, count, start) offline_source = "" offline_as_of = "" if err: # A failed fetch used to be a 502, and the catalog view answered it # by replacing itself with one error line. That hid the categories, # the whole library, and the ZIMs a LAN peer was offering right # then, none of which depend on Kiwix answering. # # Fall back instead: the cached catalog if this machine has ever # been online, otherwise the snapshot that ships in the package. # Only a machine with neither still errors. from zimi import library as _offline fallback, offline_source, offline_as_of = _offline.offline_catalog() if not fallback: return handler._json( 502, {"error": f"Kiwix catalog fetch failed: {err}"} ) if query: needle = query.lower() fallback = [ it for it in fallback if needle in str(it.get("title", "")).lower() or needle in str(it.get("name", "")).lower() ] total = len(fallback) items = fallback[start : start + count] # Optional client-side language filter — `ui_languages=en,fr` returns # only items whose normalized language code is in the set. ui_langs_raw = param("ui_languages", "") if ui_langs_raw: wanted = {x.strip().lower() for x in ui_langs_raw.split(",") if x.strip()} if wanted: items = [ it for it in items if str(it.get("language", "")).lower() in wanted ] total = len(items) # Optional bundle/subset hierarchy detection. Off by default because # the UI only needs it on the catalog drill-in page. if param("include_hierarchy", "") == "1": from zimi.catalog_hierarchy import bundle_relationships rels = bundle_relationships(items) for it in items: it["hierarchy"] = rels.get(it.get("name"), {}) # Once the browse pages in cache cover the whole catalog, write it # down as one file. No extra requests: the pages are already here. # This is what lets a machine that was online once browse forever. if not err and total: try: from zimi import library as _persist _persist.maybe_persist_full_catalog(total) except Exception: pass # caching is best effort; never fail a browse over it # Where each map is, so a map page can offer the maps of the spot on # screen. A no-op for everything that is not a catalog map. from zimi import mapregions mapregions.annotate(items) resp = {"total": total, "items": items} # Offline: last-good catalog served from disk — tell the client so # it can show a quiet "catalog from " note. from zimi import library as _lib if _lib._catalog_stale_ts: resp["stale"] = True resp["fetched_at"] = _lib._catalog_stale_ts if offline_source: # Which of the three states this answer came from, so the UI can # date it honestly rather than presenting a six-month-old library # as current. resp["source"] = offline_source resp["as_of"] = offline_as_of resp["stale"] = True return handler._json(200, resp) elif parsed.path == "/manage/check-updates": updates = _srv._check_updates() return handler._json(200, {"updates": updates, "count": len(updates)}) elif parsed.path == "/manage/updates": # Same shape as /manage/check-updates — stable name without "check-" # so callers reading last-known state aren't named for the side # effect. Triggers a catalog fetch; fast when cached. updates = _srv._check_updates() return handler._json(200, {"updates": updates, "count": len(updates)}) elif parsed.path == "/manage/app-update": # The Zimi APP itself — not /manage/auto-update (ZIM-content refresh) # and not /manage/updates (per-ZIM update list). Passive read: serves # the cached answer, refreshing at most once a day. Never runs at # boot — the only trigger is an admin opening the Manage server pane. return handler._json(200, _app_update_payload()) elif parsed.path == "/manage/downloads": return handler._json(200, {"downloads": _srv._get_downloads()}) elif parsed.path == "/manage/fieldmanual" and _srv.fieldguide_enabled(): # The Field Guide's field-manual ZIM: how far its build is. from zimi import fieldguide return handler._json(200, _fieldmanual_status(fieldguide)) elif parsed.path == "/manage/activity": # Aggregated background-activity snapshot for the topbar status row. # Cheap to call — reads in-memory state only, no heavy I/O. Designed # for 5s polling. Returns small flat dict; client renders one line. idx = _srv._get_title_index_status_brief() downloads = _srv._get_downloads() # _get_downloads() shape: queued items have queued=True, in-flight # items have queued=False + done=False + paused=False. There is no # `status` key on a real download object. Active = actively # transferring; queued is a separate bucket. active = [ d for d in downloads if not d.get("done") and not d.get("paused") and not d.get("queued") ] active_dl = len(active) queued_dl = sum(1 for d in downloads if d.get("queued")) # Name of the first in-flight download so the topbar badge tooltip can # read "1 downloading — " instead of a bare count. Base filename # (sans .zim) — recognizable without a catalog lookup on a 5s poll. first_name = "" if active: fn = active[0].get("filename", "") or "" first_name = fn[:-4] if fn.endswith(".zim") else fn seeding_count = 0 try: from zimi import p2p as _p2p if _p2p.is_torrent_enabled(): # peek only — a 5s poll must never spawn (or retry) the sidecar backend = _p2p.peek_backend() if backend: # A client engine answers from its last list, refreshed in # the background; the built-in one from memory. rows = getattr( backend, "list_managed_cached", backend.list_managed )() seeding_count = sum( 1 for raw in rows if raw.get("seeder") == "true" and raw.get("status") == "active" ) except Exception: pass # Other long-running jobs a user starts and then navigates away from: # bookmark→ZIM export and the library health check. Both keep their # phase/done/total in module memory, so this stays poll-cheap. Only # the brief shape is forwarded (health's full report can be large). def _op_brief(mod_state): return { "phase": mod_state.get("phase"), "done": mod_state.get("done", 0), "total": mod_state.get("total", 0), } export_op = {"phase": None, "done": 0, "total": 0} try: from zimi import zimwriter as _zw export_op = _op_brief(_zw.get_export_state()) except Exception: pass health_op = {"phase": None, "done": 0, "total": 0} try: from zimi import health as _health health_op = _op_brief(_health.get_state()) except Exception: pass return handler._json( 200, { "indexing": { "state": idx.get("state", "idle"), "ready": idx.get("ready", 0), "total": idx.get("total", 0), "current": idx.get("building_now"), # Names only: a ZIM whose index failed to build (it keeps # its old one, or has none). "failed": sorted({name for name, _ in idx.get("errors", [])}), }, "downloads": { "active": active_dl, "queued": queued_dl, "name": first_name, }, "seeding": {"torrents": seeding_count}, "export": export_op, "health": health_op, # The Q-ID scan, did-you-mean and ZimiTube details, while # they run: Manage's cache section says what is still building. "background": _search_background_work(), "failed": _search_background_failures(), }, ) elif parsed.path == "/manage/peers": try: from zimi import p2p_discovery as _disc # The share toggle governs BOTH directions: with it off, we # neither serve /dl nor surface peers to pull from — the user # asked for "internet sources only". if not _disc.is_share_enabled(): return handler._json( 200, { "enabled": False, "self": _disc._self_service_name or _disc._peer_instance_name(), "peers": [], }, ) return handler._json( 200, { "enabled": _disc.is_enabled(), "self": _disc._self_service_name or _disc._peer_instance_name(), "peers": _disc.get_peers(), }, ) except Exception: return handler._json(200, {"enabled": False, "self": "", "peers": []}) elif parsed.path == "/manage/mirror": try: from zimi import p2p as _p2p return handler._json(200, _p2p.get_mirror_status()) except Exception: return handler._json( 200, {"enabled": False, "ratio_cap": 0.0, "upload_kb": 0} ) elif parsed.path == "/manage/health": # Library health report — poll status of the on-demand check. from zimi import health as _health return handler._json(200, _health.get_state()) elif parsed.path == "/manage/export-bookmarks": # Save-to-ZIM export — poll status of the on-demand export. from zimi import zimwriter as _zw return handler._json(200, _zw.get_export_state()) elif parsed.path == "/manage/peers/list": try: from zimi import p2p_discovery as _disc if not _disc.is_share_enabled(): return handler._json(403, {"error": "LAN sharing is turned off"}) peer = param("peer", "") if not peer: return handler._json(400, {"error": "missing 'peer' param"}) data = _disc.fetch_peer_list(peer) if data is None: return handler._json(404, {"error": "peer not reachable or unknown"}) return handler._json(200, {"peer": peer, "list": data}) except Exception: return handler._json(503, {"error": "peer fetch failed"}) elif parsed.path == "/manage/history": return handler._json(200, {"history": _srv._load_history()}) elif parsed.path == "/manage/activity-log": # The unified journal behind the Activity view. Named -log because # /manage/activity is the live "what is happening right now" poll that # feeds the topbar badge; this is "what has happened". return handler._json(200, activity_payload(param("type"), param("actor"))) elif parsed.path == "/manage/cache-info": return handler._json(200, _cache_info_payload()) elif parsed.path == "/manage/hot": # Pro: list of hot ZIMs + which env source controls them. env_locked = "ZIMI_HOT_ZIMS" in os.environ return handler._json( 200, { "hot_zims": _srv.get_hot_zims(), "env_locked": env_locked, }, ) elif parsed.path == "/manage/seeding": # Surface what we're seeding right now: per-ZIM ratio, peers, speeds. # Empty list when BT is off or no torrents are loaded. from zimi import p2p if not p2p.is_torrent_enabled(): return handler._json( 200, { "enabled": False, "ratio_cap": p2p.get_seed_ratio_cap(), "torrents": [], "totals": {"uploaded": 0, "downloaded": 0, "ratio": 0.0}, }, ) # peek only — a list view must not spawn (or retry) the sidecar backend = p2p.peek_backend() if not backend: return handler._json( 200, { "enabled": True, "ratio_cap": p2p.get_seed_ratio_cap(), "torrents": [], "totals": {"uploaded": 0, "downloaded": 0, "ratio": 0.0}, }, ) torrents = [] total_up = 0 total_down = 0 # Mirror seeds carry no ratio cap; personal seeds stop at cap x size. # The cap is a single global (per-torrent goal = cap x that file's # size), computed client-side from ratio_cap + the file size we send. mirror_on = p2p.is_mirror_enabled() ratio_cap = p2p.get_seed_ratio_cap() from zimi import library as _lib ledger = _lib.seed_ledger_snapshot() # Drop finished/errored results (e.g. broken-ZIM torrents that can't # resolve) so they don't linger in the seeding panel. Best-effort. purge = getattr(backend, "purge_stopped", None) if callable(purge): try: purge() except Exception: pass try: for raw in backend.list_managed(): files = raw.get("files", []) fpath = "" if files and isinstance(files, list) and files[0].get("path"): fpath = files[0]["path"] fname = os.path.basename(fpath) # Skip anything that isn't a ZIM (stray .torrent noise). if not fname.endswith(".zim"): continue completed = int(raw.get("completedLength", 0)) uploaded = int(raw.get("uploadLength", 0)) ratio = uploaded / max(completed, 1) state = raw.get("status", "unknown") # An in-flight BT download is the Downloads tab's job, not a # seed — list_managed() returns downloading torrents too, so # without this a BT download double-surfaces (one download # card AND one "seed" card for the same .zim under "All"). # Only skip when we KNOW it's still downloading (shared # predicate with the stop_all action). total = int(raw.get("totalLength", 0)) if _bt_still_downloading(raw): continue # Honesty: a seed whose file vanished (or that errored) is # snagged, not seeding — surface it, don't hide it. snag = "" if state == "error": snag = raw.get("errorMessage", "") or "error" elif fpath and not os.path.exists(fpath): snag = "file missing" # Lifetime upload from the ledger (survives restarts) — at # least this session's count. file_size prefers the torrent's # total; completedLength is the seeding-file fallback. led = ledger.get(fname, {}) cumulative = max(int(led.get("uploaded", 0) or 0), uploaded) file_size = total or completed is_mirror = mirror_on or led.get("origin") == "mirror" # Personal seeds have a byte goal (cap x size); mirror = none. cap_bytes = 0 if is_mirror else int(ratio_cap * file_size) torrents.append( { "id": raw.get("gid", ""), "filename": fname, "state": state, "snag": snag, "completed_bytes": completed, "file_size_bytes": file_size, "uploaded_bytes": uploaded, "cumulative_uploaded_bytes": cumulative, # Ledger intent time = when Zimi first decided to seed # this file (download completion / mirror sync). 0 when # the ledger has no entry — the client hides the age. "added": int(led.get("added") or 0), "cap_bytes": cap_bytes, "mirror": is_mirror, "ratio": round(ratio, 3), "peers": int(raw.get("connections", 0)), "down_speed": int(raw.get("downloadSpeed", 0)), "up_speed": int(raw.get("uploadSpeed", 0)), "info_hash": raw.get("infoHash", ""), } ) if not snag: total_up += uploaded total_down += completed except Exception as e: log.warning("seeding list failed: %s", e) return handler._json( 200, { "enabled": p2p.is_seeding_enabled(), "ratio_cap": ratio_cap, "mirror": mirror_on, "disk_pressure": p2p.should_pause_for_disk_pressure(_srv.ZIM_DIR), "torrents": torrents, "totals": { "uploaded": total_up, "downloaded": total_down, "ratio": round(total_up / max(total_down, 1), 3), }, }, ) elif parsed.path == "/manage/apps": shown = _srv.apps_shown() return handler._json( 200, { "enabled": bool(shown), "shown": [n for n in _srv.APP_NAMES if n in shown], "env_locked": _srv._apps_env() is not None, }, ) elif parsed.path == "/manage/own-zims": # Zimi's own ZIMs (Almanac, Games) for the Catalog's Zimi group: from # the package, so an offline or air-gapped install lists them too. from zimi import ownzims return handler._json(200, {"zims": ownzims.catalog()}) elif parsed.path == "/manage/outbound": # "What Zimi fetches from the internet": every destination, what sets # it off and whether it is on now. Read-only; each row names the # setting that changes it. return handler._json(200, outbound.inventory()) elif parsed.path == "/manage/satellites": # "Satellite data from the internet" for Server settings. from zimi import satellites as _sats return handler._json(200, _sats.setting()) elif parsed.path == "/manage/voices": # "Voices for Dictionary": the setting and every pinned Piper voice. from zimi import voices as _voices return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/books/whole": # The ZIMs put on the Bookshelf as one book, or taken off it, by hand. from zimi import books as _books return handler._json(200, {"zims": _books._whole_overrides()}) elif parsed.path == "/manage/catalog-streetzim": # StreetZim's regions, from the Internet Archive, for the toggle in # the Maps category. Cached and served stale while a refresh runs. from zimi import streetzim from zimi import mapregions items, source, as_of, refreshing = streetzim.get() return handler._json( 200, { "items": mapregions.annotate(list(items)), "source": source, "as_of": as_of, "refreshing": refreshing, }, ) elif parsed.path == "/manage/library-folders": if not _primary_admin_authorized(handler): return handler._json(403, _FOLDERS_PRIMARY_ONLY) return handler._json(200, _library_folders_view()) elif parsed.path == "/manage/env": # What the environment is overriding, so an admin can SEE it rather # than deducing it from a greyed-out control (#69). Read-only by # design: the environment belongs to whoever starts the process. from zimi import envinfo return handler._json( 200, {"vars": envinfo.effective(published=_srv.CONFIG_PUBLISHED)} ) elif parsed.path == "/manage/bt-status": # Surface the BT engine state so the user can self-diagnose: # enabled? libtorrent importable on this install? session up? from zimi import p2p enabled = p2p.is_torrent_enabled() engine_importable = p2p._lt() is not None or p2p.engine_name() != "libtorrent" # Live state — peek only. A status view must never start the # engine (with BT on by default that would mean every settings # visit spins up a session). backend = p2p.peek_backend() if enabled else None engine_alive = backend is not None and backend.is_alive() if not enabled: status = "off" elif backend is not None: status = "ready" elif not engine_importable: status = "unavailable" else: # Importable, session just not started yet — it starts at # boot or on first download, so report ready-to-torrent. status = "ready" hint_key, hint_vars = None, {} # Off by the environment: name the variable that did it, as it is # set (ZIMI_TORRENT=0, ZIMI_OFFLINE=1). Off by the switch: the switch # says so, nothing to add. setting = p2p.torrent_env_setting() if not enabled else "" if setting: hint_key = "bt_why_off" hint_vars = {"v": setting} elif status == "unavailable": import platform as _platform import sys as _sys # Give the exact next step, and never one that cannot work. # libtorrent publishes no sdist, so "pip install zimi[bt]" is only # good advice where a wheel exists: CPython 3.9–3.13, on x86_64 or # 64-bit ARM. Two ways to miss it, and they are not the same news. # 3.14 is temporary and the wheel will come; 32-bit ARM — which is # what plain Raspberry Pi OS still installs — has never had one and # is not going to. # A KEY and its variables, never a sentence. Everything else this # server sends a browser is a number or a name, and the client # writes the prose in the reader's language — a sentence composed # here is English in all ten of them. machine = (_platform.machine() or "").lower() if machine and machine not in _BT_WHEEL_ARCHES: hint_key = "bt_why_no_arch" hint_vars = {"arch": _platform.machine()} elif _sys.version_info >= (3, 14): hint_key = "bt_why_no_wheel" hint_vars = { "version": f"{_sys.version_info.major}.{_sys.version_info.minor}" } else: hint_key = "bt_why_install" hint_vars = {} from zimi import p2p_nat return handler._json( 200, { "status": status, "enabled": enabled, "backend": p2p.engine_name(), "client": _btc_view(), "bt_port": p2p.get_bt_port(), "staging_dir": p2p.get_staging_dir(_srv.ZIMI_DATA_DIR), "engine_importable": engine_importable, "hint_key": hint_key, "hint_vars": hint_vars, "upnp_enabled": p2p.is_upnp_enabled(), "upnp_env_locked": p2p.is_upnp_env_locked(), # True only when the session is actually up — "ready" alone # is optimistic (importable counts). The UI reads this key. "sidecar_running": engine_alive, "bt_port_env_locked": p2p.is_bt_port_env_locked(), # Cached: reachability is asked only by /manage/nat-recheck "nat": p2p_nat.last_status() or None, }, ) else: return handler._json(404, {"error": "not found"}) def _zim_picker_options(): """``[{name, title, language, article_count}]`` for the allowlist pickers, sorted by title. Admin view = all installed ZIMs. Titles/languages come from the startup metadata cache; a ZIM not yet in that cache still appears (by name) so it is always selectable.""" opts = [] seen = set() for z in _srv._zim_list_cache or []: name = z.get("name") if not name: continue seen.add(name) opts.append( { "name": name, "title": z.get("title") or name, "language": z.get("language", ""), "article_count": z.get("article_count"), } ) for name in sorted(_srv.get_zim_files().keys()): if name not in seen: opts.append( {"name": name, "title": name, "language": "", "article_count": None} ) opts.sort(key=lambda o: (o["title"] or "").casefold()) return opts def _handle_public_access_post(handler, data): """Admin-only: set the anonymous-access policy. ``mode`` ∈ {open, limited, private}; ``allowlist`` applies only to ``limited``. Echoes the fresh status so the UI re-renders in one round trip. Auth already passed (gated in ``handle_manage_post``).""" from zimi import users as _users mode = data.get("mode", "") ok, err = _users.set_public_access(mode, data.get("allowlist")) if not ok: return handler._json(400, {"error": err or "operation failed"}) return handler._json( 200, {"status": "ok", "public_access": _users.public_access_status()} ) def _handle_users_post(handler, data): """Admin-only user CRUD (multi-user v1). action ∈ {create, delete, set-password, set-allowlist, set-role, set-can-create, set-display}. Errors are returned generically; on success the fresh roster (no hashes) is echoed so the UI re-renders in one round trip. Reaching here means the admin-auth challenge already passed. Hierarchy (see ``users`` module docstring): only the PRIMARY admin may manage admin-role accounts. A SECONDARY admin can CRUD regular users but cannot create/modify/delete any admin, and NO admin can mutate the primary account (it lives in the password file, not users.json).""" from zimi import users as _users action = data.get("action", "") name = data.get("name", "") if not isinstance(action, str) or not isinstance(name, str): return handler._json(400, {"error": "invalid request"}) kind = admin_kind(handler) # 'primary' | 'secondary' (auth already passed) role = data.get("role") # While anyone can manage Zimi, no one may make a way in that outlives it. if open_from_settings() and action in ("create", "set-password", "set-role"): return handler._json(403, {"error": "open_locked"}) # The primary admin is a synthetic row — no CRUD action may target it. primary_name = _get_manage_user() or "admin" if name and name.strip().casefold() == primary_name.strip().casefold(): return handler._json(403, {"error": "cannot modify the primary admin"}) # Only the primary admin manages admin-role accounts. A secondary admin # cannot create an admin, nor touch an existing admin-role user. if kind != "primary": targets_admin_role = role == "admin" touches_existing_admin = bool(name) and _users.is_admin_user(name) if targets_admin_role or touches_existing_admin: return handler._json( 403, {"error": "only the primary admin manages admins"} ) if action == "create": ok, err = _users.create_user( name, data.get("password", ""), data.get("allowlist"), role=role ) elif action == "delete": ok, err = _users.delete_user(name) elif action == "set-password": ok, err = _users.set_password(name, data.get("password", "")) elif action == "set-allowlist": ok, err = _users.set_allowlist(name, data.get("allowlist")) elif action == "set-role": ok, err = _users.set_role(name, role, data.get("allowlist")) elif action == "set-display": # What a person goes by in games and on the boards (users.set_display_name's rules). if not _users.get_user(name): return handler._json(400, {"error": "user not found"}) ok, err, _shown = _users.set_display_name(name, data.get("display")) if not ok and err == "name taken": return handler._json(409, {"error": err}) elif action == "set-can-create": # Grant/revoke the per-user create permission (see users.set_can_create). # The hierarchy gate above already bars a secondary admin from touching # admin accounts; admins themselves are refused there (implicitly true). ok, err = _users.set_can_create(name, bool(data.get("can_create"))) else: return handler._json(400, {"error": "unknown action"}) if not ok: return handler._json(400, {"error": err or "operation failed"}) # The whole panel, as the GET gives it: the client paints from one # object, and a reply with only the users left the public-access card # reading "Open" and the allowlist picker "No ZIMs installed" after every # change (Eric, 2026-09-21: "change my claude user to limited then my # public access changes to open!? That makes zero sense"). return handler._json(200, dict(_users_payload(handler), status="ok")) def _users_payload(handler): """The Users panel in one object: the accounts, the ZIMs an allowlist can name, the anonymous-access policy, the primary admin and which kind of admin is looking. Every reply that changes any of it returns all of it.""" from zimi import users as _users return { "users": _users.list_users(), "zims": sorted(_srv.get_zim_files().keys()), # Rich per-ZIM options for the allowlist picker (used by both the # per-user Limited picker and the public-access Limited picker). "zim_options": _zim_picker_options(), # Anonymous-access policy (Open / Limited / Sign-in required). "public_access": _users.public_access_status(), # The PRIMARY admin (password-file account) is not stored in # users.json — surface it as a synthetic, non-deletable row so # the UI can show "the admin" alongside the named users. "primary_admin": { "name": _get_manage_user() or "admin", "role": "admin", "primary": True, }, # Which kind of admin is viewing — the client hides admin-only # controls (creating/managing other admins) for secondaries. "self_kind": admin_kind(handler), } # ============================================================================ # Manage POST Routes # ============================================================================ # One-time download tickets: {token: (filename, expiry)}. Minted by an # authorized admin, spent by the very next /dl/ navigation, dead in two # minutes either way. In-memory on purpose — a restart invalidating tickets # is correct behavior for a credential. DL_TICKET_TTL_SEC = 120 _dl_tickets: dict = {} _dl_ticket_lock = threading.Lock() def spend_dl_ticket(token, fname): """True exactly once per ticket, and only for the file it was minted for. Wrong file, reuse, expiry — all read as no ticket at all.""" if not token: return False now = time.time() with _dl_ticket_lock: entry = _dl_tickets.pop(token, None) return bool(entry and entry[1] >= now and entry[0] == fname) def _password_set_response(handler, data, body): """After a new password is saved: the setup key's life ends with the bootstrap it existed for, a password ends "Anyone on my network" and the first-run gate, the sessions the old one opened end, and this browser gets a fresh one (it keeps a session, never a password).""" _clear_setup_key() if _read_app_update_prefs().get("lan_admin"): _write_app_update_prefs(lan_admin=False) _end_setup_gate() from zimi import users as _users_pw _users_pw.drop_admin_sessions() token = _users_pw.create_admin_session() return handler._json_cookie( 200, dict(body, token=token), handler._session_cookie(token, bool(data.get("remember"))), ) def _set_manage_username(name): """Rename the password account, keeping its hash. False when the file cannot be written.""" stored = _get_manage_password_hash() if not stored or os.environ.get("ZIMI_MANAGE_PASSWORD", ""): return True # nothing in the file to rename content = stored + ("\n" + name if name else "") return _atomic_write_text(_password_file(), content) def access_answer(handler): """The setup page's state, for /manage/has-password: what is decided, what the environment owns, and where this browser stands.""" return { "access": access_mode(), "access_env": _lan_admin_env() is not None, # The password off: set in the environment (the switch is locked and # the rows are not shown), and whether a password is kept for when it # is turned off again. "open_env": manage_open_env() is not None, "kept_password": bool(_get_manage_password_hash()), "setup": setup_pending(), # Whether this device answers without the setup key: the machine # running Zimi, or the home network while a fresh install's page is up # (_first_run_lan_client). Elsewhere inside the network a device is # offered the key field; outside it, only "being set up". "keyless": ( _host_is_owner() and bool(getattr(handler, "_is_loopback_client", lambda: False)()) ) or _first_run_lan_client(handler), "inside": handler._is_private_client(), # The account name, for the admin editing it: never to anyone else, or # it would be half the login handed out. "username": ( _get_manage_user() if _get_manage_password_hash() and not manage_open() # everyone passes the check while open and _check_manage_auth(handler) is None else "" ), } def _handle_access(handler, data): """POST /manage/access: the one switch, on the setup page and in Settings. {require_password, password, username, current_password, open_confirm}. Before a password exists this is the bootstrap (GHSA-5mw2-53vv-9pw6): only the machine running Zimi or the holder of the setup key it logged gets through, so a neighbour cannot answer it for the owner. After, it is admin-only. Where the request came from is not asked. Every rule that asked (a LAN behind a reverse proxy, a proxy that could not be told from the internet) ended with an owner who could not turn their own password off at home. On, whoever has the password manages Zimi; off, anyone who can reach it does (_open_to_anyone). Changing an existing password stays with set-password, which asks for the current one.""" env_open = manage_open_env() if env_open: # the environment opened it; only the environment closes it return handler._json( 403, {"error": "env_controlled", "var": "ZIMI_MANAGE_OPEN"} ) challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) if data.get("require_password") is not True: if env_open is False: # ZIMI_MANAGE_OPEN=0 forbids only this answer return handler._json( 403, {"error": "env_controlled", "var": "ZIMI_MANAGE_OPEN"} ) return _open_to_anyone(handler, data) # No username sent leaves the stored one alone (only a form showing the # field can rename the account). username = ( str(data.get("username") or "").strip()[:64] if "username" in data else None ) password = str(data.get("password") or "").strip() stored = _get_manage_password_hash() if os.environ.get("ZIMI_MANAGE_PASSWORD", "") and password: return handler._json( 403, {"error": "env_controlled", "var": "ZIMI_MANAGE_PASSWORD"} ) if not stored and not password: return handler._json(400, {"error": "needs_password"}) if stored and password: # Off with a kept password, on returns to that password, never to a # new one a visitor could set to lock the owner out with. if open_from_settings(): return handler._json(403, {"error": "open_locked"}) return handler._json(400, {"error": "change it with the current password"}) if ( stored and open_from_settings() and username is not None and username != _file_username() ): # Nor a new name for it: the kept password would no longer log in. return handler._json(403, {"error": "open_locked"}) if os.environ.get("ZIMI_MANAGE_USER", "").strip(): username = None # the environment names the account if password: if not _set_manage_password(password, username=username or ""): return handler._json( 500, {"error": "Could not save the password (storage is not writable)"} ) elif username is not None and username != _file_username(): if not _set_manage_username(username): return handler._json(500, {"error": "Could not save the username"}) _write_app_update_prefs(lan_admin=False, manage_open=False) _clear_setup_key() _end_setup_gate() log.info("Access: password") if password: return _password_set_response(handler, data, {"access": access_mode()}) return handler._json(200, {"access": access_mode()}) def _open_to_anyone(handler, data): """The password switched off in Settings: nobody is asked for anything, from anywhere. The answer to "I do not want a password" for an instance that is reachable from outside, which used to need ZIMI_MANAGE_OPEN in a config. It costs a deliberate act: the box that names the cost, and the current password when there is one, so a borrowed session cannot do it. Nothing is purged (password, API token, accounts and sessions stay), so turning it off goes back to exactly what was there. On a first run it is one of the two answers, made only by those the setup page's two doors let through (GHSA-5mw2-53vv-9pw6): never a default, always this named press.""" if data.get("open_confirm") is not True: return handler._json(400, {"error": "open_unconfirmed"}) if _env_flag("ZIMI_MANAGE_EXTERNAL") is False: return handler._json( 403, {"error": "env_controlled", "var": "ZIMI_MANAGE_EXTERNAL"} ) if os.environ.get("ZIMI_MANAGE_PASSWORD", ""): return handler._json( 403, {"error": "env_controlled", "var": "ZIMI_MANAGE_PASSWORD"} ) if _lan_admin_env() is False: return handler._json(403, {"error": "env_controlled", "var": "ZIMI_LAN_ADMIN"}) stored = _get_manage_password_hash() if not manage_open() and stored: current = str(data.get("current_password") or "") if not current or not _verify_current(current, stored): return handler._json(403, {"error": "wrong_password"}) _write_app_update_prefs(manage_open=True) _clear_setup_key() _end_setup_gate() log.warning( "Access: password off. Nobody is asked for a password; anyone who " "can reach this server can manage it (Settings > Access > Managing " "Zimi turns it off)." ) return handler._json(200, {"access": access_mode()}) def _btc_locked(): """Why the engine cannot be changed here, or None. The environment owns it when ZIMI_BT_CLIENT or its URL is set; and while the password is off a client could only come from there, or anyone could point Zimi's requests at the operator's own network.""" from zimi import btclient var = btclient.env_var() if var: return var if open_from_settings(): return "open" return None def _btc_view(): """The engine for Settings. Never the password: only whether one is saved.""" from zimi import btclient cfg = btclient.config() or {} return { "kind": cfg.get("kind", ""), "url": cfg.get("url", ""), "user": cfg.get("user", ""), "password_set": bool(cfg.get("password")), "category": cfg.get("category", btclient.DEFAULT_CATEGORY), "paths": btclient.format_paths(cfg.get("paths", [])), "locked": _btc_locked(), } _DISK_PRIMARY_ONLY = {"error": "reading the server's disk is for the primary admin"} _FOLDERS_PRIMARY_ONLY = {**_DISK_PRIMARY_ONLY, "error_key": "folder_primary_only"} def _delete_through_nomad(handler, filename): """Delete a ZIM in Project NOMAD's folder by asking NOMAD (its database, Kiwix library and knowledge base follow), journalled like any delete.""" title = filename for z in _srv._zim_list_cache or []: if z.get("file") == filename: title = z.get("title") or z.get("name") or filename break # Let go of it first, as the own-library delete does: Windows refuses to # remove a file anyone holds open, and on POSIX an open handle would keep # the deleted ZIM's space on NOMAD's disk until something else closed it. try: _srv.release_zim_handles([_srv._zim_short_name(filename)]) except Exception as e: log.debug( "Handle release before NOMAD deletes %s: %s", loggable(filename), loggable(e), ) try: nomadapi.delete(filename) except nomadapi.NomadError as e: log.warning( "Project NOMAD would not delete %s: %s", loggable(filename), loggable(e) ) status = 404 if e.status == 404 else 502 return handler._json(status, {"error": "Project NOMAD did not delete it"}) record_activity("delete", title, actor=activity_actor(handler)) _srv._append_history( {"event": "deleted", "ts": time.time(), "filename": filename, "title": title} ) return handler._json(200, {"status": "deleted", "filename": filename}) def _library_folders_view(): """What the Storage card draws: the folders read in place, and the one offer, if there is one. Asked when the card opens, so a listing per folder is fine.""" rows = [ {**f, **libfolders.audit(f["path"]), "present": os.path.isdir(f["path"])} for f in libfolders.folders() ] return { "folders": rows, "suggestions": libfolders.suggestions(), "nomad": nomadapi.view(), } def _handle_library_folders(handler, data): """POST /manage/library-folders: {action: add|remove|dismiss, path, label?}, or {action: nomad, enabled, url?} for the Project NOMAD opt-in. Adding or removing splices just that folder's ZIMs into the live library and answers once it has; the files in the folder are never touched.""" if not _primary_admin_authorized(handler): return handler._json(403, _FOLDERS_PRIMARY_ONLY) action = data.get("action") path = str(data.get("path") or "") try: if action == "add": libfolders.reconcile(libfolders.add(path, str(data.get("label") or "")), []) elif action == "label": libfolders.rename(path, str(data.get("label") or "")) elif action == "remove": libfolders.reconcile([], libfolders.registered_in(libfolders.remove(path))) elif action == "dismiss": libfolders.dismiss(path) elif action == "nomad": if nomadapi.settings()["locked"]: return handler._json( 403, {"error": "env_locked", "error_key": "configured_via_env"} ) nomadapi.save(bool(data.get("enabled")), str(data.get("url") or "")) else: return handler._json(400, {"error": "bad_action"}) except libfolders.FolderError as e: return handler._json(400, {"error": e.key, "error_key": e.key}) except ValueError as e: # nomad_bad_url is the one ValueError raised on purpose; anything else # (a path with a NUL in it) is logged here and not sent back. key = "nomad_bad_url" if str(e) == "nomad_bad_url" else "save_failed" if key == "save_failed": log.info("library-folders %s refused: %s", loggable(action), loggable(e)) return handler._json(400, {"error": key, "error_key": key}) if action == "add": libfolders.ensure_watch() # A folder added or gone changes whether NOMAD can be the back end. nomadapi._forget_probe() return handler._json(200, _library_folders_view()) def _handle_bt_client(handler, data): """POST /manage/bt-client: {kind, url, user, password?, category, paths, test?}. ``test`` only probes and saves nothing. A missing password keeps the saved one; an empty kind (or url) goes back to the built-in engine. Saving moves to the new engine at once: downloads carry on there and seeds follow (p2p.switch_engine).""" from zimi import btclient, p2p locked = _btc_locked() if locked: return handler._json( 403, { "error": "env_controlled" if locked != "open" else "open_locked", "var": locked, }, ) if p2p.is_offline(): # BitTorrent is off, and Settings hides the card return handler._json(403, {"error": "env_controlled", "var": "ZIMI_OFFLINE"}) old = btclient.config() or {} kind = str(data.get("kind") or "").strip().lower() url = str(data.get("url") or "").strip().rstrip("/") if kind and kind not in btclient.KINDS: return handler._json(400, {"error": "bad_kind"}) if not kind: url = "" if kind and not btclient.valid_url(url): return handler._json(400, {"error": "bad_url"}) password = data.get("password") if password is None: # The saved password goes only to the client it was saved for: a new # address with a blank password must not send it somewhere else. same = old.get("kind") == kind and btclient.same_url(old.get("url", ""), url) password = old.get("password", "") if same else "" cfg = { "kind": kind, "url": url, "user": str(data.get("user") or "").strip()[:128], "password": str(password)[:256], "category": str(data.get("category") or "").strip()[:64] or btclient.DEFAULT_CATEGORY, "paths": btclient.parse_paths(data.get("paths") or ""), } if data.get("test"): if not kind: return handler._json(400, {"error": "bad_url"}) return handler._json(200, btclient.probe(cfg, library_dir=_srv.ZIM_DIR)) if kind: # A client that does not answer is not switched to: the engine in # use keeps its downloads and seeds, and the form says why. found = btclient.probe(cfg, library_dir=_srv.ZIM_DIR) if not found.get("ok"): return handler._json(409, found) saved = p2p.set_prefs( { btclient.PREF["kind"]: kind, btclient.PREF["url"]: url, btclient.PREF["user"]: cfg["user"] if kind else "", btclient.PREF["password"]: cfg["password"] if kind else "", btclient.PREF["category"]: cfg["category"], btclient.PREF["paths"]: btclient.format_paths(cfg["paths"]), } ) if not saved: return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) log.info( "BitTorrent engine: %s", f"{btclient.label(kind)} at {btclient.loggable(url)}" if kind else "built in", ) def _switch(): from zimi import library as _lib if p2p.switch_engine(data_dir=_srv.ZIMI_DATA_DIR): _lib.apply_seed_settings() threading.Thread(target=_switch, daemon=True).start() return handler._json(200, {"engine": kind or "libtorrent", "client": _btc_view()}) def handle_manage_post(handler, parsed, data): """Handle all POST /manage/* requests. Called from ZimHandler.do_POST.""" if not _srv.ZIMI_MANAGE: return handler._json(404, {"error": "Library management is disabled."}) # Password management — browser only, not accessible via API if parsed.path == "/manage/access": return _handle_access(handler, data) if parsed.path == "/manage/set-password": if open_from_settings(): return handler._json(403, {"error": "open_locked"}) # Env var controls password — UI changes would be silently overridden if os.environ.get("ZIMI_MANAGE_PASSWORD", ""): return handler._json( 403, { "error": "Password is controlled by ZIMI_MANAGE_PASSWORD environment variable" }, ) stored = _get_manage_password_hash() if stored: cur = data.get("current", "") if not cur or not _verify_current(cur, stored): return handler._json(401, {"error": "Current password is incorrect"}) else: # Initial setup: there is no current password to verify, so the # public-lock is the only thing between a public client and a # full instance takeover. Gate it exactly like the rest of # manage — private clients set the first password, public clients # get 403 public_locked (must set it from the LAN). challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) new_pw = data.get("password", "").strip() # OPTIONAL username stored alongside the hash. Absent field → None → # _set_manage_password preserves any existing username. When the env # var owns the username, the file copy is inert (env wins on read), so # we simply don't persist it. new_user = data.get("username") if new_user is not None and os.environ.get("ZIMI_MANAGE_USER", "").strip(): new_user = None if not _set_manage_password(new_pw, username=new_user): # Generic on purpose: the OSError detail is already in the server # log, and error bodies never carry internal paths or str(e). return handler._json( 500, {"error": "Could not save the password (storage is not writable)"} ) if new_pw: return _password_set_response(handler, data, {"status": "password set"}) return handler._json(200, {"status": "password cleared"}) # API token management — requires existing auth + password must be set if parsed.path == "/manage/generate-token": challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) if open_from_settings(): return handler._json(403, {"error": "open_locked"}) if not _get_manage_password_hash(): return handler._json( 400, {"error": "Set a password before generating an API token"} ) token = _generate_api_token() if not token: # Same discipline as set-password above: log has the real reason. return handler._json( 500, {"error": "Could not save the API token (storage is not writable)"} ) return handler._json(200, {"token": token}) if parsed.path == "/manage/revoke-token": challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) _revoke_api_token() return handler._json(200, {"status": "token revoked"}) if parsed.path == "/manage/dl-ticket": # A browser NAVIGATION to /dl/ carries none of Zimi's auth headers, so # right-click -> Download on a passworded instance used to land on an # HTML refusal Safari saved as name.zim.html. The authorized client # mints a one-time ticket here; the /dl/ URL spends it within 120s. challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) fname = str(data.get("file") or "").strip() if not fname or "/" in fname or "\\" in fname or ".." in fname: return handler._json(400, {"error": "that is not a ZIM filename"}) ticket = secrets.token_urlsafe(24) now = time.time() with _dl_ticket_lock: # Expired tickets leave with every mint; the dict stays tiny. for t in [t for t, (_, exp) in _dl_tickets.items() if exp < now]: _dl_tickets.pop(t, None) _dl_tickets[ticket] = (fname, now + DL_TICKET_TTL_SEC) return handler._json(200, {"ticket": ticket}) # ZIM creation — a creator account (can_create) may drive these routes # without admin credentials, so they gate themselves ahead of the generic # admin challenge below. Folder and archive import, the web modes that # read the server's disk, are held to the primary admin just below. if parsed.path in ( "/manage/create", "/manage/create/cancel", "/manage/create/finish", "/manage/create/probe", ): denial = _creator_denial(handler) if denial: return handler._json(*denial) # Import and folder read the server's disk (under the create root, by # listing), so they stay with the primary admin; a creator account # captures the web and packages its own bookmarks, nothing more. if ( parsed.path in ("/manage/create", "/manage/create/probe") and data.get("mode") in CREATE_DISK_MODES and not _primary_admin_authorized(handler) ): return handler._json(403, _DISK_PRIMARY_ONLY) if parsed.path == "/manage/create/cancel": # With an id: that job, wherever it is — the running one or one # still waiting. Without: whatever is running. payload, status = _create_cancel(data.get("id")) return handler._json(status, payload) if parsed.path == "/manage/create/finish": # Cancel's keeping twin: stop FETCHING at the next page boundary # and package everything captured so far. Same auth as cancel. payload, status = _create_finish_now() return handler._json(status, payload) if parsed.path == "/manage/create": payload, status = _create_start(data, actor=activity_actor(handler)) else: payload, status = _create_probe(data) return handler._json(status, payload) challenge = _manage_auth_challenge(handler) if challenge: return handler._json(*challenge) if parsed.path == "/manage/creator": # The write half of the Creator section: the standing capture # defaults. What each may hold is the capture-option table's to say # (crawler.CAPTURE_OPTIONS); a value it refuses is a 400 with a # plain sentence, because storing junk a later job would obey is # worse. null or "" clears one. Admin-gated by the challenge above, # like every other manage settings write, which is also why # allow_private can only be set here and never with a capture. from zimi.crawler import validate_stored_defaults from zimi.creator import CreateError if not data: return handler._json(400, {"error": "nothing to change"}) try: updates = validate_stored_defaults(data) except CreateError as e: return handler._json(400, {"error": str(e)}) _write_create_defaults(**updates) return handler._json( 200, { "block_ads_default": _create_default("block_ads", CREATE_BLOCK_ADS), "capture_variants_default": _create_default( "capture_variants", CREATE_CAPTURE_VARIANTS ), **_create_defaults_view(), }, ) if parsed.path == "/manage/users": return _handle_users_post(handler, data) if parsed.path == "/manage/public-access": return _handle_public_access_post(handler, data) if parsed.path == "/manage/download": url = data.get("url", "") size_bytes = data.get("size_bytes") if not url: return handler._json(400, {"error": "missing 'url' in request body"}) dl_id, err = _srv._start_download( url, size_bytes=size_bytes, actor=activity_actor(handler) ) if err: return handler._json(400, {"error": err}) return handler._json(200, {"status": "started", "id": dl_id}) elif parsed.path == "/manage/fieldmanual" and _srv.fieldguide_enabled(): # Build a ZIM of the Army's public-domain manuals (zimi.fieldguide.build_field_manual). from zimi import fieldguide, p2p if p2p.is_offline(): return handler._json( 409, { "error": "offline", "message": "Offline mode is on: nothing is fetched from the internet.", }, ) if fieldguide.installed_manual(): return handler._json( 409, { "error": "installed", "message": "The field manual is already in the library.", }, ) payload, status = _create_start( {"mode": "fieldmanual"}, actor=activity_actor(handler) ) return handler._json(status, payload) elif parsed.path == "/manage/download-batch": urls = data.get("urls") if not isinstance(urls, list): return handler._json(400, {"error": "missing 'urls' array in request body"}) sizes = data.get("sizes") or [] if not isinstance(sizes, list): sizes = [] ids = [] errors = [] # One resolution for the whole batch — it is one click by one person. actor = activity_actor(handler) for i, url in enumerate(urls): if not isinstance(url, str) or not url: ids.append(None) errors.append("invalid url at index %d" % i) continue sz = ( sizes[i] if i < len(sizes) and isinstance(sizes[i], (int, float)) else None ) dl_id, err = _srv._start_download(url, size_bytes=sz, actor=actor) ids.append(dl_id) errors.append(err) succeeded = sum(1 for x in ids if x is not None) return handler._json(200, {"ids": ids, "errors": errors, "started": succeeded}) elif parsed.path == "/manage/download-from-peer": # Pull a ZIM straight from a discovered LAN peer over HTTP. The server # resolves peer→host:port from discovery state, so the client only # names the peer + file — it can't point us at an arbitrary URL. peer = data.get("peer") fname = data.get("file") if not isinstance(peer, str) or not peer: return handler._json(400, {"error": "missing 'peer'"}) if not isinstance(fname, str) or not fname: return handler._json(400, {"error": "missing 'file'"}) dl_id, err = _srv._start_peer_download( peer, fname, actor=activity_actor(handler) ) if err: return handler._json(400, {"error": err}) return handler._json(200, {"status": "started", "id": dl_id}) elif parsed.path == "/manage/import": url = data.get("url", "") if not url: return handler._json(400, {"error": "missing 'url' in request body"}) dl_id, err = _srv._start_import(url, actor=activity_actor(handler)) if err: return handler._json(400, {"error": err}) return handler._json(200, {"status": "started", "id": dl_id}) elif parsed.path == "/manage/cancel": dl_id = data.get("id", "") from zimi.library import _cancel_download, _download_by_id, download_subject # Read the transfer's identity BEFORE cancelling it: a cancelled # download leaves the queue, and the journal line still has to name # what it was. cancelled = _download_by_id(dl_id) status, code = _cancel_download(dl_id) if status == "not_found": return handler._json(404, {"error": "Download not found"}) if status == "already_done": return handler._json(400, {"error": "Download already finished"}) if cancelled: record_activity( "update" if cancelled.get("is_update") else "download", download_subject(cancelled), outcome="cancelled", actor=activity_actor(handler), ) return handler._json(code, {"status": status, "id": dl_id}) elif parsed.path == "/manage/download-start-now": # Override the nightly window for one scheduled item — start it now # (or promote it to a normal queued item if every slot is busy). dl_id = data.get("id", "") from zimi.library import _start_scheduled_now status, code = _start_scheduled_now(dl_id) if status == "not_found": return handler._json(404, {"error": "Download not found"}) return handler._json(code, {"status": status, "id": dl_id}) elif parsed.path == "/manage/switch-direct": # Escape hatch for a slow BitTorrent swarm: abandon BT for this # download and pull it over HTTP instead. dl_id = data.get("id", "") from zimi.library import _switch_to_direct status, code = _switch_to_direct(dl_id) if status == "not_found": return handler._json(404, {"error": "Download not found"}) if status == "already_done": return handler._json(400, {"error": "Download already finished"}) if status == "not_bt": return handler._json(400, {"error": "Download is not using BitTorrent"}) return handler._json(code, {"status": status, "id": dl_id}) elif parsed.path == "/manage/clear-downloads": with _srv._download_lock: to_remove = [k for k, v in _srv._active_downloads.items() if v.get("done")] for k in to_remove: del _srv._active_downloads[k] return handler._json(200, {"status": "cleared", "removed": len(to_remove)}) elif parsed.path == "/manage/refresh": # Re-scan ZIM directory and rebuild cache without full restart log.info("Library refresh triggered") with _srv._zim_lock: _srv.load_cache(force=True) count = len(_srv._zim_list_cache or []) _srv._search_cache_clear() _srv._suggest_cache_clear() _srv._clean_stale_title_indexes() return handler._json(200, {"status": "refreshed", "zim_count": count}) elif parsed.path in ("/manage/pause", "/manage/resume"): dl_id = data.get("id", "") with _srv._download_lock: dl = _srv._active_downloads.get(dl_id) if not dl: return handler._json(404, {"error": "Download not found"}) if dl.get("done"): return handler._json(400, {"error": "Download already finished"}) dl["paused"] = parsed.path == "/manage/pause" return handler._json( 200, {"status": "paused" if dl["paused"] else "resumed", "id": dl_id} ) elif parsed.path == "/manage/cache-action": # Lightweight cache maintenance for the Server-settings UI. # action ∈ {clear-search, clear-suggest, rebuild-title, rebuild-qid, purge-catalog} action = data.get("action", "") if action == "purge-catalog": return handler._json(200, {"status": "cleared", "target": "catalog", "freed_bytes": _purge_catalog_copies()}) if action == "clear-search": _srv._search_cache_clear() return handler._json(200, {"status": "cleared", "target": "search"}) if action == "clear-suggest": _srv._suggest_cache_clear() return handler._json(200, {"status": "cleared", "target": "suggest"}) if action == "rebuild-title": # Heavy — run in background so the request returns immediately. import threading as _t _t.Thread(target=_srv._build_all_title_indexes, daemon=True).start() return handler._json(200, {"status": "started", "target": "title"}) if action == "rebuild-qid": import threading as _t _t.Thread(target=_srv._build_all_qid_indexes, daemon=True).start() return handler._json(200, {"status": "started", "target": "qid"}) return handler._json(400, {"error": "unknown action"}) elif parsed.path == "/manage/health-check": # Kick off the library health report on a worker thread. from zimi import health as _health started, msg = _health.start_check() if started: _activity_after( _health.get_state, _activity_health_finish(activity_actor(handler)), ) return handler._json( 200, {"status": "started" if started else "running", "detail": msg} ) elif parsed.path == "/manage/export-bookmarks": # Save bookmarks to standalone ZIM(s). The client POSTs its localStorage # bookmarks (client-side only — server has no copy) as either: # {"bookmarks": [...]} → one ZIM (v1 / Export all) # {"exports": [{"name","title","bookmarks":[...]}, ...]} → one ZIM each from zimi import zimwriter as _zw def _clean_bm(b): return { "zim": str(b.get("zim", "")), "path": str(b.get("path", "")), "title": str(b.get("title", "")), "section": str(b.get("section", "")), } def _safe_name(s): s = re.sub(r"[^a-zA-Z0-9._-]+", "_", str(s or "")).strip("_.") return s[:60] or None exports = data.get("exports") total = 0 if isinstance(exports, list) and exports: payload = [] for job in exports: if not isinstance(job, dict): continue bms = [ _clean_bm(b) for b in (job.get("bookmarks") or []) if isinstance(b, dict) ] if not bms: continue total += len(bms) # Section headers the index must render even when empty (an # exported empty folder is shown, never silently dropped). sections = [ str(s)[:120] for s in (job.get("sections") or [])[:200] if isinstance(s, str) and s.strip() ] payload.append( { "name": _safe_name(job.get("name")), "title": str(job.get("title") or "")[:120] or None, "sections": sections, "bookmarks": bms, } ) if not payload: return handler._json(400, {"error": "No bookmarks to export"}) else: bookmarks = data.get("bookmarks") if not isinstance(bookmarks, list) or not bookmarks: return handler._json(400, {"error": "No bookmarks to export"}) payload = [_clean_bm(b) for b in bookmarks if isinstance(b, dict)] total = len(payload) if total > 2000: return handler._json(400, {"error": "Too many bookmarks (max 2000)"}) started, msg = _zw.start_export(payload) if started: _activity_after( _zw.get_export_state, _activity_export_finish(activity_actor(handler), total), ) return handler._json( 200, {"status": "started" if started else "busy", "detail": msg} ) elif parsed.path == "/manage/build-fts": zim_name = data.get("name", "") if not zim_name: return handler._json(400, {"error": "Missing 'name' parameter"}) try: result = _srv._build_fts_for_index(zim_name) return handler._json(200, result) except FileNotFoundError as e: log.warning("FTS build: ZIM not found: %s", e) return handler._json(404, {"error": "ZIM not found"}) except Exception as e: log.error("FTS build failed for %s: %s", loggable(zim_name), loggable(e)) return handler._json(500, {"error": "FTS build failed"}) elif parsed.path == "/manage/own-zims": # Remove one of Zimi's own ZIMs from this server, or add it back from # the Catalog. The file is part of the package and is never deleted. name, gone = data.get("name"), data.get("removed") if not isinstance(gone, bool) or not _srv.set_own_zim_removed(str(name), gone): return handler._json( 400, { "error": "name is zimi_games or zimi_almanac, removed is true or false" }, ) log.info( "%s %s", "Removed" if gone else "Added back", str(name).replace("\r", "").replace("\n", ""), ) from zimi import ownzims return handler._json(200, {"zims": ownzims.catalog()}) elif parsed.path == "/manage/delete": filename = data.get("filename", "") if not filename or ".." in filename or "/" in filename: return handler._json(400, {"error": "Invalid filename"}) if not filename.endswith(".zim"): return handler._json(400, {"error": "Only .zim files can be deleted"}) # One of Zimi's own ZIMs is part of the package: Delete removes it from # this server (the Catalog adds it back) and never touches the file. from zimi import ownzims as _own # Only the package's file: a copy of the same name in the library is an # ordinary ZIM (deleted below), unless the package's file holds the name. own_name = _own.name_of_file(filename) served = (_srv.get_zim_files() or {}).get(own_name) if own_name else None if served and ( not _own.is_own_path(served) or os.path.basename(served) != filename ): own_name = None # not the package's file: an ordinary ZIM, deleted below if own_name: _srv.set_own_zim_removed(own_name, True) return handler._json(200, {"status": "removed", "own": own_name}) # A ZIM in a SUBFOLDER (everything `zimi create` writes lands in # created/, and folders are categories now) is listed by its basename, # so joining it onto ZIM_DIR looked in the wrong directory: the delete # 404'd, the file survived, and the next scan brought it straight back # (Eric: "the ones I deleted kept coming back"). Resolve through the # library's own name→path map, which knows where each file actually is, # and keep the traversal guard by requiring the result to live under # ZIM_DIR. filepath = join_inside(_srv.ZIM_DIR, filename) if filepath is None: return handler._json(400, {"error": "Invalid filename"}) if not os.path.exists(filepath): root = os.path.realpath(_srv.ZIM_DIR) for candidate in (_srv.get_zim_files() or {}).values(): if os.path.basename(candidate) != filename: continue label = libfolders.owner(candidate) if ( label is not None and nomadapi.managed() and nomadapi.is_nomad_path(candidate) ): return _delete_through_nomad(handler, filename) if label is not None: return handler._json( 403, { "error": "not_ours", "error_key": "folder_not_ours", "label": label, }, ) resolved = os.path.realpath(candidate) if resolved == root or not resolved.startswith(root + os.sep): continue # outside the library — not ours to delete filepath = resolved break if not os.path.exists(filepath): return handler._json(404, {"error": f"File not found: {filename}"}) try: file_size = 0 try: file_size = os.path.getsize(filepath) except OSError: pass # Cache ZIM info before deletion so history shows proper title/icon zim_info = {} try: for z in _srv._zim_list_cache or []: if z.get("file") == filename: zim_info = { "title": z.get("title", ""), "name": z.get("name", ""), "has_icon": z.get("has_icon", False), } break except Exception as e: log.debug( "Failed to cache ZIM metadata before deletion of %s: %s", loggable(filename), loggable(e), ) pass # Release this ZIM's pooled handles BEFORE unlinking. Windows # refuses to remove a file anyone still has open, and a pooled # libzim Archive is exactly that, so Delete answered 500 there # every time. A no-op on POSIX, where unlink of an open file has # always worked. try: _srv.release_zim_handles([_srv._zim_short_name(filename)]) except Exception as e: log.debug( "Handle release before deleting %s: %s", loggable(filename), loggable(e), ) os.remove(filepath) log.info("Deleted ZIM: %s", loggable(filename)) record_activity( "delete", zim_info.get("title") or zim_info.get("name") or filename, actor=activity_actor(handler), size_bytes=file_size, ) _srv._append_history( { "event": "deleted", "ts": time.time(), "filename": filename, "size_bytes": file_size, **zim_info, } ) # Splice the file out of the live library instead of rebuilding it. # The old shape here — load_cache(force=True) under _zim_lock — # re-opened and re-scanned every archive while holding the lock # every libzim request needs, so pressing Delete froze search and # reading for the length of the rescan (#51). The full rescan # survives as the fallback for the cases the splice won't handle. unregistered = False try: unregistered = _srv.unregister_zim_file(filename) except Exception as e: log.warning( "Incremental removal of %s failed (%s) — falling back to a " "full library rescan", loggable(filename), loggable(e), ) if not unregistered: with _srv._zim_lock: _srv.load_cache(force=True) _srv._search_cache_clear() _srv._suggest_cache_clear() _srv._clean_stale_title_indexes() # The library just changed size — don't show the pre-delete free # space for the rest of the memo window. Imported here, not at # module scope: http.py imports this module. from zimi import http as _http _http._reset_disk_usage_cache() # Stop seeding the file we just deleted. Without this the engine # keeps advertising (and hash-check failing) the missing file # until the 12h maintenance pass or a restart. peek_backend() # no-ops when BT is off, so this is safe unconditionally; run it # off the response thread. try: from zimi import library as _lib threading.Thread(target=_lib.retire_stale_seeds, daemon=True).start() except Exception as e: log.debug("Post-delete seed retire skipped: %s", e) return handler._json(200, {"status": "deleted", "filename": filename}) except OSError as e: log.error("Failed to delete %s: %s", loggable(filename), loggable(e)) return handler._json(500, {"error": "Failed to delete file"}) elif parsed.path == "/manage/cleanup-tmp": # Remove only genuinely orphaned partials. Defense in depth: even if a # stale client posts this, never delete an active, queued, or # resumable-with-progress .zim.tmp the user still wants. from zimi import library as _lib _protected, orphaned = _lib.classify_partials() removed = [] for info in orphaned: fpath = os.path.join(_srv.ZIM_DIR, info["filename"]) try: os.remove(fpath) removed.append( {"filename": info["filename"], "size_bytes": info["size_bytes"]} ) log.info("Cleaned up orphaned partial download: %s", info["filename"]) except OSError: pass return handler._json(200, {"removed": removed}) elif parsed.path == "/manage/update": # Trigger manual update: check for updates and start downloads updates = _srv._check_updates() started = [] # Eric's case exactly: this is the same work the auto-updater does, and # the only difference worth recording is that a person asked for it. actor = activity_actor(handler) for upd in updates: url = upd.get("download_url") if url: dl_id, err = _srv._start_download(url, actor=actor) if not err: started.append({"name": upd.get("name", "?"), "id": dl_id}) return handler._json( 200, {"status": "started", "count": len(started), "downloads": started} ) elif parsed.path == "/manage/auto-update": if _srv._auto_update_env_locked: return handler._json( 403, {"error": "Auto-update is controlled by ZIMI_AUTO_UPDATE env var"} ) enabled = data.get("enabled", _srv._auto_update_enabled) freq = data.get("frequency", _srv._auto_update_freq) if freq not in _srv._FREQ_SECONDS: return handler._json( 400, { "error": f"Invalid frequency. Use: {', '.join(_srv._FREQ_SECONDS.keys())}" }, ) _srv._auto_update_freq = freq if enabled and not _srv._auto_update_enabled: _srv._auto_update_enabled = True if _srv._auto_update_thread and _srv._auto_update_thread.is_alive(): log.info("Auto-update thread still running, reusing it") else: _srv._auto_update_thread = threading.Thread( target=_srv._auto_update_loop, kwargs={"initial_delay": 30}, daemon=True, ) _srv._auto_update_thread.start() log.info("Auto-update enabled: %s (first check in 30s)", loggable(freq)) elif not enabled and _srv._auto_update_enabled: _srv._auto_update_enabled = False log.info("Auto-update disabled") _srv._save_auto_update_config(_srv._auto_update_enabled, _srv._auto_update_freq) return handler._json( 200, {"enabled": _srv._auto_update_enabled, "frequency": _srv._auto_update_freq}, ) elif parsed.path == "/manage/auto-update-skip": name = data.get("zim") if not isinstance(name, str) or name not in _srv.get_zim_files(): return handler._json(404, {"error": "unknown ZIM"}) skip = data.get("skip") if not isinstance(skip, bool): return handler._json(400, {"error": "skip must be true or false"}) _srv.set_auto_update_skip(name, skip) with _srv._zim_lock: _srv.mark_auto_update_skips(_srv._zim_list_cache) _srv._changes.announce("library", None) return handler._json( 200, {"zim": name, "skip": name in _srv._auto_update_skips} ) elif parsed.path == "/manage/app-update-check": # "Check now" for the Zimi APP release check — bypasses the daily # cache but keeps a short flood guard (see check_app_update). Distinct # from /manage/auto-update directly above, which is ZIM content. return handler._json(200, _app_update_payload(force=True)) elif parsed.path == "/manage/app-update-delay": # How long a release must have been public before this instance is # offered it. Same env-lock contract as the other settings. days, err = set_update_delay_days(data.get("delay_days")) if err == "env_locked": return handler._json( 403, { "error": "Update delay is controlled by the %s env var" % APP_UPDATE_DELAY_ENV }, ) if err: return handler._json( 400, { "error": "Invalid delay. Use whole days, 0 to %d" % APP_UPDATE_DELAY_MAX }, ) log.info("App update delay set to %d day(s)", days) # The delay is applied when the payload is built, so no re-check is # needed — the cached answer is still the right answer. return handler._json(200, _app_update_payload()) elif parsed.path == "/manage/apps": # The server-wide apps switch. Same env-lock contract as the other # settings: ZIMI_APPS wins and the write is refused, not ignored. # ``shown`` names the apps offered; ``enabled`` is the old all-or-nothing. enabled, err = _srv.set_apps_enabled( data.get("shown") if "shown" in data else data.get("enabled") ) if err == "env_locked": return handler._json( 403, {"error": "Apps are controlled by the %s env var" % _srv.APPS_ENV} ) shown = _srv.apps_shown() log.info( "Apps offered: %s", ", ".join(n for n in _srv.APP_NAMES if n in shown) or "none", ) return handler._json( 200, { "enabled": enabled, "shown": [n for n in _srv.APP_NAMES if n in shown], "env_locked": False, }, ) elif parsed.path == "/manage/satellites": # "Satellite data from the internet": {"mode": "ask"|"auto"|"never"}. # Same env-lock contract as the other settings: ZIMI_SATELLITE_UPDATES # (or ZIMI_OFFLINE, which forces never) wins and the write is refused. from zimi import satellites as _sats _mode, err = _sats.set_update_mode(data.get("mode")) if err == "invalid": return handler._json(400, {"error": "mode is ask, auto or never"}) if err == _sats.LOCKED_OFFLINE: return handler._json(403, {"error": "Zimi is offline (ZIMI_OFFLINE)"}) if err == _sats.LOCKED_ENV: return handler._json( 403, { "error": "Satellite data is controlled by the %s env var" % _sats.UPDATES_ENV }, ) if err: return handler._json(500, {"error": "Could not save the setting"}) return handler._json(200, _sats.setting()) elif parsed.path == "/manage/almanac-hd": # Almanac HD: {"mode": "ask"|"auto"|"never"} saves the setting (the # env-lock contract: ZIMI_ALMANAC_HD or ZIMI_OFFLINE wins); {"start": # true} queues the download, the Almanac's offer said yes. from zimi import almanachd as _hd if data.get("start"): dl_id, err = _hd.start(activity_actor(handler)) if err == "never": return handler._json( 409, {"error": "Almanac HD is set to never be fetched"} ) if err == "unavailable": return handler._json(404, {"error": "No Almanac HD for this version"}) if err and err != "installed": return handler._json(500, {"error": "Could not start the download"}) return handler._json(200, dict(_hd.status(), id=dl_id)) _mode, err = _hd.POLICY.set(data.get("mode")) if err == "invalid": return handler._json(400, {"error": "mode is ask, auto or never"}) if err == outbound.LOCKED_OFFLINE: return handler._json(403, {"error": "Zimi is offline (ZIMI_OFFLINE)"}) if err == outbound.LOCKED_ENV: return handler._json( 403, {"error": "Almanac HD is controlled by the %s env var" % _hd.ENV} ) if err: return handler._json(500, {"error": "Could not save the setting"}) return handler._json(200, _hd.status()) elif parsed.path == "/manage/satellites/refresh": # The Earth view's "Get fresh data": one CelesTrak fetch, waited for, # answered with the view's payload so it redraws from the answer. from zimi import satellites as _sats payload, err = _sats.refresh_now() if err == "never": return handler._json( 409, {"error": "Satellite data is set to never be fetched"} ) if err: return handler._json(502, {"error": "Could not reach CelesTrak"}) payload["can_change"] = True return handler._json(200, payload) elif parsed.path == "/manage/voices": # "Voices for Dictionary": {"mode": "ask"|"auto"|"never"}, the same # env-lock contract: ZIMI_VOICE_DOWNLOADS (or ZIMI_OFFLINE) wins. from zimi import voices as _voices _mode, err = _voices.POLICY.set(data.get("mode")) if err == "invalid": return handler._json(400, {"error": "mode is ask, auto or never"}) if err == outbound.LOCKED_OFFLINE: return handler._json(403, {"error": "Zimi is offline (ZIMI_OFFLINE)"}) if err == outbound.LOCKED_ENV: return handler._json( 403, { "error": "Voices are controlled by the %s env var" % _voices.DOWNLOADS_ENV }, ) if err: return handler._json(500, {"error": "Could not save the setting"}) return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/voices/choose": # Which engine says a language: {"lang": primary, "engine": name}, or # engine null for the best here. from zimi import voices as _voices if not _voices.set_choice(data.get("lang"), data.get("engine")): return handler._json( 409, {"error": "That voice cannot say this language here"} ) return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/voices/download": # One language's clearer voice, fetched in the background: {"lang": tag}. from zimi import voices as _voices _ok, err = _voices.start_download(data.get("lang")) if err == "unknown": return handler._json(404, {"error": "No such voice"}) if err in ("never", "noengine"): return handler._json(409, {"error": "Voices cannot be downloaded here"}) if err == "busy": return handler._json(409, {"error": "Another voice is downloading"}) if err == "blocked": return handler._json( 409, { "error": "Voices cannot be set up here", "detail": _voices.setup_problem(), }, ) return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/voices/cancel": # The download in flight stops; its partial files go. from zimi import voices as _voices _voices.cancel_download() return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/voices/test": # Settings' Test voice speed: {"lang", "chunks"}, a paragraph in # the page's language cut as a reading cuts it. Runs in the # background; the payload's "testing" says how far it is, "timings" # what it found. from zimi import voices as _voices started = _voices.start_test(data.get("lang"), data.get("chunks")) if started is False: return handler._json(400, {"error": "bad request"}) return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/voices/remove": # {"lang": tag}: the voice and its audio go; the language falls back. from zimi import voices as _voices if not _voices.remove(data.get("lang")): return handler._json(404, {"error": "No such voice"}) return handler._json(200, _voices.manage_payload()) elif parsed.path == "/manage/books/whole": # A ZIM that is one book (a textbook captured whole) onto the # Bookshelf: {"zim": name, "whole": true}; false takes a ZIM off # the shelf, null leaves it to what it is. from zimi import books as _books name = data.get("zim") whole = data.get("whole") if not isinstance(name, str) or name not in _srv.get_zim_files(): return handler._json(404, {"error": "No such ZIM"}) if whole not in (True, False, None): return handler._json(400, {"error": "whole is true, false or null"}) reader = _books.set_whole(name, whole) log.info("Bookshelf: %s set by hand to %s", loggable(name), loggable(whole)) return handler._json(200, {"zim": name, "whole": whole, "reader": reader}) elif parsed.path == "/manage/app-update-mode": # "Check for Zimi updates": {"mode": "ask"|"auto"|"never"}. Same # env-lock contract as the satellite setting: ZIMI_UPDATE_CHECK (or # ZIMI_OFFLINE, which forces never) wins and the write is refused. _mode, err = UPDATE_CHECK.set(data.get("mode")) if err == "invalid": return handler._json(400, {"error": "mode is ask, auto or never"}) if err == outbound.LOCKED_OFFLINE: return handler._json(403, {"error": "Zimi is offline (ZIMI_OFFLINE)"}) if err == outbound.LOCKED_ENV: return handler._json( 403, { "error": "Update checks are controlled by the %s env var" % APP_UPDATE_CHECK_ENV }, ) if err: return handler._json(500, {"error": "Could not save the setting"}) return handler._json(200, _app_update_payload()) elif parsed.path == "/manage/download-schedule": # Night-window queueing + the global download-speed cap. Same env-lock # contract as the other settings endpoints: ZIMI_DL_WINDOW locks the # window, ZIMI_BT_DOWN_KB (via bt_down_kb) locks the speed cap. from zimi import library as _lib from zimi import p2p sched = _lib._load_download_schedule() # Window fields + the upload restrictor (restrict seeding to the window # + its trickle cap). All ride the same config file, so one save covers # any subset the client sent; absent fields are preserved. window_keys = ( "enabled", "start", "end", "upload_restrict", "upload_trickle_kb", ) if any(k in data for k in window_keys): if sched.get("locked"): return handler._json( 403, { "error": "Download window is controlled by the ZIMI_DL_WINDOW env var" }, ) enabled = bool(data.get("enabled", sched["enabled"])) start = data.get("start", sched["start"]) end = data.get("end", sched["end"]) if _lib._parse_hhmm(start) is None or _lib._parse_hhmm(end) is None: return handler._json( 400, {"error": "start/end must be 'HH:MM' (24-hour)"} ) upload_restrict = ( bool(data["upload_restrict"]) if "upload_restrict" in data else sched["upload_restrict"] ) upload_trickle_kb = sched["upload_trickle_kb"] if "upload_trickle_kb" in data: try: upload_trickle_kb = max(1, int(data["upload_trickle_kb"])) except (ValueError, TypeError): return handler._json( 400, {"error": "upload_trickle_kb must be a number"} ) if not _lib._save_download_schedule( enabled, start, end, upload_restrict, upload_trickle_kb ): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) # Whether the window just opened or scheduling was turned off, # release anything already waiting now — don't wait for a tick. threading.Thread(target=_lib._download_schedule_tick, daemon=True).start() # Global download-speed cap (KB/s, 0 = unlimited) — shared with the BT # download limit so one number governs every transport. if "download_kb" in data: if p2p.is_bt_down_env_locked(): return handler._json( 403, { "error": "Download speed limit is controlled by the ZIMI_BT env var" }, ) try: kb = max(0, int(data["download_kb"])) except (ValueError, TypeError): return handler._json(400, {"error": "download_kb must be a number"}) if not p2p.set_pref("bt_down_kb", kb): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) p2p.apply_rate_limits() return handler._json(200, _lib._download_schedule_status()) elif parsed.path == "/manage/seeding-action": # Pause / resume / stop one seed, or stop everything — the # sidecar shouldn't need a terminal to be told to quiet down. from zimi import p2p backend = p2p.peek_backend() if backend is None: return handler._json(400, {"error": "BitTorrent engine is not running"}) from zimi import library as _lib_seeds action = data.get("action", "") if action == "stop_all": stopped = 0 try: for raw in backend.list_managed(): files = raw.get("files", []) fname = os.path.basename(files[0].get("path", "")) if files else "" if not fname.endswith(".zim"): continue # Same in-flight guard as the /manage/seeding list: # list_managed() returns downloading torrents too, and an # active BT download lives in the staging dir — where # remove(delete_files=True) really deletes payload. The # seeds panel never showed those rows; the button that # says "remove from seeding" must not cancel downloads. if _bt_still_downloading(raw): continue try: backend.remove(raw.get("gid", ""), delete_files=True) stopped += 1 # A user stop is deliberate — don't resurrect it # from the intent ledger at next startup. _lib_seeds.unrecord_seed(fname) except Exception: pass except Exception: pass log.info("Seeding: stopped all (%d)", stopped) return handler._json(200, {"status": "ok", "stopped": stopped}) tid = data.get("id", "") if not tid or action not in ("pause", "resume", "stop"): return handler._json( 400, {"error": "provide id and action: pause/resume/stop/stop_all"} ) try: if action == "pause": backend.pause(tid) elif action == "resume": backend.resume(tid) else: # Resolve the filename BEFORE removing, to drop its ledger # intent too — a user stop must not come back at startup. _stop_fname = "" try: for _raw in backend.list_managed(): if _raw.get("gid", "") == tid: _fs = _raw.get("files", []) if _fs: _stop_fname = os.path.basename(_fs[0].get("path", "")) break except Exception: pass backend.remove(tid, delete_files=True) if _stop_fname: _lib_seeds.unrecord_seed(_stop_fname) except Exception: return handler._json(502, {"error": "engine refused the action"}) return handler._json(200, {"status": "ok"}) elif parsed.path == "/manage/nat-recheck": # The "retry" button every real BT client has: re-map UPnP and # re-test reachability. Slow (SSDP + external check, a few # seconds) but asked for by an admin looking: the button, or the # sharing settings opening with BitTorrent on. The only caller that # asks portcheck.transmissionbt.com. from zimi import p2p, p2p_nat if not p2p.is_torrent_enabled(): return handler._json(400, {"error": "BitTorrent is turned off"}) result = p2p_nat.probe( p2p.get_bt_port(), try_upnp=p2p.is_upnp_enabled(), check_reachable=True ) return handler._json(200, {"nat": result}) elif parsed.path == "/manage/bt-client": return _handle_bt_client(handler, data) elif parsed.path == "/manage/library-folders": return _handle_library_folders(handler, data) elif parsed.path == "/manage/bt-settings": # Seed/mirror toggles. An env var locks its field — UI changes would # be silently overridden on next read (same contract as auto-update). from zimi import p2p changed = {} if "seed" in data: if p2p.is_seed_env_locked(): return handler._json( 403, {"error": "Seeding is controlled by the ZIMI_BT env var"} ) if not p2p.set_pref("seed", bool(data["seed"])): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["seed"] = bool(data["seed"]) # Settings govern LIVE seeds too: toggling seeding off stops the # running library seeds (files and intent stay); on re-seeds them. from zimi import library as _lib_seed threading.Thread(target=_lib_seed.apply_seed_settings, daemon=True).start() if "mirror" in data: if p2p.is_mirror_env_locked(): return handler._json( 403, {"error": "Mirror mode is controlled by the ZIMI_BT env var"}, ) if not p2p.set_pref("mirror", bool(data["mirror"])): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["mirror"] = bool(data["mirror"]) from zimi import library as _lib if changed["mirror"]: # Seed the installed library now, off the request thread # (hash checks + torrent fetches take a while). def _mirror_kickoff(): # Retag seeds that predate mirror mode to the mirror's # uncapped ratio before syncing in the rest. _lib.apply_seed_policy() _lib.mirror_sync() _lib.archive_catalog_torrents() threading.Thread(target=_mirror_kickoff, daemon=True).start() else: # Off = stop seeding, keep the archive (a toggle never # deletes a backup; Mirror on again re-seeds from disk). threading.Thread(target=_lib.stop_mirror_seeds, daemon=True).start() if "peer_share" in data: from zimi import p2p_discovery as _disc if _disc.is_share_env_locked(): return handler._json( 403, {"error": "LAN sharing is controlled by the ZIMI_NEARBY env var"}, ) if not p2p.set_pref("peer_share", bool(data["peer_share"])): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["peer_share"] = bool(data["peer_share"]) # Nearby on or off decides announcing too, applied now. threading.Thread(target=_disc.apply_enabled, daemon=True).start() if "bt_port" in data: if p2p.is_bt_port_env_locked(): return handler._json( 403, {"error": "The BT port is controlled by the ZIMI_BT env var"} ) try: port = int(data["bt_port"]) assert 1024 <= port <= 65535 except (ValueError, TypeError, AssertionError): return handler._json(400, {"error": "Port must be 1024-65535"}) if not p2p.set_pref("bt_port", port): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["bt_port"] = port # Apply live: respawn the sidecar on the new port + re-map UPnP def _respawn(): if p2p.switch_engine(data_dir=_srv.ZIMI_DATA_DIR): try: from zimi import p2p_nat p2p_nat.probe(port, try_upnp=p2p.is_upnp_enabled()) except Exception: pass threading.Thread(target=_respawn, daemon=True).start() if "upnp" in data: if p2p.is_upnp_env_locked(): return handler._json( 403, {"error": "UPnP is controlled by the ZIMI_BT env var"} ) if not p2p.set_pref("upnp", bool(data["upnp"])): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["upnp"] = bool(data["upnp"]) if "torrent" in data: if p2p.is_torrent_env_locked(): return handler._json( 403, {"error": "BitTorrent is controlled by the ZIMI_BT env var"}, ) on = bool(data["torrent"]) if not p2p.set_pref("torrent", on): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["torrent"] = on if not on: # Switch off means OFF — stop the engine and its seeds now, # in a client the operator runs too. try: p2p.shutdown_backend(release=True) except Exception: pass else: # Switch on means ON — bring the sidecar up now. Status # endpoints only peek, so without this nothing spawns it # until the next download and the UI dot stays grey. def _spawn_now(): try: p2p.get_backend(data_dir=_srv.ZIMI_DATA_DIR) except Exception: pass threading.Thread(target=_spawn_now, daemon=True).start() if "peer_name" in data: from zimi import p2p_discovery as _disc2 if _disc2.is_name_env_locked(): return handler._json( 403, {"error": "Peer name is controlled by the ZIMI_NEARBY env var"}, ) name = str(data["peer_name"]).strip()[:63] if not p2p.set_pref("peer_name", name): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["peer_name"] = name # Apply live: re-register the mDNS advertisement with the new # name — no restart required. from zimi import p2p_discovery as _disc2 threading.Thread(target=_disc2.restart_advertising, daemon=True).start() if "seed_ratio" in data: if p2p.is_seed_ratio_env_locked(): return handler._json( 403, {"error": "Seed ratio is controlled by the ZIMI_BT env var"}, ) try: ratio = max(0.0, min(10.0, float(data["seed_ratio"]))) except (ValueError, TypeError): return handler._json(400, {"error": "seed_ratio must be a number"}) if not p2p.set_pref("seed_ratio", ratio): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["seed_ratio"] = ratio # Apply the new cap to every live library seed, not just future # adds — the ledger stops seeds already past the new ratio, and a # ratio raised from 0 brings back the seeds it had stopped. from zimi import library as _lib_ratio threading.Thread(target=_lib_ratio.apply_seed_settings, daemon=True).start() # Global bandwidth caps (KB/s, 0 = unlimited). Applied live to the # running session so a new limit takes effect without a restart. for _field, _envlock in ( ("bt_up_kb", p2p.is_bt_up_env_locked), ("bt_down_kb", p2p.is_bt_down_env_locked), ): if _field in data: if _envlock(): return handler._json( 403, { "error": "Bandwidth limits are controlled by the ZIMI_BT env var" }, ) try: kb = max(0, int(data[_field])) except (ValueError, TypeError): return handler._json(400, {"error": f"{_field} must be a number"}) if not p2p.set_pref(_field, kb): return handler._json( 500, {"error": "could not save setting (config dir not writable)"}, ) changed[_field] = kb if any(k in changed for k in ("bt_up_kb", "bt_down_kb")): p2p.apply_rate_limits() # Max concurrent downloads (governs HTTP + BT via library.py's queue). if "max_active_downloads" in data: if p2p.is_max_active_downloads_env_locked(): return handler._json( 403, {"error": "Max concurrent downloads is controlled by an env var"}, ) try: n = max(1, min(20, int(data["max_active_downloads"]))) except (ValueError, TypeError): return handler._json( 400, {"error": "max_active_downloads must be a number"} ) if not p2p.set_pref("max_active_downloads", n): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["max_active_downloads"] = n # Raising the cap frees slots that nothing else would drain until a # download finishes — promote queued items now. from zimi import library as _lib_cc threading.Thread(target=_lib_cc.drain_download_queue, daemon=True).start() # Max connections — a real libtorrent session setting, applied live. if "bt_max_connections" in data: if p2p.is_bt_max_connections_env_locked(): return handler._json( 403, {"error": "Max connections is controlled by the ZIMI_BT env var"}, ) try: n = max(10, min(2000, int(data["bt_max_connections"]))) except (ValueError, TypeError): return handler._json( 400, {"error": "bt_max_connections must be a number"} ) if not p2p.set_pref("bt_max_connections", n): return handler._json( 500, {"error": "could not save setting (config dir not writable)"} ) changed["bt_max_connections"] = n p2p.apply_session_limits() if not changed: return handler._json( 400, {"error": "provide torrent/seed/mirror/peer_share/seed_ratio"}, ) log.info("BT settings updated via UI: %s", loggable(changed)) return handler._json(200, p2p.get_mirror_status()) elif parsed.path == "/manage/hot": # Pro hot-cache live update. Rejected when ZIMI_HOT_ZIMS env var is set # (env wins, UI changes would be silently ignored on next read). if "ZIMI_HOT_ZIMS" in os.environ: return handler._json( 403, { "error": "Hot ZIMs are controlled by ZIMI_HOT_ZIMS environment variable" }, ) names = data.get("hot_zims") if not isinstance(names, list): return handler._json( 400, {"error": "missing 'hot_zims' array in request body"} ) # Drop unknown ZIMs rather than 400 — UI can show warnings client-side. zim_files = _srv.get_zim_files() valid = [n for n in names if isinstance(n, str) and n in zim_files] try: _srv.set_hot_zims(valid) except (TypeError, ValueError) as e: log.warning("set_hot_zims rejected payload: %s", e) return handler._json(400, {"error": "invalid hot_zims payload"}) return handler._json(200, {"hot_zims": valid, "saved": len(valid)}) elif parsed.path == "/manage/library-layout": # Per-ZIM category overrides + home section order (#37). Merge-patch: # `overrides` is merged key-by-key (empty string clears an entry back to # the heuristic); `section_order` fully replaces when present. Either key # may be omitted so "Move to…" and "Reorder" send minimal payloads. overrides = data.get("overrides") order = data.get("section_order") sections = data.get("sections") if overrides is None and order is None and sections is None: return handler._json(400, {"error": "nothing to update"}) err = _validate_library_layout(overrides, order, sections) if err: return handler._json(400, {"error": err}) layout = _apply_library_layout(overrides, order, sections) return handler._json( 200, { "status": "ok", "overrides": layout.get("overrides", {}), "section_order": layout.get("section_order", []), "sections": layout.get("sections", []), }, ) elif parsed.path == "/manage/backup": # Restore a backup bundle. Two-step so nothing lands before the admin # confirms: action="preview" (default) returns a diff summary and # applies NOTHING; action="apply" writes. MERGE by default; overwrite # replaces wholesale. A server-scope bundle is admin-only in BOTH # directions — a non-admin session can't preview OR apply one. if _bundle_scope(data) == "server" and admin_kind(handler) is None: return handler._json(403, {"error": "full-server backup requires an admin"}) action = data.get("action", "preview") overwrite = bool(data.get("overwrite")) if action == "apply": result, err = _apply_backup_bundle(data, overwrite=overwrite) record_activity( "restore", "", # the server's own state — named on the client outcome="failed" if err else "ok", detail=err or "", actor=activity_actor(handler), count=len((result or {}).get("applied") or []), ) if err: return handler._json(400, {"error": err}) return handler._json(200, result) # Preview (default): compute the diff, persist nothing. _plan, preview, err = _compute_backup(data, overwrite) if err: return handler._json(400, {"error": err}) return handler._json(200, {"status": "preview", "preview": preview}) else: return handler._json(404, {"error": "not found"})