#!/usr/bin/env python3 """ Zimi -- Offline Knowledge Viewer & API Search and read articles from Kiwix ZIM files. Provides both a CLI and an HTTP server with JSON API + web UI for browsing offline knowledge archives. Requires: libzim (pip install libzim) Optional: PyMuPDF (pip install PyMuPDF) for PDF-in-ZIM text extraction Table of contents (this file: ~980 lines) ----------------------------------------- 1. Imports & Configuration .............. ~60 2. Constants & Shared Utilities ......... ~165 3. History, Favorites & Collections ..... ~260 4. ZIM File Discovery ................... ~370 5. ZIM Listing & Metadata Cache ......... ~460 6. CLI & Entry Points ................... ~710 7. Re-exports ........................... ~895 See also: zimi/search.py (~1,400 lines) — search, suggest, title index, content serving zimi/interlang.py (~1,000 lines) — Q-ID matching, cross-ZIM resolution, languages zimi/library.py (~730 lines) — downloads, catalog, auto-update zimi/http.py (~1,220 lines) — rate limiting, metrics, ZimHandler class zimi/manage.py (~450 lines) — auth, /manage/* route handlers zimi/previews.py (~600 lines) — content preview extraction Configuration: ZIM_DIR Path to directory containing *.zim files (default: /zims) ZIMI_DATA_DIR Where Zimi keeps its own state (default: /.zimi) ZIMI_HOST Address to bind (default: 0.0.0.0) ZIMI_PORT Port to bind (default: 8899) ZIMI_CONFIG Path to a JSON config file (default: /zimi.json) ZIMI_MANAGE Enabled by default; set to "0" to disable management endpoints Precedence is CLI flag > environment > config file > built-in default: the file sits below the environment so adding one can never change how a running deployment behaves. `zimi config` prints the resolved values and their provenance. The config file also carries settings that have no flag and are read by other modules: manage, manage_user, manage_password, api_token, offline, hot_zims, index_throttle (see CONFIG_ENV_SETTINGS). A value that comes from the file is published into the matching environment variable at startup, so one file can describe a whole instance without a click-through setup. Usage (CLI): zimi search "water purification" --limit 10 zimi read stackoverflow "Questions/12345" zimi list zimi suggest "pytho" Usage (HTTP API): zimi serve --port 8899 GET /search?q=...&limit=5&zim=... Full-text search (cross-ZIM or scoped) GET /read?zim=...&path=... Read article as plaintext GET /w// Serve raw ZIM content (HTML, images) GET /suggest?q=...&limit=10 Title autocomplete GET /snippet?zim=...&path=... Short text snippet GET /list List all ZIM sources with metadata GET /languages Installed language summary GET /article-languages?zim=...&path=... Available translations for article GET /catalog?zim=... PDF catalog for zimgit-style ZIMs GET /random Random article GET /resolve?url=... Cross-ZIM URL resolution GET /resolve?domains=1 Domain→ZIM map for installed sources GET /health Health check """ # ============================================================================ # Imports & Configuration # ============================================================================ import argparse import collections import glob import hashlib import importlib.util import json import logging import os import re import shutil import sys import tempfile import threading import time import socketserver from http.server import ThreadingHTTPServer import ssl from typing import Any, NoReturn import certifi from libzim.reader import Archive from libzim.suggestion import SuggestionSearcher from zimi.libzimcompat import entry_by_id, result_paths from zimi import changes as _changes from zimi import zimparts from zimi.safety import loggable # PyMuPDF, for reading PDFs embedded in ZIM files. # # `pymupdf` is the module's real name; `fitz` is the historical alias, and # importing it on a current PyMuPDF PRINTS to stdout: # # warning: The `fitz` API is deprecated and will be removed in future. # # stdout is a protocol channel for the MCP server and a parseable channel for # the CLI, so that line corrupted the JSON-RPC handshake and turned up inside # `zimi config` output. Both of those were caught as "JSON decode error", which # names the symptom and hides the cause — a library's deprecation notice. # # Importing the current name is also the fix for the deprecation itself, rather # than a way to silence it: `fitz` is scheduled to go away. try: import pymupdf as fitz HAS_PYMUPDF = True except ImportError: try: import fitz # PyMuPDF older than 1.24.3, which had no `pymupdf` name HAS_PYMUPDF = True except ImportError: HAS_PYMUPDF = False # SSL context using certifi CA bundle (PyInstaller bundles lack system certs) SSL_CTX = ssl.create_default_context(cafile=certifi.where()) ZIMI_VERSION = "1.15.7" def bundled(module): """Whether ``zimi.`` is part of this install. The zimi package has every module. zimi-mcp (packaging/zimi-mcp) is built from the same tree with only the search-and-read core: no web app, no downloads, no capture. The few places the core reaches for the rest ask here first, so a missing module is a decision, not a caught ImportError that would also hide a real one. Asked of the package's own directory, not of sys.meta_path: an editable install of the full zimi (CI's) adds a finder that maps every ``zimi.`` to the source tree, so a staged zimi-mcp beside it answered "bundled" for the web app and then imported it.""" import importlib.machinery here = [os.path.dirname(os.path.abspath(__file__))] return importlib.machinery.PathFinder.find_spec(f"zimi.{module}", here) is not None # Standing maintenance cadence: catalog TTL is 24h and UPnP leases are # 24h — run every 12h so both stay fresh at half-life. _MAINTENANCE_INTERVAL = 12 * 3600 _background_services_started = False def _bt_prefs_path(): """Where the BT/sharing prefs live. One derivation shared by the serve boot and the headless backup/restore CLI — if the two disagreed, a CLI backup would silently carry empty sharing prefs.""" return os.path.join(ZIMI_DATA_DIR, "bt", "prefs.json") def start_background_services(http_port): """P2P init, download resume, NAT/UPnP probe, LAN discovery, mirror upkeep, and the 12h maintenance loop — shared by the serve CLI and the desktop app (which builds its own HTTP server and used to miss ALL of this; BT only worked there via the lazy download-time spawn). Everything network-ish runs on background threads: nothing here may delay READY / the first request. Starting the BT engine once stalled startup for minutes. All parts fail soft.""" global _background_services_started if _background_services_started: return _background_services_started = True from zimi import p2p # Prefs path must be set before the first request can read/write BT # settings — cheap, so it stays synchronous. p2p.set_prefs_path(_bt_prefs_path()) # Registered unconditionally, not just when the startup start succeeds: # the session can come up LATER (port change, mirror enable, lazy # download-time start). shutdown_backend saves fastresume and no-ops # without a backend. import atexit atexit.register(p2p.shutdown_backend) # Registered AFTER shutdown_backend so it runs BEFORE it (atexit is # LIFO): the final accounting pass reads the engine's upload counters # while the session is still alive, so a clean shutdown loses no upload. from zimi import library as _lib_flush atexit.register(_lib_flush.flush_seed_accounting) # Registered last, so it runs first: the download poll must know the # process is leaving before shutdown_backend takes the engine away, or # it reads a stopped engine as "BitTorrent was turned off" and falls # back to HTTP in the seconds before exit. atexit.register(_lib_flush.note_exiting) def _init_p2p_background(): # The engine starts now only when it has work waiting (see # bt_work_waiting); otherwise the first download starts it. try: from zimi import library as _lib_bt if _lib_bt.bt_work_waiting(): p2p.get_backend(data_dir=ZIMI_DATA_DIR) except Exception as e: log.warning("BT backend init failed (HTTP downloads unaffected): %s", e) try: from zimi import p2p_discovery as _disc _disc.start( http_port=http_port, # Advertise the port the engine actually listens on — # get_bt_port() honors the ZIMI_BT blob's port= and the # persisted UI pref; reading the raw env told peers 6881 # while the session (and the NAT probe) used the configured # port. bt_port=p2p.get_bt_port(), zim_count=len(list_zims()), version=ZIMI_VERSION, current=lambda: { "zim_count": len(list_zims()), "bt_port": p2p.get_bt_port(), }, ) import atexit atexit.register(_disc.stop) except Exception as e: # repr + type: zeroconf raises exceptions with empty str() log.warning("Peer discovery startup failed: %s: %r", type(e).__name__, e) # Downloads that were in flight or queued when the server stopped # restart themselves (after the BT backend is up so they can take # the torrent-first path again). try: from zimi import library as _lib _lib.resume_pending_downloads() # Watcher that releases night-window-scheduled downloads when the # window opens (no-op unless the user enabled download scheduling). _lib.start_download_scheduler() # Mirror mode seeds the whole installed library; either way, # drop seeds whose file an update has replaced, and bring # session-resumed seeds under the CURRENT settings (a seed # added under old settings otherwise keeps its old cap forever). _lib.retire_stale_seeds() _lib.apply_seed_policy() _lib.reseed_from_ledger() _lib.mirror_sync() _lib.archive_catalog_torrents() _lib.ensure_magnets_for_installed() # Continuous upload books: sample the engine every 30s so the ledger # tracks lifetime upload closely and the ratio cap is enforced # within half a minute, not at the 12h maintenance cadence. threading.Thread( target=_lib.seed_accounting_loop, daemon=True, name="seed-accounting", ).start() except Exception as e: log.warning("Download resume failed: %s", e) _nat_upkeep() threading.Thread(target=_init_p2p_background, daemon=True, name="p2p-init").start() # Standing maintenance, independent of anyone visiting the site: # refresh the offline catalog copy before it goes stale, renew the # UPnP mapping at half-lease (24h lease dies silently otherwise), # keep magnet manifest / mirror seeds / torrent archive current. def _maintenance_loop(): import random as _random_mod # Jitter so a fleet of Zimis doesn't hit Kiwix on the hour time.sleep(_MAINTENANCE_INTERVAL / 2 + _random_mod.uniform(0, 3600)) while True: _maintenance_pass() time.sleep(_MAINTENANCE_INTERVAL + _random_mod.uniform(0, 3600)) threading.Thread(target=_maintenance_loop, daemon=True, name="maintenance").start() threading.Thread(target=_shape_backfill, daemon=True, name="zim-shapes").start() threading.Thread(target=_sweep_working_files, daemon=True, name="zim-sweep").start() # Zimipedia's Today, worked out before anyone opens it. from zimi import wiki as _wiki threading.Thread( target=_wiki.warm_daily, daemon=True, name="zimipedia-daily" ).start() # Working files a capture left behind. # # Every engine spools beside its output under a `.zimi-` prefix and removes it # in a `finally`. A process that dies between those two — a container restart, # an OOM kill, a watchdog that gave up on a wedged browser — leaves the spool # on disk with nothing that will ever come back for it. One abandoned recording # on the real NAS was 2.6 GB. # # Old enough is the whole safety argument: a live job's spool is minutes old at # most (the stall watchdog gives up at ten), so nothing this removes can belong # to anything still running. _WORKING_PREFIX = ".zimi-" _WORKING_MAX_AGE = 6 * 3600 def _sweep_working_files(): """Remove abandoned capture spools from the directories Zimi writes to.""" time.sleep(_SHAPE_SETTLE_SECONDS) cutoff = time.time() - _WORKING_MAX_AGE freed = 0 for folder in _working_file_dirs(): try: names = os.listdir(folder) except OSError: continue for name in names: if not name.startswith(_WORKING_PREFIX): continue path = os.path.join(folder, name) try: if os.path.getmtime(path) > cutoff: continue if os.path.isdir(path): shutil.rmtree(path, ignore_errors=True) else: freed += os.path.getsize(path) os.remove(path) except OSError as e: log.debug("could not remove %s: %s", path, e) if freed: log.info("removed %.1f MB of abandoned capture files", freed / 1e6) def _working_file_dirs(): """Where captures spool: the library, and the folder created ZIMs land in.""" dirs = [ZIM_DIR] try: from zimi.manage import _create_root root = _create_root() if root: dirs.append(root) except Exception: pass return [d for d in dict.fromkeys(dirs) if d and os.path.isdir(d)] # ── what each ZIM is made of ──────────────────────────────────────────────── # # The composition bar wants one fact per ZIM: the per-kind split of what is # inside it. That fact is like size and entry count — true of the file, cheap to # remember, expensive to derive — so it lives with them in the metadata cache # and is read from there by everything that draws it. # # It is measured HERE and nowhere else, and that is the whole design. The first # attempt read the archive inside the request that drew the panel, which put a # disk seek behind a screen whose only job is to open instantly; measuring at # SCAN time instead would have moved the same cost onto boot, where a cold # library already takes long enough. A background thread owns it: nothing waits # on it, and if it never finishes, the only consequence is a panel with no bar. # # Politeness is the rest of the design, and holding the lock for a "short" run # is not enough of it. A hundred sequential entry reads is nothing on an SSD # and most of a second on the spinning disks a 220 GB library lives on: with # that, the About panel measured a median of 631ms and a worst case of 2.6 # seconds against 6ms idle. Work moved off the request path still reaches the # reader through the one lock they share. # # So it YIELDS rather than pauses. While anyone is using the library it does # not take the lock at all, and resumes when they stop. The cost is a library # measured later; the benefit is that measuring cannot be felt. _SHAPE_SETTLE_SECONDS = 20.0 # let the server finish waking up first _SHAPE_IDLE_SECONDS = 4.0 # quiet for this long before touching the lock _SHAPE_IDLE_POLL_SECONDS = 1.0 # how often to re-check for quiet _SHAPE_RUN_ENTRIES = 25 # entries per lock hold: short even on a slow disk _SHAPE_BREATH_SECONDS = 0.05 # released between every run, unconditionally _SHAPE_PAUSE_SECONDS = 2.0 # between ZIMs _SHAPE_RETRY_SECONDS = 900.0 # look again for ZIMs added since # Stamped by the HTTP layer on every request (http._record_metric). A worker # that intends to be invisible has to know when somebody is there. LAST_REQUEST_AT = 0.0 def _wait_until_idle(max_wait=None): """Block until nobody has asked the server for anything recently, or for ``max_wait`` seconds when given (a worker with one cheap read to make, which a busy server must not starve). True when it is quiet. """ deadline = None if max_wait is None else time.time() + max_wait while time.time() - LAST_REQUEST_AT < _SHAPE_IDLE_SECONDS: if deadline is not None and time.time() >= deadline: return False time.sleep( _SHAPE_IDLE_POLL_SECONDS if deadline is None else min(_SHAPE_IDLE_POLL_SECONDS, max(0.0, deadline - time.time())) ) return True class _PoliteGuard: """The libzim lock, taken for one short run and handed straight back. Entered once per run of entries by zim_content_breakdown, so a reader who arrives mid-file waits for 25 entries and never for the file. Between runs it waits for quiet again — a burst of traffic stops the measurement rather than queueing behind it.""" def __enter__(self): _wait_until_idle() _zim_lock.acquire() return self def __exit__(self, *_exc): _zim_lock.release() # Unconditional, so a request that arrived while the lock was held gets # it before this worker asks for it again. time.sleep(_SHAPE_BREATH_SECONDS) return False def _shape_backfill(): """Fill in the missing per-ZIM composition, slowly and out of the way.""" from zimi import zimwriter as _zw time.sleep(_SHAPE_SETTLE_SECONDS) # The Apps page's counts first: a few listing pages, where the # provenance walk opens every archive. _app_items_warm() _provenance_warm() while True: try: _shape_backfill_pass(_zw) except Exception: log.debug("ZIM shape backfill pass failed", exc_info=True) time.sleep(_SHAPE_RETRY_SECONDS) _app_items_warm() def _provenance_warm(): """Answer "which ZIMs did Zimi make" once, here, rather than under an admin. kind_store makes the answer survive a restart, but SOMEBODY still has to pay for the first walk, and left alone that somebody is whoever opens Manage -> Creator first after a deploy — which is the wait this was meant to remove. A library whose cache already holds the answer costs nothing here, so this is a one-off on a new install and free afterwards. Runs on the shape worker's thread, after its settle, so it adds no thread and nothing on the serving path waits for it.""" try: from zimi import http as _http _http._zim_kinds() except Exception: log.debug("provenance warm failed", exc_info=True) def _app_items_warm(): """Count ZimiExchange's questions and Reddot's posts for the Apps page here. Books and videos are counted by their details builders; these two were counted only by the app reading its listing, so a fresh server's Apps page showed a size until each app had been opened once. A site already counted costs a dict lookup (app_items_known), so every pass runs this and a ZIM added later is counted at the next one. The listing pages it reads are the ones the app reads first, and stay in its page cache.""" from zimi import exchange, reddot for app in (exchange, reddot): _wait_until_idle() try: app.note_counts() except Exception: log.debug("%s count failed", app.__name__, exc_info=True) def _shape_backfill_pass(_zw): """One sweep: measure every ZIM that has no shape yet. Persisted per ZIM rather than per sweep. The first version collected the whole library and wrote once at the end, which meant a restart part-way through threw away everything it had done and the panel showed nothing until the slowest file in the library had been read. One at a time costs one small JSON write per ZIM, once ever, and each ZIM's bar appears as soon as it is known.""" pending = [ z.get("name") for z in (_zim_list_cache or []) if z.get("name") and not z.get("shape") ] if not pending: return files = get_zim_files() done = 0 for name in pending: path = files.get(name) if not path: continue _wait_until_idle() shape = _zw.zim_content_breakdown( path, guard=_PoliteGuard, run_entries=_SHAPE_RUN_ENTRIES ) if shape: _shape_store({name: shape}) done += 1 log.debug("measured %s: %s", loggable(name), loggable(shape.get("entries"))) time.sleep(_SHAPE_PAUSE_SECONDS) if done: log.info("measured what %d ZIM(s) are made of", done) # One writer at a time for the metadata cache. # # Four separate places read that file, change part of it and write the whole # thing back: the shape worker, the provenance walk, and registering or # unregistering a single ZIM. They run on different threads — the provenance # one from whichever request asked for it — so two of them interleaving means # the second save is built on a copy taken before the first, and the first's # work is simply gone. # # Losing a shape is not a cosmetic loss. The shape worker re-measures anything # without one, and measuring means walking every entry in the file; on a # 40 GB Wikipedia that is minutes of the global libzim lock, every quarter of # an hour, forever. Eric heard it as the NAS cranking and saw it as Manage -> # Creator never finishing, because the walk starves the request that would # have answered it. _disk_cache_lock = threading.RLock() def _update_disk_cache(mutate): """Read the metadata cache, let ``mutate`` change it, write it back. All of it under one lock, so a change is never built on a copy that has since been superseded. ``mutate`` returns True when it changed anything; an unchanged cache is not rewritten.""" with _disk_cache_lock: disk = _load_disk_cache() or {} if mutate(disk): _save_disk_cache(disk) def _shape_store(measured): """Write the shapes into the live list and the disk cache, together. Both, or the answer is forgotten on restart and re-measured for ever; the disk cache is keyed by FILENAME, which is what the live entry's ``file`` field holds.""" for entry in _zim_list_cache or []: shape = measured.get(entry.get("name")) if shape: entry["shape"] = shape def _apply(disk): touched = False for entry in _zim_list_cache or []: shape = measured.get(entry.get("name")) cached = disk.get(entry.get("file", "")) if shape and isinstance(cached, dict): cached["shape"] = shape touched = True return touched _update_disk_cache(_apply) def note_app_items(name, app, n): """How many of what ``app`` shows the ZIM ``name`` holds (its books, its videos, its questions, its posts), counted by the app when it has read them anyway: kept on the live entry as ``items`` and in the metadata cache beside it, so the Apps page counts what each app shows without reading anything on its way. A new build of the ZIM is another file, so another record, counted afresh when the app reads it.""" try: n = int(n) except (TypeError, ValueError): return if n <= 0: return entry = next((z for z in _zim_list_cache or [] if z.get("name") == name), None) if entry is None or (entry.get("items") or {}).get(app) == n: return entry["items"] = dict(entry.get("items") or {}, **{app: n}) filename = entry.get("file", "") def _apply(disk): cached = disk.get(filename) if not isinstance(cached, dict) or (cached.get("items") or {}).get(app) == n: return False cached["items"] = dict(cached.get("items") or {}, **{app: n}) return True _update_disk_cache(_apply) def app_items_known(name, app): """Whether ``app`` has counted what the ZIM ``name`` holds already.""" entry = next((z for z in _zim_list_cache or [] if z.get("name") == name), None) return bool(entry and (entry.get("items") or {}).get(app)) def paged_count(first, read_page): """How many rows a paged listing holds (Stack Exchange's questions, a subreddit's posts): its first page ``{rows, pages}`` full, the last read for what it has left.""" per, pages = len(first.get("rows") or []), int(first.get("pages") or 1) if pages <= 1: return per return (pages - 1) * per + len(read_page(pages).get("rows") or []) # Provenance survives a restart, because the walk that builds it does not. # # "Which ZIMs did Zimi make" is answered by opening each archive and reading # three metadata fields. The answer is memoized per process, so the walk is # free after the first one — and the first one is a read of every file in the # library, paid again on every restart. On a 73-ZIM NAS that is what made # Manage -> Creator's made-here list "super slow" every time (Eric, # 2026-09-11), because a deploy restarts the container. # # The answer is a property of the FILE, keyed by the same name-and-size # signature the memo uses, so it belongs in the cache beside every other fact # about that file. Same shape as _shape_store: the live list and the disk cache # together, or it is forgotten and recomputed forever. # # None is a real answer here and the common one — most ZIMs were published by # somebody else — so the record wraps it rather than storing it bare, and an # absent record means "not looked at yet" instead of "looked at, not ours". def zim_signature(name): """``(mtime, size)`` for an installed ZIM, from the list cache, or None. The file's identity, free: no stat, no archive open, no lock. Replacing a ZIM or re-running a capture over the same filename changes it, which is exactly the question a cached picture has to be able to ask.""" for entry in _zim_list_cache or []: if entry.get("name") == name: mtime, size = entry.get("mtime"), entry.get("size_bytes") if mtime is not None and size is not None: return (mtime, size) return None return None def kind_store(records): """Remember ``{name: {"file": ..., "sig": ..., "kind": ...}}``. One write. Keyed off the filename each record carries rather than looked up in the live list: the walk that produces these runs before the list cache exists in some callers, and a store that quietly wrote nothing would look exactly like a store that worked.""" if not records: return for entry in _zim_list_cache or []: record = records.get(entry.get("name")) if record: entry["zimi_kind"] = record def _apply(disk): touched = False for record in records.values(): cached = disk.get(record.get("file") or "") if isinstance(cached, dict): cached["zimi_kind"] = record touched = True return touched _update_disk_cache(_apply) def _nat_upkeep(): """Map (or renew) the running BT engine's port on the router, for the settings UI and incoming peers. The router is on this network; the external reachability check is the recheck button's alone. Nothing without a running engine: an idle Zimi asks its router for nothing.""" from zimi import p2p as _p2p try: if _p2p.is_torrent_enabled() and _p2p.peek_backend(): from zimi import p2p_nat p2p_nat.probe(_p2p.get_bt_port(), try_upnp=_p2p.is_upnp_enabled()) except Exception as e: log.debug("NAT upkeep failed: %s", e) def _maintenance_pass(): """One standing-maintenance sweep: renew the UPnP mapping (24h lease dies silently otherwise), refresh the offline catalog inside its TTL, keep magnets / mirror seeds / torrent archive current. Runs on the 12h loop; extracted so tests can pin it.""" from zimi import library as _lib _nat_upkeep() try: # Gated: only instances that consume the catalog (Mirror mode, # auto-update, recent user browsing) refresh it; idle Zimis make # zero standing kiwix.org requests. _lib.maintenance_catalog_refresh() _lib._magnets_ensured = False _lib.ensure_magnets_for_installed() _lib.retire_stale_seeds() _lib.apply_seed_policy() _lib.reseed_from_ledger() _lib._catalog_torrents_archived = False _lib.mirror_sync() _lib.archive_catalog_torrents() except Exception as e: log.debug("maintenance pass failed: %s", e) log = logging.getLogger("zimi") logging.basicConfig( format="%(asctime)s %(message)s", datefmt="%H:%M:%S", level=logging.INFO ) DEFAULT_ZIM_DIR = "/zims" DEFAULT_DATA_DIR_NAME = ".zimi" DEFAULT_HOST = "0.0.0.0" DEFAULT_PORT = 8899 def announce_ready(port): """Print `READY ` for whatever started us (CI smoke tests, the desktop launcher, service managers), as ONE write. print() writes the text and the newline separately, and on an unbuffered stdout another thread's log line landed between them: "READY 888323:07:20 Title indexes warmed", which reads as no READY.""" sys.stdout.write(f"READY {port}\n") sys.stdout.flush() # --------------------------------------------------------------------------- # Zero-config ZIM discovery (1.9 portable mode) # # When NOTHING names a ZIM directory — no flag, no env, no config file — the # resolver used to fall straight to the hardcoded fallback (`/zims`, or the # desktop app's `~/Zimi`). Discovery slots in strictly between "nobody said # anything" and that fallback: it probes the directory holding the executable # (a frozen build on a USB stick), the folder a macOS .app bundle sits in, and # the working directory, for `*.zim` files or a `zims/` child holding them. # # The compatibility contract is why this # is a separate, explicitly-passed layer rather than a smarter default: an # explicit ZIM_DIR, --zim-dir, config-file zim_dir, or a desktop-configured # folder must ALWAYS beat a discovered one, and the precedence tests pin that. # --------------------------------------------------------------------------- DISCOVERY_ZIMS_SUBDIR = "zims" # The locations the last discover_zim_dir() call actually probed — surfaced in # the empty-library boot message so "where should I put my files?" has a # concrete answer for every install type, not just Docker. _discovery_probed = [] def _dir_holding_zims(candidate): """The directory Zimi should serve from `candidate`, or None. A hit is `*.zim` directly in the candidate, else in a `zims/` child — the two shapes a hand-assembled folder of ZIMs actually has.""" for d in (candidate, os.path.join(candidate, DISCOVERY_ZIMS_SUBDIR)): if zimparts.in_folder(d): return d return None def discovery_candidates(): """Where discovery looks, in priority order: executable dir (frozen builds only — for a source checkout it would be the Python bin dir), the folder a macOS .app bundle sits in, then the working directory.""" cands = [] if getattr(sys, "frozen", False) or getattr(sys, "_MEIPASS", None): exe_dir = os.path.dirname(os.path.abspath(sys.executable)) cands.append(exe_dir) # Zimi.app/Contents/MacOS/ → the folder holding Zimi.app; that is # the stick root when someone drags the app next to their ZIMs. if exe_dir.replace("\\", "/").endswith(".app/Contents/MacOS"): cands.append(os.path.dirname(os.path.dirname(os.path.dirname(exe_dir)))) try: cands.append(os.getcwd()) except OSError: pass # cwd can be deleted from under a long-lived shell seen = set() return [c for c in cands if not (c in seen or seen.add(c))] PORTABLE_DATA_NAME = "zimi-data" PORTABLE_ZIMS_NAME = "zims" def portable_root(env=None): """The folder a portable Zimi keeps itself in, or None for the normal paths. One rule: a frozen build whose own folder holds ``zimi-data`` (or any run with ZIMI_PORTABLE=1, which ``--portable`` sets) is portable. State then lives in ``/zimi-data`` and the ZIMs are read from ``/zims`` when it exists, so the folder can sit on a USB disk and move between machines. The folder is the executable's; a source run has none, so there ZIMI_PORTABLE=1 means the working directory. It is a default, not an order: a flag, an environment variable or a config file still wins. """ env = os.environ if env is None else env forced = env.get("ZIMI_PORTABLE", "").strip().lower() in ("1", "true", "yes", "on") if getattr(sys, "frozen", False): root = os.path.dirname(os.path.realpath(sys.executable)) elif forced: root = os.getcwd() else: return None if forced or os.path.isdir(os.path.join(root, PORTABLE_DATA_NAME)): return root return None def discover_zim_dir(candidates=None): """Probe the candidate locations for ZIMs. First hit wins; None if none. Only ever consulted when zim_dir would otherwise resolve to the hardcoded default — callers pass the result into resolve_settings(), which applies it below every explicit source.""" global _discovery_probed candidates = discovery_candidates() if candidates is None else list(candidates) _discovery_probed = candidates for cand in candidates: hit = _dir_holding_zims(cand) if hit: return hit return None # --------------------------------------------------------------------------- # Headless configuration file # # One JSON file that describes an instance, so a deployment can be handed over # without click-through setup. JSON and not TOML/YAML on purpose: the package # supports Python 3.9 (no `tomllib`) and stays stdlib-only (no PyYAML), and # every other file Zimi writes is already JSON. # # Scope is deliberately small: only settings that must be known *before* the # server boots. Everything that already has its own state file plus an admin UI # (access mode, auto-update, download schedule, seeding) stays where it is — # folding those in is a migration question, not a config question. # # The file sits BELOW the environment in precedence, which is the whole # compatibility argument: a running Docker/compose deployment that sets ZIM_DIR # keeps winning, so dropping a config file next to an existing instance can # never change how it behaves. Adding config can only fill in what nobody else # said. # # Two families of key, resolved by the same precedence chain but delivered # differently: # # * The four PATH/BIND keys (zim_dir, data_dir, host, port) are consumed by # this module directly — resolve_settings() hands them to apply_data_paths() # and to serve(). # * The ENVIRONMENT-BACKED keys below name settings that had no input other # than an environment variable, read at call time by whichever module owns # the feature. Rather than teaching each of those modules about the config # file — one more resolution path and one more precedence bug apiece — the # single resolution here PUBLISHES its answer into os.environ, but only when # the answer came from the file. An environment variable is never # overwritten, precedence stays exactly what resolve_settings() computed, # and the owning module remains the only thing that interprets the string. # # The credential keys (manage_user, manage_password, api_token) look like an # exception to the scope note above, since each also has a state file and an # admin UI. They are not: their environment variable ALREADY outranks that file, # and the config file feeds that same override layer rather than adding a third # opinion. Provisioning credentials is also the one thing that makes headless # setup headless — without it, first boot is a click-through. # # The bar for adding an environment-backed key: the setting must be read at call # time. ZIMI_RATE_LIMIT, ZIMI_RATE_LIMIT_TRUSTED, ZIMI_RATE_LIMIT_LOGIN, # ZIMI_TRUST_CGNAT and ZIMI_TRUSTED_PROXIES are all frozen into module constants # when zimi.http is imported — which happens while this module is still being # imported, long before argparse can point us at a file — so publishing them # would be a silent no-op. They need their consumer to read them lazily first. # --------------------------------------------------------------------------- CONFIG_FILENAME = "zimi.json" CONFIG_ENV_VAR = "ZIMI_CONFIG" # The path/bind keys, each with its own flag and its own consumer in this file. CONFIG_PATH_KEYS = ("zim_dir", "data_dir", "host", "port") # kind: how a JSON value is validated and encoded into the string its # environment variable would have carried ("str", "bool" or "csv"). # default: what the report shows when nobody set it — the string form of the # consumer's own built-in default. NEVER published; a default must stay # indistinguishable from "unset" so consumers that treat an absent variable # specially (get_hot_zims falls back to hot.json) keep doing so. # secret: masked in `zimi config` output, because that report is what people # paste into bug threads. ConfigSetting = collections.namedtuple( "ConfigSetting", "key env_var kind default default_note secret" ) CONFIG_ENV_SETTINGS = ( ConfigSetting("manage", "ZIMI_MANAGE", "bool", "1", None, False), ConfigSetting("manage_user", "ZIMI_MANAGE_USER", "str", "", "password file", True), ConfigSetting( "manage_password", "ZIMI_MANAGE_PASSWORD", "str", "", "password file", True ), ConfigSetting("api_token", "ZIMI_API_TOKEN", "str", "", "token file", True), ConfigSetting("offline", "ZIMI_OFFLINE", "bool", "0", None, False), ConfigSetting("hot_zims", "ZIMI_HOT_ZIMS", "csv", "", "hot.json", False), # The MCP tool set: lean (search, read, read_section) or full (every tool). # Unset means lean under `zimi mcp` and full under `python -m # zimi.mcp_server`, which kept the full set for configs written before. ConfigSetting("mcp_tools", "ZIMI_MCP_TOOLS", "str", "", "lean", False), ConfigSetting("index_throttle", "ZIMI_INDEX_THROTTLE", "bool", "1", None, False), # Zimi's own ZIMs (zimi/ownzims.py: ZimiGames, the Almanac), committed in the package. ConfigSetting("builtin_zims", "ZIMI_BUILTIN_ZIMS", "bool", "1", None, False), # The one directory tree the WEB may package a ZIM from (zimi.manage's # folder and import modes, and the directory picker that feeds them). # Unset — the default — means the web cannot package a server path at all; # it is not a filter that starts wide open. The CLI is unaffected: someone # at a shell on the machine already has the filesystem. ConfigSetting("create_root", "ZIMI_CREATE_ROOT", "str", "", "web off", False), # Folders another program owns (Project NOMAD, a Kiwix box), read in place # and never changed: a path list, os.pathsep separated (zimi/libfolders.py). ConfigSetting("extra_zim_dirs", "ZIMI_EXTRA_ZIM_DIRS", "str", "", "none", False), # Project NOMAD's admin address: turns on "Zimi manages NOMAD's library # through NOMAD's API" for a NOMAD folder (zimi/nomadapi.py). Unset, the # page's own opt-in decides, and the default is read-only. ConfigSetting("nomad_api", "ZIMI_NOMAD_API", "str", "", "read-only", False), # Trusted-header SSO (zimi/sso.py). Both the team domain and the audience # tag must be present for the feature to switch on at all, which is what # keeps a bare install from trusting an identity header anyone can send. # Neither is a secret: they identify the Access org and application, and a # masked value in `zimi config` would hide the most common misconfiguration. ConfigSetting("sso_team", "ZIMI_SSO_TEAM", "str", "", "SSO off", False), ConfigSetting("sso_aud", "ZIMI_SSO_AUD", "str", "", "SSO off", False), ConfigSetting("sso_role", "ZIMI_SSO_ROLE", "str", "user", None, False), ConfigSetting("sso_proxy", "ZIMI_SSO_PROXY", "csv", "", "private networks", False), # "My LAN is my trust boundary." Off by default, and it has to be typed by # someone who runs the server: with it on, a passwordless instance treats # any private-network client as the primary admin, which is what Zimi did # before 1.9.0 and what GHSA-5mw2-53vv-9pw6 closed. # # The advisory is still right — that default let an adjacent device race # the owner to the first password. What it lacked was a way to say "yes, I # know, this is a single-household server on a LAN I control, and I do not # want an admin password at all", which is a real way people run this and # which 1.9.0 removed with nothing in its place (issue #59). ConfigSetting("lan_admin", "ZIMI_LAN_ADMIN", "bool", "0", None, False), # Settings from outside the private network: on unless this says 0. The # page no longer asks (one switch, a password; manage.manage_external). ConfigSetting("manage_external", "ZIMI_MANAGE_EXTERNAL", "bool", "", "on", False), # The opt out. Management asks for nothing at all: no password, no setup # key, no question about where the request came from. # # Every other answer Zimi has given to "I do not want a password" reasons # about network position, and that reasoning is what has now failed twice # (GHSA-5mw2-53vv-9pw6, and again behind a same-host reverse proxy). A # LAN-shaped rule cannot see a client behind a proxy, and a proxy-shaped # rule cannot tell that client from the internet. This switch does not ask: # it is one meaning, it cannot be spoofed or misread, and an operator who # sets it has said plainly what they want. # # It is a real footgun on a reachable instance, so it announces itself at # boot and the app says so on every management screen. ConfigSetting("manage_open", "ZIMI_MANAGE_OPEN", "bool", "0", None, False), ) _CONFIG_ENV_BY_KEY = {s.key: s for s in CONFIG_ENV_SETTINGS} # Every key v1 understands. Anything else is warned about, never fatal: # failing a boot over an unknown key punishes people for a forward-compatible # file, but silently swallowing a typo is a support ticket. CONFIG_KEYS = CONFIG_PATH_KEYS + tuple(s.key for s in CONFIG_ENV_SETTINGS) # The spellings accepted for a boolean written as a string, mapped to the # canonical form. JSON booleans are the documented way; these exist because # people copy values out of a compose file. _CONFIG_BOOL_WORDS = { "1": "1", "true": "1", "yes": "1", "on": "1", "0": "0", "false": "0", "no": "0", "off": "0", } class ConfigError(Exception): """A config file was found but cannot be used. Always carries the offending path in the message — "invalid JSON" with no filename is exactly the error someone with three mounted config files cannot act on. """ def load_config_file(path): """Read and validate one config file. Returns a dict of known keys. Raises ConfigError (never a traceback) for anything a deployer can fix: unreadable file, malformed JSON, a top-level array, a wrong-typed value. Unknown keys are logged and dropped. """ try: with open(path, encoding="utf-8") as f: raw = f.read() except OSError as e: raise ConfigError(f"config file {path}: cannot read it ({e.strerror})") # An empty file is a legitimate "I have nothing to say" — treat it as {} # rather than as a JSON syntax error, since `touch zimi.json` is a normal # first step and failing there is a bad first impression. if not raw.strip(): return {} try: data = json.loads(raw) except ValueError as e: raise ConfigError(f"config file {path}: invalid JSON ({e})") if not isinstance(data, dict): raise ConfigError( f"config file {path}: expected a JSON object, got {type(data).__name__}" ) unknown = [k for k in data if k not in CONFIG_KEYS] if unknown: log.warning( "config file %s: ignoring unknown key(s): %s (known keys: %s)", path, ", ".join(sorted(unknown)), ", ".join(CONFIG_KEYS), ) config = {} for key in CONFIG_KEYS: if key not in data: continue value = data[key] origin = f"config file {path}" if key == "port": config[key] = _coerce_port(value, origin) elif key in _CONFIG_ENV_BY_KEY: config[key] = _encode_env_value(_CONFIG_ENV_BY_KEY[key], value, origin) elif not isinstance(value, str): raise ConfigError( f"config file {path}: {key} must be a string, " f"got {type(value).__name__}" ) else: config[key] = value return config def _encode_env_value(setting, value, origin): """Validate one environment-backed value and render it as the string its environment variable would have carried. Encoding at parse time (like ``_coerce_port``) is what keeps ``resolve_settings`` type-agnostic: by the time precedence runs, every layer — flag, env, file, default — is speaking the same string, and the module that owns the feature stays the only thing that interprets it. Idempotent, so re-encoding an already-encoded value is safe. """ if setting.kind == "bool": if isinstance(value, bool): return "1" if value else "0" word = ( _CONFIG_BOOL_WORDS.get(value.strip().lower()) if isinstance(value, str) else None ) if word is None: raise ConfigError( f"{origin}: {setting.key} must be true or false, got {value!r}" ) return word if setting.kind == "csv": if isinstance(value, str): return value if isinstance(value, list) and all(isinstance(v, str) for v in value): return ",".join(v.strip() for v in value if v.strip()) raise ConfigError( f"{origin}: {setting.key} must be a list of strings (or a " f"comma-separated string), got {type(value).__name__}" ) if not isinstance(value, str): raise ConfigError( f"{origin}: {setting.key} must be a string, got {type(value).__name__}" ) return value def _coerce_port(value, origin): """Ports arrive as a JSON number, an env string, or an argparse int.""" if isinstance(value, bool): # bool is an int subclass; reject it explicitly raise ConfigError(f"{origin}: port must be a number, got boolean") try: port = int(value) except (TypeError, ValueError): raise ConfigError(f"{origin}: port must be a number, got {value!r}") # 0 stays legal: `--port 0` is how the smoke tests ask the OS for a free one. if not 0 <= port <= 65535: raise ConfigError(f"{origin}: port {port} is outside 0-65535") return port def find_config_file(config_flag=None, env=None, data_dir=None): """Locate the config file: --config, else ZIMI_CONFIG, else /zimi.json. A path someone named explicitly must exist — a typo'd --config that boots with silently different settings is worse than a refusal. The implicit ```` location is the opposite: absence is the normal case for every install that predates this feature, so it is silent. """ env = os.environ if env is None else env for value, origin in ( (config_flag, "--config"), (env.get(CONFIG_ENV_VAR), CONFIG_ENV_VAR), ): if value: if not os.path.isfile(value): raise ConfigError(f"config file {value}: no such file ({origin})") return value if data_dir: implicit = os.path.join(data_dir, CONFIG_FILENAME) if os.path.isfile(implicit): return implicit return None def load_config( zim_dir_flag=None, data_dir_flag=None, config_flag=None, env=None, discovered_zim_dir=None, ): """Discovery + read: the one impure step. Returns ``(config, path_or_None)``. Kept separate from resolution so ``resolve_settings`` stays a pure function of (flags, env, config) and the precedence matrix is testable without touching a filesystem. Note the small circularity in the implicit location: to look for ``/zimi.json`` we must first know the data dir, which is resolved from flags, env and the discovery probe only. That is deliberate — a file can only be *found* somewhere the flags/env/defaults (or a discovered stick, whose ``/.zimi/zimi.json`` makes it self-describing) already point, and a file found there may still relocate the data dir for everything else. """ env = os.environ if env is None else env _, probe_data_dir = resolve_data_paths( zim_dir_flag, data_dir_flag, env, discovered_zim_dir=discovered_zim_dir ) path = find_config_file(config_flag, env, probe_data_dir) if not path: return {}, None return load_config_file(path), path def resolve_settings( zim_dir_flag=None, data_dir_flag=None, host_flag=None, port_flag=None, env=None, config=None, config_path=None, discovered_zim_dir=None, ) -> "collections.OrderedDict[str, tuple[Any, str]]": """Resolve every boot setting, with the provenance of each one. Returns an ordered ``{key: (value, source)}`` mapping where source is a human string like ``env: ZIM_DIR`` — `zimi config` prints it verbatim, and "where did this value come from" is the question that actually costs people time when a deployment misbehaves. The four path/bind keys come first, then every environment-backed key in CONFIG_ENV_SETTINGS; those resolve through the same chain with no flag layer (they have no flags) and their values are always the string their environment variable carries. Precedence, strictly: flag > environment > config file > portable folder > discovered > built-in default (see ``portable_root``). ``discovered_zim_dir`` is the fifth, lowest layer: it only ever replaces the hardcoded fallback, never a value any person or file supplied — that is the 1.9 compatibility contract, and it is why discovery is an argument (the impure probe stays in the caller) rather than something this function goes looking for. Pure: pass ``env``, ``config`` and ``discovered_zim_dir`` in, get values out. """ env = os.environ if env is None else env config = {} if config is None else config file_source = f"config file: {config_path}" if config_path else "config file" def pick(flag, flag_name, env_key, key, default, default_note=None): if flag is not None: return flag, f"flag: {flag_name}" # `in`, not `.get()` truthiness: `ZIM_DIR=` resolves to the empty # string today and must keep doing so. if env_key in env: return env[env_key], f"env: {env_key}" if key in config: return config[key], file_source return default, f"default: {default_note}" if default_note else "default" zim_dir, zim_dir_src = pick( zim_dir_flag, "--zim-dir", "ZIM_DIR", "zim_dir", DEFAULT_ZIM_DIR ) # A portable folder's own `zims`, below every explicit source and above discovery. portable = portable_root(env) portable_zims = portable and os.path.join(portable, PORTABLE_ZIMS_NAME) if ( portable_zims and zim_dir_src.startswith("default") and os.path.isdir(portable_zims) ): zim_dir, zim_dir_src = portable_zims, f"portable: {portable_zims}" # Discovery fills in ONLY what was the hardcoded fallback: `pick` says # "default" exactly when no flag, env or config named a zim_dir. Applied # before the data-dir derivation below so a discovered stick carries its # state (`/.zimi`) with it. if discovered_zim_dir is not None and zim_dir_src.startswith("default"): zim_dir, zim_dir_src = discovered_zim_dir, f"discovered: {discovered_zim_dir}" # The derived `/.zimi` is a *default*, so an explicit data dir from # any layer beats it — that is what keeps `--zim-dir /media/usb` from # dragging state away from a configured ZIMI_DATA_DIR. data_dir, data_dir_src = pick( data_dir_flag, "--data-dir", "ZIMI_DATA_DIR", "data_dir", os.path.join(zim_dir, DEFAULT_DATA_DIR_NAME), f"/{DEFAULT_DATA_DIR_NAME}", ) if portable and data_dir_src.startswith("default"): # Not "default": a stick that cannot be written is an error to read, not a reason to keep # the settings in ~/.cache where they would never travel with it. data_dir, data_dir_src = ( os.path.join(portable, PORTABLE_DATA_NAME), f"portable: {portable}", ) host, host_src = pick(host_flag, "--host", "ZIMI_HOST", "host", DEFAULT_HOST) port, port_src = pick(port_flag, "--port", "ZIMI_PORT", "port", DEFAULT_PORT) if not isinstance(port, int) or isinstance(port, bool): port = _coerce_port(port, port_src) # Annotated rather than inferred: from the literal below a checker deduces # a key type of Literal["zim_dir", ...] and a value type that is the union # of exactly these four tuples, which then rejects both the loop that adds # the environment-backed keys and any caller indexing one of them. The # value is genuinely per-key (port is an int, everything else a string), so # `Any` is the honest element type for a heterogeneous settings map. settings: "collections.OrderedDict[str, tuple[Any, str]]" = collections.OrderedDict( ( ("zim_dir", (zim_dir, zim_dir_src)), ("data_dir", (data_dir, data_dir_src)), ("host", (host, host_src)), ("port", (port, port_src)), ) ) for setting in CONFIG_ENV_SETTINGS: value, source = pick( None, None, setting.env_var, setting.key, setting.default, setting.default_note, ) # Environment values and defaults are already strings; a native JSON # type only survives this far when a caller hand-built `config` instead # of going through load_config_file, so encode defensively — same shape # as the port coercion above. if not isinstance(value, str): value = _encode_env_value(setting, value, source) settings[setting.key] = (value, source) return settings CONFIG_SECRET_MASK = "********" # An empty value gets a visible stand-in so the column never collapses and a # reader can tell "set to empty" from a formatting accident. CONFIG_EMPTY_MASK = '""' def _report_value(key, value): """What `zimi config` shows for one value: never a secret, never blank.""" setting = _CONFIG_ENV_BY_KEY.get(key) shown = str(value) if setting is not None and setting.secret and shown: return CONFIG_SECRET_MASK return shown or CONFIG_EMPTY_MASK def format_config_report(settings): """Render `zimi config` output: value plus where it came from, one per line.""" shown = [(key, _report_value(key, v), src) for key, (v, src) in settings.items()] name_w = max(len(key) for key, _, _ in shown) value_w = max(len(value) for _, value, _ in shown) lines = [] for key, value, source in shown: lines.append(f"{key:<{name_w}} {value:<{value_w}} ({source})") return "\n".join(lines) # Variables apply_env_settings wrote from the config file, name -> file path. CONFIG_PUBLISHED = {} def apply_env_settings(settings): """Publish file-sourced settings into os.environ, and rebind ZIMI_MANAGE. The delivery half of the environment-backed keys. Only values whose provenance is the config file are written: a variable the operator actually exported is never touched (it already won in ``resolve_settings``), and a built-in default is never written at all, so "nobody configured this" stays distinguishable from "configured to the default value" for consumers that care about the difference. Must run before anything reads these settings — ``main()`` calls it right after resolution, ahead of ``_init()`` and ``serve()``. Returns the list of variables written, for tests and for logging. """ global ZIMI_MANAGE published = [] CONFIG_PUBLISHED.clear() for setting in CONFIG_ENV_SETTINGS: value, source = settings[setting.key] if source.startswith("config file"): os.environ[setting.env_var] = value published.append(setting.env_var) # The environment panel shows these rows as the file's, not the # environment's: an admin told "change it where Zimi is started" # would search a launcher that sets nothing. CONFIG_PUBLISHED[setting.env_var] = source.partition(": ")[2] # ZIMI_MANAGE is the one environment-backed setting this module reads into a # global at import time, so publishing alone would be too late for it. The # `== "1"` test is the same one the import-time read uses, which is what # keeps every existing ZIMI_MANAGE spelling behaving exactly as before. ZIMI_MANAGE = settings["manage"][0] == "1" return published def resolve_data_paths( zim_dir_flag=None, data_dir_flag=None, env=None, config=None, discovered_zim_dir=None, ): """Resolve ``(ZIM_DIR, ZIMI_DATA_DIR)`` from flags, environment and config. Precedence is flag > environment > config file > discovered > default, and the default data dir follows whichever ZIM dir won — so ``--zim-dir`` alone moves the state with it, while an explicit ``ZIMI_DATA_DIR`` stays put. Pure so the precedence rules can be tested without touching the process globals. """ settings = resolve_settings( zim_dir_flag=zim_dir_flag, data_dir_flag=data_dir_flag, env=env, config=config, discovered_zim_dir=discovered_zim_dir, ) return settings["zim_dir"][0], settings["data_dir"][0] # --------------------------------------------------------------------------- # Read-only media: automatic data-dir fallback (1.9 portable mode, phase 3) # # A ZIM library on a read-only stick/DVD/locked share used to boot with four # permission errors and silently lose the title index, did-you-mean and Q-ID # links, and rebuild the metadata cache on every start. When the data dir is # the DERIVED default (`/.zimi`) and turns out unwritable, state is # rerouted to a stable per-library directory under the platform user-cache # location instead, so indexes persist across boots of the same library. # # Two deliberate asymmetries: # * An EXPLICITLY configured data dir (--data-dir, ZIMI_DATA_DIR, config # file) that is unwritable is an error, never a fallback — the user asked # for that path, and dying with one clear line beats silently writing # somewhere else. # * If `/.zimi` already EXISTS but is unwritable, its contents are # ignored and the cache dir is used wholesale. Reading stick indexes while # writing new state elsewhere would be a two-layer overlay; the simple # rule is one data dir at a time. # --------------------------------------------------------------------------- class DataDirError(Exception): """An explicitly configured data dir cannot be written. Same contract as ConfigError: an operator mistake reported as one clear line (main() exits 2), never a traceback.""" def _platform_cache_root(): """Per-user cache location, stdlib only (no platformdirs dependency).""" if sys.platform == "darwin": return os.path.expanduser(os.path.join("~", "Library", "Caches", "Zimi")) if os.name == "nt": base = os.environ.get("LOCALAPPDATA") or os.path.expanduser( os.path.join("~", "AppData", "Local") ) return os.path.join(base, "Zimi", "Cache") base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser( os.path.join("~", ".cache") ) # Lowercase on XDG systems, capitalized on macOS/Windows — each platform's # own convention for vendor dirs. return os.path.join(base, "zimi") def fallback_data_dir(zim_dir): """The stable cache-dir stand-in for an unwritable `/.zimi`. Stability is the point: indexes built on the first boot of a read-only library must be found again on the next one, so the name is a pure function of the library's real path — a readable prefix (the folder name, sanitized) plus a hash tail that disambiguates same-named folders on different mounts.""" real = os.path.realpath(zim_dir) tail = hashlib.sha256(real.encode("utf-8", "surrogatepass")).hexdigest()[:10] base = os.path.basename(real.rstrip("/\\")) or "library" prefix = re.sub(r"[^A-Za-z0-9._-]+", "-", base).strip("-.")[:40] or "library" return os.path.join(_platform_cache_root(), f"{prefix}-{tail}") def _dir_is_writable(path): """Probe writability by actually writing: mkdir + tempfile + unlink. Not os.access(): network mounts and read-only remounts routinely report writable modes for directories that reject every write. If the probe had to create the directory, it removes it again on the way out — `zimi config` must be able to ask the question without scattering empty dirs.""" existed = os.path.isdir(path) try: os.makedirs(path, exist_ok=True) fd, probe = tempfile.mkstemp(dir=path, prefix=".zimi-write-probe-") os.close(fd) os.remove(probe) ok = True except OSError: ok = False if not existed: try: os.rmdir(path) # only succeeds when empty, so state is never lost except OSError: pass return ok def _ensure_writable_data_dir(): """Reroute ZIMI_DATA_DIR to the per-library cache dir when the derived default is unwritable. Raises DataDirError for an explicit dir instead. Idempotent and cheap: after a reroute the bound dir IS writable, so a second call (main() runs it early for the CLI exit-code contract, _init() runs it for library/desktop entry points) is a silent no-op — the log line below appears exactly once per boot.""" global ZIMI_DATA_DIR, _data_dir_fallback_from if _dir_is_writable(ZIMI_DATA_DIR): return if not _data_dir_source.startswith("default"): raise DataDirError( f"data dir {ZIMI_DATA_DIR} is not writable ({_data_dir_source}); " "fix its permissions or point --data-dir/ZIMI_DATA_DIR at a " "writable location" ) # A missing ZIM dir means there is no library to keep state for — keep # today's fail-soft boot rather than manufacturing a cache dir for it. if not os.path.isdir(ZIM_DIR): return stale_state = os.path.isdir(ZIMI_DATA_DIR) fallback = fallback_data_dir(ZIM_DIR) if not _dir_is_writable(fallback): log.warning( "Data dir %s is not writable and neither is the cache fallback %s; " "state writes will fail soft", ZIMI_DATA_DIR, fallback, ) return # The one promised log line: where state went, and why. When a read-only # `.zimi` already sits beside the ZIMs it is NOT read live (no two-layer # overlay): the standard cross-directory migration in _migrate_data_files # copies it once into a fresh fallback dir, and after that the cache dir # is the sole data dir. log.warning( "Data dir %s is not writable (read-only media?); keeping state in %s " "instead — it persists there across boots of this library%s", ZIMI_DATA_DIR, fallback, ( "; the read-only state beside the ZIMs stays untouched (seeded " "into the cache dir once, never read live)" if stale_state else "" ), ) _data_dir_fallback_from = ZIMI_DATA_DIR ZIMI_DATA_DIR = fallback ZIM_DIR, ZIMI_DATA_DIR = resolve_data_paths() # Provenance of the bound data dir, kept in lockstep with the binding above and # in apply_data_paths(). "default: …" is the derived `/.zimi`; anything # else marks an explicit choice, which _ensure_writable_data_dir refuses to # override. _data_dir_fallback_from records a reroute for `zimi config`. _data_dir_source = resolve_settings()["data_dir"][1] _data_dir_fallback_from = None ZIMI_MANAGE = os.environ.get("ZIMI_MANAGE", "1") == "1" _initialized = False def apply_data_paths( zim_dir_flag=None, data_dir_flag=None, config=None, discovered_zim_dir=None ): """Rebind the path globals from CLI flags, before anything reads them. Every consumer resolves ``_srv.ZIM_DIR`` / ``_srv.ZIMI_DATA_DIR`` at call time (no module derives a constant from either), so rebinding here is enough — but only if it happens before ``_init()`` creates the data dir and runs migrations. ``main()`` calls this immediately after argparse and before ``load_cache()``. """ global ZIM_DIR, ZIMI_DATA_DIR, _data_dir_source, _data_dir_fallback_from settings = resolve_settings( zim_dir_flag=zim_dir_flag, data_dir_flag=data_dir_flag, config=config, discovered_zim_dir=discovered_zim_dir, ) ZIM_DIR, ZIMI_DATA_DIR = settings["zim_dir"][0], settings["data_dir"][0] # Rebinding invalidates any earlier read-only reroute: the fallback # decision belongs to whichever paths are bound when _init() runs. _data_dir_source = settings["data_dir"][1] _data_dir_fallback_from = None return ZIM_DIR, ZIMI_DATA_DIR def _init(): """Initialize data directory and run migrations. Called lazily on first use.""" global _initialized if _initialized: return _initialized = True # Read-only media check first, so the makedirs below (and every migration # after it) already targets the rerouted dir. Raises DataDirError for an # explicitly configured unwritable dir — main() converts that to exit 2. _ensure_writable_data_dir() try: os.makedirs(ZIMI_DATA_DIR, exist_ok=True) except OSError: pass # ZIM_DIR may not exist yet (e.g. during import in tests) _migrate_data_files() if bundled("library"): # auto-update is downloads; zimi-mcp has none global _auto_update_enabled, _auto_update_freq, _auto_update_skips _auto_update_enabled, _auto_update_freq = _load_auto_update_config() _auto_update_skips = _load_auto_update_skips() if bundled("addons"): # installed add-ons (browser, SingleFile, video) onto PATH / sys.path from zimi import addons addons.activate() def _migrate_data_files(): """Migrate data files from old locations into ZIMI_DATA_DIR.""" # 1. Legacy flat files (v1.3 → v1.4): .zimi_* in ZIM_DIR root migrations = [ (".zimi_password", "password"), (".zimi_collections.json", "collections.json"), (".zimi_cache.json", "cache.json"), ] for old_name, new_name in migrations: old_path = os.path.join(ZIM_DIR, old_name) new_path = os.path.join(ZIMI_DATA_DIR, new_name) if os.path.exists(old_path) and not os.path.exists(new_path): try: os.makedirs(ZIMI_DATA_DIR, exist_ok=True) shutil.copy2(old_path, new_path) os.remove(old_path) log.info("Migrated %s → %s", old_name, new_name) except OSError: pass # 2. Docker /data → /config rename (v1.5 → v1.6) # Users who mounted /data in v1.5 and upgrade to v1.6 (which uses /config) if ( ZIMI_DATA_DIR == "/config" and os.path.isdir("/data") and not os.path.exists("/config/cache.json") ): data_files = [ "cache.json", "collections.json", "history.json", "suggest_cache.json", "auto_update.json", "password", ] migrated_any = False for fname in data_files: old = os.path.join("/data", fname) if os.path.exists(old) and not os.path.exists( os.path.join("/config", fname) ): try: os.makedirs("/config", exist_ok=True) shutil.copy2(old, os.path.join("/config", fname)) migrated_any = True except OSError: pass old_titles = "/data/titles" if os.path.isdir(old_titles) and not os.path.isdir("/config/titles"): try: shutil.copytree(old_titles, "/config/titles") migrated_any = True except OSError: pass if migrated_any: log.info("Migrated config from /data → /config (v1.6 rename)") # 3. Cross-directory migration: ZIM_DIR/.zimi → new ZIMI_DATA_DIR # Triggered when ZIMI_DATA_DIR is set to a different path old_data_dir = os.path.join(ZIM_DIR, ".zimi") if os.path.normpath(ZIMI_DATA_DIR) != os.path.normpath( old_data_dir ) and os.path.isdir(old_data_dir): # Only migrate if new data dir has no cache yet (fresh destination) if not os.path.exists(os.path.join(ZIMI_DATA_DIR, "cache.json")): data_files = [ "cache.json", "collections.json", "history.json", "suggest_cache.json", "auto_update.json", "password", ] for fname in data_files: old = os.path.join(old_data_dir, fname) new = os.path.join(ZIMI_DATA_DIR, fname) if os.path.exists(old) and not os.path.exists(new): try: shutil.copy2(old, new) log.info("Migrated %s → %s", old, new) except OSError: pass # Migrate titles/ directory (title indexes) old_titles = os.path.join(old_data_dir, "titles") new_titles = os.path.join(ZIMI_DATA_DIR, "titles") if os.path.isdir(old_titles) and not os.path.isdir(new_titles): try: shutil.copytree(old_titles, new_titles) log.info("Migrated titles/ → %s", new_titles) except OSError: pass # 4. Stray .torrent companions in ZIM_DIR → ZIMI_DATA_DIR/bt/torrents _migrate_stray_torrent_files() def _migrate_stray_torrent_files(): """Move any ``*.torrent`` companions out of ZIM_DIR into the cache dir. Torrent metadata belongs under ``ZIMI_DATA_DIR/bt/torrents`` — never beside the ZIMs. Older installs (aria2-era, pre-1.8) left ``.zim.torrent`` next to the ZIM; those are bencoded metadata, not ZIMs, so a health scan flags them and zimcheck chokes on one with "Invalid magic number", looking like ZIM corruption (#38). Move them once — non-recursive listdir, never a walk — repoint any torrents-manifest record that referenced the old in-library path, and log a single summary line. Idempotent.""" try: strays = [f for f in os.listdir(ZIM_DIR) if f.endswith(".torrent")] except OSError: return if not strays: return tdir = os.path.join(ZIMI_DATA_DIR, "bt", "torrents") try: os.makedirs(tdir, exist_ok=True) except OSError: return moved = {} # old ZIM_DIR path -> new bt/torrents path for fn in strays: src = os.path.join(ZIM_DIR, fn) dst = os.path.join(tdir, fn) if os.path.exists(dst): # A good copy is already archived — drop the in-library litter. try: os.remove(src) moved[os.path.normpath(src)] = dst except OSError: pass continue try: os.replace(src, dst) # same-filesystem fast path except OSError: try: shutil.copy2(src, dst) os.remove(src) except OSError: continue moved[os.path.normpath(src)] = dst if not moved: return # Repoint any manifest record whose torrent_file pointed into ZIM_DIR. manifest_path = os.path.join(ZIMI_DATA_DIR, "bt", "torrents.json") try: with open(manifest_path, encoding="utf-8") as f: manifest = json.load(f) except (OSError, ValueError): manifest = None if isinstance(manifest, dict): changed = False for entry in manifest.values(): if not isinstance(entry, dict): continue tf = entry.get("torrent_file") if tf and os.path.normpath(tf) in moved: entry["torrent_file"] = moved[os.path.normpath(tf)] changed = True if changed: try: _atomic_write_json(manifest_path, manifest) except OSError: pass log.info( "Moved %d stray .torrent file(s) out of ZIM_DIR into bt/torrents", len(moved) ) # ============================================================================ # Constants & Shared Utilities # ============================================================================ # (Password & Authentication → zimi/manage.py) # (Rate Limiting, Metrics & Usage → zimi/http.py) MAX_CONTENT_LENGTH = ( 8000 # chars returned per article, keeps responses manageable for LLMs ) READ_MAX_LENGTH = 50000 # longer limit for the web UI reader MAX_SEARCH_LIMIT = ( 50 # upper bound for search results per ZIM to prevent resource exhaustion ) MAX_CONTENT_BYTES = ( 10 * 1024 * 1024 ) # 10 MB — skip snippet extraction for entries larger than this MAX_SERVE_BYTES = ( 50 * 1024 * 1024 ) # 50 MB — refuse to serve entries larger than this (prevents OOM) # The most of a streamable entry (video, audio) handed out per request. A # browser's player asks for `bytes=N-`, reads what it needs and aborts, then # asks again a little further on — Chrome did that every 300 KB through a # 114 MB video (2026-09-03), and each answer was a 50 MB copy out of libzim # under the lock. Eight megabytes is a few seconds of 720p, more than a # player reads before its next request, and a sixth of the copying. STREAM_WINDOW_BYTES = 8 * 1024 * 1024 MAX_POST_BODY = 65536 # max bytes accepted in POST requests (64KB — handles ~500 URLs for batch resolve) # Backup bundles and per-user data blobs (bookmarks/history/preferences) are the # one class of POST that legitimately runs large — a full-server backup carries # users, history and every per-user blob. They get their own ceiling so the tight # 64 KB cap keeps guarding every other endpoint. MAX_BACKUP_BODY = 8 * 1024 * 1024 # 8 MB — backup import + /userdata save # Sizes are DECIMAL everywhere Zimi prints one: a kB is 1000 bytes, an MB is # 1000 kB, a GB is 1000 MB. # # It used to divide by 1024 and print "GB", which is a GiB wearing the wrong # name, and the gap is not academic at the sizes this program deals in: # wikipedia_en_all_maxi is 123,980,647,016 bytes, which Zimi called 115 GB # while the NAS, Finder, df and the Kiwix library page all called it 124 GB. # Nine gigabytes of disagreement on one row of a screen whose entire job is # answering "will this fit". # # Everything derives from these three and nothing divides by hand, so there is # one place to be wrong. format_bytes() below turns them into text, and the # browser's fmtBytes() is the same function — tests_size_units holds the two to # a single table of expected strings. _BYTES_PER_KB = 1000 _BYTES_PER_MB = 1000**2 _BYTES_PER_GB = 1000**3 # Where GB stops being written to one decimal. Below ten, a tenth is real # information about a ZIM; above it, "115 GB" beats "115.5 GB" in a list. _GB_WHOLE_FROM = 10 # MB likewise: from a hundred, "285 MB" beats "285.0 MB". _MB_WHOLE_FROM = 100 def format_bytes(n): """One byte count as display text. The single spelling of a size. Matches ``fmtBytes`` in the browser exactly, including the thresholds and the decimal places, so the same file reads the same in the web UI, the CLI, the MCP tool listing and this server's own logs.""" n = max(0, int(n or 0)) if n < _BYTES_PER_KB: return f"{n} B" if n < _BYTES_PER_MB: return f"{n / _BYTES_PER_KB:.1f} KB" if n < _BYTES_PER_GB: mb = n / _BYTES_PER_MB return f"{mb:.0f} MB" if mb >= _MB_WHOLE_FROM else f"{mb:.1f} MB" gb = n / _BYTES_PER_GB return f"{gb:.0f} GB" if gb >= _GB_WHOLE_FROM else f"{gb:.1f} GB" # Windows refuses to replace a file another thread still has open for reading # ("Access is denied", WinError 5), where POSIX just swaps the inode. The # create-jobs journal is read by the route that reports progress and written # by the worker that makes it, and the 1.9.6 release build lost its Windows # leg to exactly that overlap. A reader holds the file for microseconds, so a # short wait is the whole fix; a genuine lock still surfaces as the warning. _REPLACE_RETRY_ATTEMPTS = 20 _REPLACE_RETRY_SLEEP_S = 0.05 def _replace_with_retry(tmp, path): for attempt in range(_REPLACE_RETRY_ATTEMPTS): try: os.replace(tmp, path) return except PermissionError: if attempt == _REPLACE_RETRY_ATTEMPTS - 1: raise time.sleep(_REPLACE_RETRY_SLEEP_S) def _read_umask(): """The process umask, read once at import (before any thread starts: reading it means setting it for a moment).""" mask = os.umask(0o022) os.umask(mask) return mask _PROCESS_UMASK = _read_umask() def _atomic_write_json(path, data, indent=None): """Write JSON data to a file atomically via temp file + os.replace(). Used for all persistent state files to prevent corruption from crashes or concurrent writes. indent=None for compact output. Returns whether the file was written (a failure is logged, never raised). """ # Unique temp name per write: a fixed ".tmp" collides when two # threads write the same target concurrently — the second os.replace races # against the first's rename/unlink and can fail or observe a torn file. directory = os.path.dirname(path) or "." prefix = os.path.basename(path) + "." try: fd, tmp = tempfile.mkstemp(dir=directory, prefix=prefix, suffix=".tmp") # mkstemp creates 0600 and os.replace carries that mode onto the # target — which would silently strip group/world read from state # files (e.g. .zimi_cache.json inspected host-side over SSH). # Give it what an ordinary open() would: 0666 less the umask (0644 # by default, 0640 under the systemd unit's UMask=0027). # POSIX-only: Windows has no fchmod and no meaningful mode bits. if hasattr(os, "fchmod"): os.fchmod(fd, 0o666 & ~_PROCESS_UMASK) except OSError as e: log.warning("Atomic write failed for %s: %s", loggable(path), loggable(e)) return False try: with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump( data, f, ensure_ascii=False, indent=indent, separators=(",", ":") if indent is None else None, ) _replace_with_retry(tmp, path) return True except (OSError, ValueError) as e: # ValueError: text that is not UTF-8 (a lone surrogate) cannot be written. log.warning("Atomic write failed for %s: %s", loggable(path), loggable(e)) try: os.unlink(tmp) except OSError: pass return False def _read_json_file(path, default=None): """The JSON value stored at ``path``, or ``default`` when the file is missing, unreadable or not JSON. Never raises: every persistent state file is rebuildable, so a damaged one reads as a fresh start.""" try: with open(path, encoding="utf-8") as f: return json.load(f) except (OSError, ValueError): return default def _read_json_dict(path): """The JSON object stored at ``path``; {} when it is missing, damaged or holds anything else.""" data = _read_json_file(path) return data if isinstance(data, dict) else {} # MIME type fallback for ZIM entries with empty mimetype MIME_FALLBACK = { ".html": "text/html", ".htm": "text/html", ".css": "text/css", ".js": "application/javascript", ".mjs": "application/javascript", ".json": "application/json", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".svg": "image/svg+xml", ".webp": "image/webp", ".ico": "image/x-icon", ".pdf": "application/pdf", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".eot": "application/vnd.ms-fontobject", ".otf": "font/otf", ".xml": "application/xml", ".txt": "text/plain", ".wasm": "application/wasm", ".bcmap": "application/octet-stream", ".properties": "text/plain", ".ftl": "text/plain", ".mp4": "video/mp4", ".webm": "video/webm", ".ogv": "video/ogg", ".mp3": "audio/mpeg", ".ogg": "audio/ogg", ".wav": "audio/wav", ".opus": "audio/opus", ".flac": "audio/flac", ".vtt": "text/vtt", ".srt": "text/plain", # Map tiles / geodata. OSM map ZIMs (Leaflet / MapLibre) store vector # tiles as .pbf|.mvt; a loader that inspects Content-Type needs protobuf, # not octet-stream. Raster (.png) tiles already covered above. ".pbf": "application/x-protobuf", ".mvt": "application/x-protobuf", ".geojson": "application/geo+json", ".topojson": "application/json", } def split_entry_fragment(path): """Split a ZIM entry path at its first URL fragment ('#'). Single-page docs (notably devdocs ZIMs like devdocs_en_markdown) surface suggestion/title-index paths of the form ``index#backslash`` where the real ZIM entry is ``index`` and ``#backslash`` is an in-page fragment. Callers use this to fall back to the base entry when a lookup for the full string fails. Returns ``(base_path, fragment)`` with the fragment excluding the '#', or ``(path, "")`` when there is no fragment.""" hash_idx = path.find("#") if hash_idx == -1: return path, "" return path[:hash_idx], path[hash_idx + 1 :] def _namespace_fallbacks(path): """Generate alternative paths for old/new namespace ZIM compatibility. Old ZIMs use A/ (articles), I/ (images), C/ (CSS), -/ (metadata) prefixes. New ZIMs dropped them. Try stripping or adding prefixes to find the entry.""" prefixes = ("A/", "I/", "C/", "-/") for p in prefixes: if path.startswith(p): yield path[len(p) :] # strip prefix return for p in prefixes: yield p + path # add prefix def _categorize_zim(name): """Auto-categorize a ZIM by name pattern. Ordered rules, first match wins. None if unknown.""" n = name.lower() # Medical — before Wikimedia so wikipedia_en_medicine categorizes correctly if ( "medicine" in n or n == "wikem" or "ready.gov" in n or ( n.startswith("zimgit-") and any(k in n for k in ("water", "food", "disaster")) ) ): return "Medical" # Stack Exchange — check before Wikimedia (some SEs have wiki-adjacent names) if ( n in ("stackoverflow", "askubuntu", "superuser", "serverfault") or "stackexchange" in n ): return "Stack Exchange" # Dev Docs if n.startswith("devdocs_") or n == "freecodecamp": return "Dev Docs" # Education if ( n.startswith("ted_") or n.startswith("phzh_") or n in ( "crashcourse", "phet", "appropedia", "artofproblemsolving", "edutechwiki", "explainxkcd", "coreeng1", ) ): return "Education" # How-To — before Wikimedia so wikihow doesn't match wiki* if n in ("wikihow", "ifixit") or "off-the-grid" in n or "knots" in n: return "How-To" # Wikimedia — broad wiki* catch-all (wikt* for wiktionary) if n.startswith(("wiki", "wikt")) or n == "openstreetmap-wiki": return "Wikimedia" # Books if n in ("gutenberg", "rationalwiki", "theworldfactbook"): return "Books" # Maps — Kiwix's maps2zim output keeps its maps__ name; # the world map is maps_en_all, whose stem strips all the way to "maps". if n == "maps" or n.startswith("maps_"): return "Maps" return None #: Ceiling on a folder-derived category name, matching the cap a hand-set #: category override may hold (_LAYOUT_STR_MAX) so both paths agree on what the #: UI and the layout file can carry. _FOLDER_CATEGORY_MAX = 128 #: Separators an admin uses in folder names where a space is meant. _FOLDER_SEPARATORS = str.maketrans("-_.", " ") def _zim_folder(path): """The immediate ZIM_DIR subfolder ``path`` lives in, '' for a root file. Pure string work on a path the scan already produced — no stat, no listdir. Anything nested deeper than one level (which the scan never yields) or outside ZIM_DIR resolves to '' rather than guessing at a folder name. """ parent = os.path.dirname(os.path.normpath(path)) root = os.path.normpath(ZIM_DIR) if parent == root or os.path.dirname(parent) != root: return "" return os.path.basename(parent) def _folder_category(folder): """Display category for a raw folder name: 'dev-docs' → 'Dev Docs'. Separators become spaces and lowercase words are capitalized. A word that already carries an uppercase letter is left alone, so 'DIY' and 'McGraw' survive a rule that would otherwise flatten them to 'Diy' and 'Mcgraw'. """ words = folder.translate(_FOLDER_SEPARATORS).split() pretty = " ".join( w if any(c.isupper() for c in w) else w.capitalize() for w in words ) return pretty[:_FOLDER_CATEGORY_MAX] # Scrapers whose output is a MapLibre map rather than pages. Matched as a # prefix of the Scraper metadata ("maps2zim v0.2.1", "streetzim/1.0"). _MAP_SCRAPERS = ("maps2zim", "streetzim", "atlaszim") # Video ZIMs, by the scraper that made them: Kiwix's TED and YouTube builds, # and Zimi's own (Scraper "Zimi x.y + yt-dlp ..."). Not by the _videos:yes # tag, which Wikipedia carries too. _VIDEO_SCRAPERS = ("ted2zim", "youtube2zim") # Q&A sites, by the scraper that made them: Kiwix builds every Stack # Exchange site with sotoki. _QA_SCRAPERS = ("sotoki",) # Subreddits, by the scraper that made them (ArcticZim, which Zimi wraps). _REDDIT_SCRAPERS = ("arcticzim",) # Wikis, by the scraper that made them: Kiwix builds every MediaWiki wiki # (Wikipedia and its sister projects, and wikis beyond Wikimedia) with # mwoffliner. A ZIM too old to carry a Scraper is still known by its Name. _WIKI_SCRAPERS = ("mwoffliner",) WIKI_PROJECTS = ( "wikipedia", "wiktionary", "wikivoyage", "wikiquote", "wikibooks", "wikiversity", "wikinews", "wikisource", "wikispecies", ) # Books, by the scraper that made them: Kiwix builds every Project Gutenberg # ZIM with gutenberg2zim; one too old to carry a Scraper is known by its Name. _BOOK_SCRAPERS = ("gutenberg2zim",) # Apps that read a ZIM beside the one its kind opens it in. A ZIM can feed # two: Wikisource is Zimipedia's and on the Bookshelf too, a nautilus # library's documents are on the shelf and its videos in ZimiTube. Each is # named with the reader that app uses for it (``{"books": "wikisource"}``), # decided once here from metadata the load reads anyway (Scraper, Name, the # Counter of mimetypes, Zimi's creation record), so no app opens a ZIM to # find out whether it is one of its own. _NAUTILUS_SCRAPERS = ("nautiluszim",) _LIBRETEXTS_SCRAPERS = ("mindtouch2zim",) BOOK_WIKI_PROJECTS = ("wikisource", "wikibooks") _DOC_MIMETYPES = ("application/pdf", "application/epub+zip") _MEDIA_MIME_PREFIXES = ("video/", "audio/") # ZIMs that are one book each, by Name: a textbook or a guide captured whole # by zimit, with nothing in its metadata that says "book" (from the 1.12 # coverage audit). Any other ZIM can # be put on the shelf by hand (books.set_whole). WHOLE_BOOK_NAMES = frozenset( ( "jeffe.cs.illinois.edu_en_all", "stacks.math.columbia.edu_en_all", "opendatastructures.org_en_all", "openmusictheory.com_en_all", "htdp.org_en_all", "learningstatisticswithr.com_en_all", "learningstatistics_en_all", "ethanweed_en_all", "mspeekenbrink_en_all", "privacydefence.org_en_opsecbible", "anonymousplanet.org_en_all", ) ) # Bumped when _zim_kind learns a new kind, so a cache record decided under an # older rule ("" for a TED ZIM) is read once more. KIND_VERSION = 6 # The same for _zim_feeds: bumped when it learns a rule, so what a cached # ZIM feeds is decided again, once. A record from before the stamp is 1. FEEDS_VERSION = 1 def _wiki_project(meta_name, name=""): """Which Wikimedia project a wiki ZIM is, by its metadata Name when it has one (a renamed enwiki.zim is still wikipedia_en_all inside), else by its filename; "" for a wiki beyond Wikimedia. The same Name _zim_kind reads, so a ZIM is never a wiki by one rule and misfiled by the other.""" n = (meta_name or name or "").lower() return next((p for p in WIKI_PROJECTS if n.startswith(p)), "") def _read_wiki_project(path, name): """``_wiki_project`` for a cache record written before it was kept: one metadata read. None when the Name could not be read (the file still being copied, say), so nothing is kept and the next boot reads it again; a ZIM with no Name is placed by its filename, for good.""" try: archive = open_archive(path) # libzim raises the same RuntimeError for a missing entry as for a # damaged one: a ZIM without a Name is known by its keys. meta_name = ( bytes(archive.get_metadata("Name")).decode("utf-8", "replace") if "Name" in archive.metadata_keys else "" ) except Exception as e: log.warning("could not read the Name of %s: %s", path, e) return None return _wiki_project(meta_name.strip(), name) def _mimetype_counts(counter): """``{mimetype: n}`` from a ZIM's Counter metadata (``application/pdf=7;image/png=2``); {} when it has none.""" out = {} for part in (counter or "").split(";"): mime, sep, n = part.rpartition("=") if sep and mime.strip(): try: out[mime.strip().lower()] = int(n) except ValueError: continue return out def _created_mode(history): """The mode of the ZIM's creation record in ``X-Zimi-History`` (``folder``, ``site``, ``video``...), "" for a ZIM Zimi did not make.""" from zimi import zimwriter as _zw for record in _zw.parse_history(history or ""): if record.get("op") == "created": return str(record.get("mode") or "") return "" def _zim_feeds(kind, project, scraper, meta_name, counter, history): """The apps beside its kind's that read a ZIM, each with its reader: ``{"books": "nautilus", "tube": "nautilus"}``, {} for most ZIMs.""" s = (scraper or "").lower() mimes = _mimetype_counts(counter) docs = any(mimes.get(m) for m in _DOC_MIMETYPES) media = any(n and m.startswith(_MEDIA_MIME_PREFIXES) for m, n in mimes.items()) feeds = {} if kind == "wiki" and project in BOOK_WIKI_PROJECTS: feeds["books"] = project elif s.startswith(_NAUTILUS_SCRAPERS): # Its documents may be pages only (python-class-vc): a library with # no video or audio is on the shelf whatever its files are. if docs or not media: feeds["books"] = "nautilus" if media: feeds["tube"] = "nautilus" elif s.startswith(_LIBRETEXTS_SCRAPERS): feeds["books"] = "libretexts" elif _created_mode(history) == "folder": if docs: feeds["books"] = "folder" if media: feeds["tube"] = "folder" elif not kind and (meta_name or "").lower() in WHOLE_BOOK_NAMES: feeds["books"] = "whole" return feeds def archive_feeds(archive, kind=None, project=None): """``_zim_feeds`` from an open archive's metadata: a few small reads. ``kind`` and ``project`` are what the library already knows of it, or None to decide them here too (a details build in a child process, which has no library).""" vals = {} for key in ("Scraper", "Tags", "Name", "Counter", "X-Zimi-History"): try: vals[key] = bytes(archive.get_metadata(key)).decode("utf-8", "replace") except Exception: vals[key] = "" scraper, name = vals["Scraper"].strip(), vals["Name"].strip() if kind is None: kind = _zim_kind(scraper, vals["Tags"], name) or "" if project is None: project = _wiki_project(name) if kind == "wiki" else "" return _zim_feeds( kind, project, scraper, name, vals["Counter"], vals["X-Zimi-History"] ) def _read_zim_feeds(path, kind, project): """``_zim_feeds`` for a cache record written before it was kept. None when the ZIM could not be opened, so nothing is kept and the next boot reads it again.""" try: archive = open_archive(path) except Exception as e: log.debug("could not read what apps %s feeds: %s", path, e) return None return archive_feeds(archive, kind, project) def _zim_kind(scraper, tags, meta_name): """What a ZIM is, from its own metadata, for when its filename says nothing. ``"map"`` for a map ZIM, else None. Kiwix ships its maps as maps_en_ but a copy is often renamed (samoa.zim), and StreetZim names its output after the region with no hint at all (osm_osm_-_hawaii). The Scraper and Tags metadata survive a rename; the filename does not. """ s = (scraper or "").lower() if s.startswith(_MAP_SCRAPERS): return "map" if "maps" in {t.strip().lower() for t in (tags or "").split(";")}: return "map" if (meta_name or "").lower().startswith("maps_"): return "map" if s.startswith(_VIDEO_SCRAPERS) or (s.startswith("zimi") and "yt-dlp" in s): return "video" if s.startswith(_QA_SCRAPERS): return "qa" if s.startswith(_REDDIT_SCRAPERS): return "reddit" if s.startswith(_WIKI_SCRAPERS) or (meta_name or "").lower().startswith( WIKI_PROJECTS ): return "wiki" if s.startswith(_BOOK_SCRAPERS) or (meta_name or "").lower().startswith( "gutenberg_" ): return "books" return None # Map ZIMs that carry a place search of their own (a box inside the map with # an index of towns, streets and addresses). Kiwix's maps2zim has no search # box, and its index holds administrative divisions only: a small town is # often not in it, and its name lands on a namesake elsewhere. Zimi's search bar offers to run a # query in the map's own search only where there is one. _MAP_SEARCH_SCRAPERS = ("streetzim", "atlaszim") def _zim_map_search(scraper): return (scraper or "").lower().startswith(_MAP_SEARCH_SCRAPERS) # Where each publisher writes down what ground its map covers, and the shape # it uses. StreetZim: map-config.json, bounds as [W, S, E, N]. Kiwix's # maps2zim: content/config.json, boundingBox as [[W, S], [E, N]]. Both are # the same four numbers; Zimi keeps the first shape. _MAP_CONFIG_PATHS = ( ("map-config.json", "bounds"), ("content/config.json", "boundingBox"), ) _MAP_SOURCE_LABELS = ( ("streetzim", "StreetZim"), ("atlaszim", "AtlasZim"), ("maps2zim", "Kiwix"), ) def _map_source(scraper): """Whose map this is, for a row that lists several: the publisher's name from the Scraper metadata, "" when it is one Zimi has not met.""" s = (scraper or "").lower() for prefix, label in _MAP_SOURCE_LABELS: if s.startswith(prefix): return label return "" # A maps2zim config with no boundingBox is the planet (Kiwix's world map, # maps_en_all, says only its zimName): Web Mercator's own edges. _MAP_PLANET = [-180.0, -85.0511, 180.0, 85.0511] # Bumped when how a map's ground is read changes, so cached records are read again once. MAP_FACTS_VERSION = 2 def _map_bounds(archive, scraper=""): """``[W, S, E, N]`` for a map ZIM, from its own config entry; the planet for a maps2zim config that names no box; None when it has none Zimi knows, or the numbers do not make a box.""" for path, key in _MAP_CONFIG_PATHS: try: entry = archive.get_entry_by_path(path) if entry.is_redirect: entry = entry.get_redirect_entry() raw = json.loads(bytes(entry.get_item().content).decode("utf-8", "replace")) except Exception: continue box = raw.get(key) if isinstance(raw, dict) else None if ( box is None and isinstance(raw, dict) and path == "content/config.json" and (scraper or "").lower().startswith("maps2zim") ): return list(_MAP_PLANET) try: if ( isinstance(box, list) and len(box) == 2 and all(isinstance(c, list) for c in box) ): box = [box[0][0], box[0][1], box[1][0], box[1][1]] w, so, e, n = (float(v) for v in box) except (TypeError, ValueError): continue if not (-180 <= w <= 180 and -180 <= e <= 180 and -90 <= so <= n <= 90): continue return [w, so, e, n] return None def _map_facts(archive, scraper): """The two facts about a map beyond its kind, read once and cached with the rest: who published it and what ground it covers.""" return { "map_source": _map_source(scraper), "map_bounds": _map_bounds(archive, scraper), } def _reddit_facts(archive): """The subreddits a Reddit ZIM carries, read once from its own index and cached with its kind, so the Reddot tile can name them (the ZIM's own title is "ArcticZim", which names the tool, not the content).""" from zimi import reddot for path in reddot.SUBREDDITS_PATHS: try: entry = archive.get_entry_by_path(path) if entry.is_redirect: entry = entry.get_redirect_entry() subs = reddot.subreddits_from_page( bytes(entry.get_item().content).decode("utf-8", "replace") ) if subs: return {"subreddits": subs} except Exception: continue return {"subreddits": []} # Every ArcticZim ZIM is titled after the tool. A ZIM named for what it # holds is what a library lists, so a Reddit ZIM with no title of its own # is named by its subreddits. _TOOL_TITLES = ("arcticzim", "") def _subreddit_title(title, subreddits): if str(title or "").strip().lower() in _TOOL_TITLES and subreddits: return " · ".join("r/" + s for s in subreddits[:3]) + ( " …" if len(subreddits) > 3 else "" ) return title def _read_reddit_facts(path): try: return _reddit_facts(open_archive(path)) except Exception as e: log.debug("could not read subreddits of %s: %s", path, e) return {"subreddits": []} def _read_map_facts(path): """``_map_facts`` for a cache record written before they were kept.""" try: archive = open_archive(path) try: scraper = bytes(archive.get_metadata("Scraper")).decode("utf-8", "replace") except Exception: scraper = "" return _map_facts(archive, scraper) except Exception as e: log.debug("could not read map facts for %s: %s", path, e) return {"map_source": "", "map_bounds": None} APPS_ENV = "ZIMI_APPS" # The Field Guide and Help now are out of the shipped release until they come # back as "How to (anything)". The code stays in # the tree; this switch (default off) is the one thing that reaches it. FIELDGUIDE_ENV = "ZIMI_FIELDGUIDE" def fieldguide_enabled(): """Whether the Field Guide, Help now and their search card are offered. Read on every call, so a server and its tests agree on what is on.""" return os.environ.get(FIELDGUIDE_ENV, "").strip().lower() in ( "1", "true", "yes", "on", ) APP_NAMES = ( "maps", "tube", "exchange", "reddot", "wiki", "books", "dictionary", "games", "almanac", ) # Apps offered only when named: a comma list in ZIMI_APPS (or a saved list) # that names one turns it on; "1", "all", the default and a saved True leave # it off. None now: Reddot was one from 1.13.1 to 1.14.0, and home shows an # app only when a ZIM gives it something to show. APPS_OPT_IN = frozenset() APPS_ALL = frozenset(APP_NAMES) APPS_DEFAULT = APPS_ALL - APPS_OPT_IN _APPS_OFF = ("0", "false", "no", "off", "none") _APPS_ON = ("1", "true", "yes", "on", "all") def _apps_value(raw, every=APPS_DEFAULT): """A setting (True/False, a list of app names, or a string of ``0``/``1`` or a comma list) as the set of apps shown; None when it says nothing. ``every`` is what "all" means: for the server, every app but the opt-in ones; for an account's own filter, everything the server offers.""" if raw is None: return None if isinstance(raw, bool): return every if raw else frozenset() if isinstance(raw, str): text = raw.strip().lower() if not text: return None if text in _APPS_OFF: return frozenset() if text in _APPS_ON: return every raw = text.split(",") if isinstance(raw, (list, tuple, set, frozenset)): return frozenset( n for n in (str(x).strip().lower() for x in raw) if n in APP_NAMES ) return every if raw else frozenset() def _apps_setting(shown, every=APPS_DEFAULT): """The set as it is saved: True for "all" (``every``), False for none, else the names (so a list naming an opt-in app keeps it).""" if shown == every: return True if not shown: return False return [n for n in APP_NAMES if n in shown] def apps_stamp(shown): """What the shell carries in ``data-zimi-apps``: nothing when the default apps are offered (every app but the opt-in ones), ``0`` for none, else the names offered.""" shown = _apps_value(shown) if shown is None or shown == APPS_DEFAULT: return None return ",".join(n for n in APP_NAMES if n in shown) or "0" def _apps_env(): """The env var's verdict, or None when it is unset or unreadable.""" return _apps_value(os.environ.get(APPS_ENV)) def url_quote(name): """A ZIM name as it appears in a /w/ path.""" import urllib.parse return urllib.parse.quote(name, safe="") def _zim_kind_of(name): """The cached kind of an installed ZIM (map, video, qa, reddit, wiki, books) or "".""" for z in _zim_list_cache or []: if z.get("name") == name: return z.get("kind") or "" return "" def apps_shown(): """The apps (Maps, ZimiTube, ZimiExchange, Reddot, Zimipedia, Bookshelf) offered on this server: ``ZIMI_APPS`` when set (``0``, ``1`` or a comma list of names), else the setting saved from Server settings, else all of them but the opt-in ones (``APPS_OPT_IN``). A signed-in user can also hide any of them for themselves (their account's preferences). Never per browser (Eric: "Not per browser only per user or server").""" verdict = _apps_env() if verdict is not None: return verdict from zimi import manage saved = _apps_value(manage._read_app_update_prefs().get("apps")) return APPS_DEFAULT if saved is None else saved def apps_enabled(): """Whether any app is offered on this server.""" return bool(apps_shown()) def user_apps_shown(setting): """What an account's saved preference leaves of the server's offer.""" mine = _apps_value(setting, APPS_ALL) shown = apps_shown() return shown if mine is None else shown & mine def set_apps_enabled(value): """Save the server-wide switch. ``(enabled, error)``; ``env_locked`` when the env var has the last word.""" if _apps_env() is not None: return None, "env_locked" from zimi import manage shown = _apps_value(value) or frozenset() manage._write_app_update_prefs(apps=_apps_setting(shown)) return bool(shown), None def set_own_zim_removed(name, gone): """Remove one of Zimi's own ZIMs from this server (or add it back), the live library following at once: no rescan of the others, no download. Open windows hear it as the library changing (_set_listing). False for a name that is not one of them.""" from zimi import ownzims if not ownzims.set_removed(name, gone): return False own = next(o for o in ownzims.OWN if o.name == name) path = ownzims.zim_path(own) done = False try: if gone: done = bool(path) and unregister_zim_file(os.path.basename(path)) elif path: register_zim_file(path) # Done only if the package's file now holds the name: a same-name copy in the library can outrank it (the scan's rules decide) done = (_zim_files_cache or {}).get(name) == path except Exception as e: log.warning( "Incremental change of %s failed (%s), rescanning the library", str(name).replace("\r", "").replace("\n", ""), e, ) if not done: with _zim_lock: load_cache(force=True) _search_cache_clear() _suggest_cache_clear() return True def build_rank(entry): """What makes one build of a thing newer than another: its date, then its size (a maxi over a nopic of the same month).""" return (str(entry.get("date") or ""), int(entry.get("size_bytes") or 0)) def newest_per(entries, key): """One entry per identity, the newest build: an update whose old file is still around, a nopic beside a maxi, two names for one thing. Eric, 2026-09-19: "handle deduplication if we're merging multiple Zims." The order of first appearance is kept; an entry whose key is falsy stays.""" best, order, out = {}, [], [] for e in entries: k = key(e) if not k: out.append(e) continue cur = best.get(k) if cur is None: best[k] = e order.append(k) elif build_rank(e) > build_rank(cur): best[k] = e return [best[k] for k in order] + out def _is_map_zim(name): """Whether the registered ZIM ``name`` is a map, from the list cache.""" return any( z.get("name") == name and z.get("kind") == "map" for z in (_zim_list_cache or []) ) def _read_has_icon(path): """Whether the book at ``path`` carries any illustration, for a cache record written when only a 48x48 counted. One metadata listing.""" try: return any(k.startswith(ILLUSTRATION_PREFIX) for k in open_archive(path).metadata_keys) except Exception as e: log.debug("could not read illustrations for %s: %s", path, e) return False def _read_zim_kind(path): """``_zim_kind`` for a cache record written before ``kind`` existed. Three metadata reads and no entry walk, so it is cheap enough to do at boot, once per legacy record; the answer is then written down with the rest. Returns ``(kind, map_search)``, "" rather than None for the kind so a decided non-map is a decision too.""" try: archive = open_archive(path) vals = {} for key in ("Scraper", "Tags", "Name"): try: vals[key] = bytes(archive.get_metadata(key)).decode("utf-8", "replace") except Exception: vals[key] = "" kind = _zim_kind(vals["Scraper"], vals["Tags"], vals["Name"]) or "" return kind, bool(kind and _zim_map_search(vals["Scraper"])) except Exception as e: log.debug("could not read kind for %s: %s", path, e) return "", False def _effective_category(name, path, kind=None): """A ZIM's category: its subfolder if it lives in one, else the heuristic. Folder beats heuristic because the folder is an act of organization by the operator — filing a ZIM under medical/ says more than any guess made from its filename. A hand-set per-ZIM override still beats both; that is applied at the /list boundary, not baked in here. Between folder and filename sits what the ZIM says it is (``kind``, from its metadata): a map is a map whatever the file was renamed to. """ from zimi import ownzims return ( _folder_category(_zim_folder(path)) or ownzims.category_of(path) or ("Maps" if kind == "map" else "Reddit" if kind == "reddit" else None) or _categorize_zim(name) ) # ============================================================================ # History, Favorites & Collections # ============================================================================ _history_lock = threading.Lock() _HISTORY_MAX = 500 def _history_file_path(): return os.path.join(ZIMI_DATA_DIR, "history.json") def _load_history(): """Load event history from disk. Returns list of event dicts, newest first.""" try: with open(_history_file_path(), encoding="utf-8") as f: data = json.load(f) if isinstance(data, list): return data except FileNotFoundError: pass # fresh install — no history yet except (OSError, json.JSONDecodeError) as e: # Unreadable/corrupt (e.g. a bind mount owned by the wrong uid raising # PermissionError/EIO) must degrade to empty, not 500 the request and # look like data loss. Log so the real problem stays visible. log.warning("Could not read history file, returning empty: %s", e) return [] def _save_history(entries): """Replace the persistent event history with ``entries`` (capped, newest first). Used by the full-server backup restore. Thread-safe.""" with _history_lock: clean = [e for e in entries if isinstance(e, dict)][:_HISTORY_MAX] _atomic_write_json(_history_file_path(), clean) def _append_history(event): """Append an event dict to persistent history. Thread-safe.""" with _history_lock: entries = _load_history() entries.insert(0, event) if len(entries) > _HISTORY_MAX: entries = entries[:_HISTORY_MAX] # Write outside lock — I/O can be slow on NAS spinning disks _atomic_write_json(_history_file_path(), entries) _collections_lock = threading.Lock() def _collections_file_path(): """Path to the collections/favorites JSON file.""" return os.path.join(ZIMI_DATA_DIR, "collections.json") def _load_collections(): """Load collections from disk. Returns default structure if missing.""" try: with open(_collections_file_path(), encoding="utf-8") as f: data = json.load(f) if data.get("version") != 1: return {"version": 1, "favorites": [], "collections": {}} return data except FileNotFoundError: pass # fresh install — no collections yet except (OSError, json.JSONDecodeError, KeyError) as e: # Unreadable/corrupt data dir must degrade to the empty default rather # than 500 /collections and blank the user's bookmarks (issue #36). log.warning("Could not read collections file, returning default: %s", e) return {"version": 1, "favorites": [], "collections": {}} def _save_collections(data): """Save collections to disk (atomic write via rename).""" data["version"] = 1 _atomic_write_json(_collections_file_path(), data, indent=2) # ── Library layout: per-ZIM category overrides + home section order (#37) ── # # Storage: ZIMI_DATA_DIR/library_layout.json — # {"overrides": {"": ""}, # "section_order": ["cat:"|"col:"|"other", ...], # "sections": ["", ...]} # Overrides win over the _categorize_zim heuristic; section_order drives the # home page ordering (unlisted sections append in default order); `sections` # holds user-declared empty categories that should be offered as Move-to targets # and reorder rows before any ZIM lives in them. Reads are public (ride /list); # writes are auth-gated /manage endpoints. _library_layout_lock = threading.Lock() #: Section-order keys are namespaced so categories and collections can share one #: ordered list without colliding (a collection named "Books" != category Books). #: The bare `other` key is the reserved slot for the uncategorized catch-all, so #: it can be ordered like any real section instead of being pinned last. _SECTION_KEY_RE = re.compile(r"^(?:(?:cat:|col:).+|other)$") #: Defensive caps so a hostile/buggy client can't write an unbounded file. _LAYOUT_MAX_OVERRIDES = 5000 _LAYOUT_MAX_ORDER = 500 _LAYOUT_MAX_SECTIONS = 200 _LAYOUT_STR_MAX = 128 def _library_layout_file_path(): """Path to the library-layout JSON file.""" return os.path.join(ZIMI_DATA_DIR, "library_layout.json") def _load_library_layout(): """Load library layout from disk. Fail-soft to the empty default. A missing or corrupt file must degrade to the empty default (``{"overrides": {}, "section_order": [], "sections": []}``) rather than 500 /list — the whole home page renders from this, so a bad read can never be allowed to blank the library. """ empty = {"overrides": {}, "section_order": [], "sections": []} try: with open(_library_layout_file_path(), encoding="utf-8") as f: data = json.load(f) if not isinstance(data, dict): return empty overrides = data.get("overrides") order = data.get("section_order") sections = data.get("sections") return { "overrides": overrides if isinstance(overrides, dict) else {}, "section_order": order if isinstance(order, list) else [], "sections": sections if isinstance(sections, list) else [], } except FileNotFoundError: pass # fresh install — no layout yet except (OSError, json.JSONDecodeError) as e: log.warning("Could not read library layout, returning default: %s", e) return empty def _save_library_layout(data): """Save library layout to disk (atomic write via rename).""" _atomic_write_json(_library_layout_file_path(), data, indent=2) # ISO 639-3 (what ZIM metadata carries) to ISO 639-1, where a language has # one. The one table the server and the web client read: the client gets it # put into app.js as it is served (http._inline_lang_codes), so the # library's lang: and the catalog's agree on every language. LANG_CODES_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "assets", "lang-codes.json" ) with open(LANG_CODES_PATH, encoding="utf-8") as _f: _ISO639_3_TO_1 = json.load(_f) # ============================================================================ # ZIM Loading & Title Index # ============================================================================ # Opening ZIM archives is expensive (~0.3s each on NAS spinning disks). # Persistent cache in .zimi_cache.json enables instant startup on subsequent runs. # Archives are opened lazily (on first search/read) instead of all at once. _CACHE_VERSION = 2 # bumped for language metadata # Self-heal thresholds for the "whole library badged New" bug: a full cache # rebuild once stamped first_seen=now for every ZIM at once. first_seen values # within this window are treated as "the same instant" (a rebuild), and a stamp # is only trusted if it lands within the mtime tolerance of the file itself. # A full rebuild stamps entries across the whole scan, which takes ~13s per 66 # ZIMs on NAS spinning disks — the bucket must swallow an entire slow scan or # the majority test splits across buckets and the heal never fires. Safe to be # generous: the per-entry mtime tolerance below is the guard that protects # genuine batch downloads, the bucket is only a pre-filter. _MASS_STAMP_WINDOW = 120.0 # seconds _MASS_STAMP_MTIME_TOL = 3600.0 # first_seen must be within 1h of file mtime to be real _zim_list_cache = None _auto_update_skips = ( frozenset() ) # ZIMs the auto-updater leaves alone; library.py owns the file _zim_files_cache = None # {name: path} — cached at startup, ZIM dir is read-only _listing_seen = None # what _set_listing last saw in the listing def mark_auto_update_skips(listing): """`auto_update: False` on the entries the auto-updater leaves alone, so the card menu can say so without a request of its own.""" for z in listing or []: if z.get("name") in _auto_update_skips: z["auto_update"] = False else: z.pop("auto_update", None) def _set_listing(listing): """The library's listing, replaced. When what it holds changed (a ZIM added, removed or replaced), every open window is told (changes.py "library") and draws the library again, without a reload; a rescan that found the same files tells nobody. Call under _zim_lock, or at load.""" global _zim_list_cache, _listing_seen mark_auto_update_skips(listing) _zim_list_cache = listing seen = frozenset( (z.get("name"), z.get("file"), z.get("size_bytes"), z.get("entries")) for z in listing or [] ) if seen != _listing_seen: told = _listing_seen is not None # the first listing is no change _listing_seen = seen if told: _changes.announce("library", None) if bundled("gamelinks"): # zimi-mcp ships no games from zimi import gamelinks gamelinks.refresh_async() # the games' encyclopedia links follow the library, off the request path # ── Per-request ZIM allow context (multi-user v1) ──────────────────────────── # When a named USER (not admin, not anonymous) is logged in, the request's ZIM # Connections the kernel holds while every handler thread is busy starting (the stdlib's is 5). LISTEN_BACKLOG = 128 class ZimiHTTPServer(ThreadingHTTPServer): """ThreadingHTTPServer that does not ask DNS who it is. The stdlib's ``server_bind`` calls ``socket.getfqdn(host)`` purely to fill in ``server_name``, which only CGI ever reads. That is a reverse lookup, and on a machine whose resolver has no answer it blocks for the full resolver timeout before the socket is usable. Zimi is offline-first: an air-gapped box, a boat, a bunker, a laptop on a captive-portal network is the normal case, not the edge. A start that hangs half a minute there looks like a hung app. Found when the 1.9.0 desktop build failed on all four runners: the server printed its whole startup banner and then took longer than thirty seconds to emit READY, on machines with no reverse DNS. Nothing in Zimi reads ``server_name``; the address is what it binds to. It also listens with a real backlog. The stdlib's is 5: a page that opens more connections than that at once (a fast machine, several tabs, the service worker's prefetch) had the rest reset by the kernel before Zimi saw them. Found on a many-core Mac, where 16 parallel requests failed every run (tests/test_best_answer_live.py).""" request_queue_size = LISTEN_BACKLOG def server_bind(self): socketserver.TCPServer.server_bind(self) host, port = self.server_address[:2] self.server_name = str(host) self.server_port = port # view is restricted to their allowlist. ThreadingHTTPServer runs one thread per # request, so a thread-local is naturally request-scoped; http.do_GET/do_POST set # it from zimi.users.request_allow() and clear it in a finally. A value of None # means all-access (admin/anonymous/all-access user) — the common case, and what # background threads (indexing, downloads) always see since they never set it. # get_zim_files() and list_zims() consult it so every dict-based read path # (search_all, read_article, chunk_article, resolve_almanac_qids, /list) is # filtered from one place; zim_allowed() covers the two spots that bypass them. _request_ctx = threading.local() def set_request_allow(allow): """Set the current request's ZIM allow set (a set of names) or None for all.""" _request_ctx.allow = allow def clear_request_allow(): """Clear the request allow context (always call in a finally).""" _request_ctx.allow = None def current_allow(): """The current request's allow set, or None for all-access.""" return getattr(_request_ctx, "allow", None) def zim_allowed(name): """True if `name` is visible to the current request. Gates the paths that don't flow through get_zim_files() (pooled /w/ content, direct list reads).""" allow = current_allow() return allow is None or name in allow _cache_generation = 0 # incremented on load_cache(force=True) — used in ETags _archive_pool = {} # {name: Archive} — kept open for fast search _archive_lock = threading.Lock() # protects _archive_pool writes in threaded mode _zim_lock = ( threading.Lock() ) # serializes all libzim operations (C library is NOT thread-safe) # Lock ordering: _zim_lock → _archive_lock (never acquire _zim_lock while holding _archive_lock) # Separate archive handles for suggestion search — allows title lookups to run in # parallel with Xapian FTS by using independent C++ Archive objects + their own lock. # Each ZIM gets its own lock so multi-ZIM scoped searches can query in parallel. _suggest_pool = {} # {name: Archive} — independent handles for SuggestionSearcher _suggest_pool_lock = threading.Lock() # protects _suggest_pool writes _suggest_zim_locks = {} # {name: Lock} — per-ZIM lock for suggestion operations # Separate archive handles for full-text search — allows parallel Xapian FTS across ZIMs. # Same pattern as _suggest_pool: each ZIM gets its own Archive + Lock. _fts_pool = {} # {name: Archive} _fts_pool_lock = threading.Lock() _fts_zim_locks = {} # {name: Lock} # Asset extensions to skip when indexing — images, fonts, scripts, not articles _ASSET_EXTS = frozenset( ( ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico", ".avif", ".css", ".js", ".json", ".woff", ".woff2", ".ttf", ".eot", ".otf", ".mp3", ".mp4", ".ogg", ".wav", ".webm", ) ) # ============================================================================ # Wikidata Q-ID Matching — see zimi/interlang.py # (Q-ID code extracted to interlang.py) # (UI Templates extracted to zimi/http.py) # ============================================================================ # ZIM File Discovery # ============================================================================ def _zim_base_name(filename): """Derive the short name a ZIM filename gets on its own. Pure: the filename alone decides. _zim_short_name is the served name, which differs only for a file _scan_zim_files gave a language name. English ZIMs strip the language code (backward-compatible): stackoverflow.com_en_all_2023-11.zim → stackoverflow wikipedia_en_all_maxi_2026-02.zim → wikipedia Non-English ZIMs preserve the language suffix: wikipedia_fr_all_maxi_2026-02.zim → wikipedia_fr stackoverflow.com_es_all_2024-01.zim → stackoverflow_es """ name = filename.split(".zim")[0] # The Almanac's HD flavour is the tile library, not a build of the Almanac the package serves: its own name. if re.match(r"zimi_almanac_maxi_\d{4}-\d{2}[a-z]?$", name): return "zimi_almanac_maxi" # Extract language code before stripping (e.g. _fr_, _de_, _es_) lang_match = re.search(r"(?:\.com)?_([a-z]{2,3})_(?:all|maxi|2\d{3})", name) lang_code = lang_match.group(1) if lang_match else "" is_english = lang_code in ("en", "eng", "") # Strip domain suffixes name = re.sub(r"\.com_[a-z]{2,3}_all.*", "", name) name = re.sub(r"\.stackexchange\.com_[a-z]{2,3}_all.*", "", name) # Strip language + flavor + date patterns # Only strip _XX_ or _XXX_ when followed by all/maxi/nopic/mini/date (not arbitrary words like css/git) name = re.sub(r"_[a-z]{2,3}_all_maxi.*", "", name) name = re.sub(r"_[a-z]{2,3}_all.*", "", name) name = re.sub(r"_[a-z]{2,3}_(?:maxi|nopic|mini).*", "", name) name = re.sub( r"_[a-z]{2}_2\d{3}.*", "", name ) # Only 2-letter codes before dates (avoids css/git) name = re.sub(r"_maxi_2\d{3}.*", "", name) name = re.sub(r"_2\d{3}-\d{2}[a-z]?$", "", name) # A topic build's flavor, whichever it is: maxi was stripped above and # nopic/mini were not, so wikipedia_en_medicine_maxi and _nopic became two # sources with two names and both were served. One name, and the scan's # collision rule (_FLAVOR_RANK) keeps the richer file. name = re.sub(r"_(?:maxi|nopic|mini)$", "", name) # StreetZim: osm-hawaii-2026-09-08 -> osm-hawaii, so the name survives an # update and the catalog's toggle can tell installed from not. name = re.sub(r"^(osm-.+?)-2\d{3}-\d{2}-\d{2}$", r"\1", name) # Append language suffix for non-English ZIMs if not is_english and lang_code: # Normalize 3-letter to 2-letter short_lang = _ISO639_3_TO_1.get( lang_code, lang_code if len(lang_code) == 2 else "" ) if short_lang and short_lang != "en": name = name + "_" + short_lang return name _LANG_SEGMENT_RE = re.compile(r"[a-z]{2,3}") def _zim_lang_key(filename): """The language a ZIM filename declares in Kiwix's language position (project_LANG_selection_flavor_date), as ISO 639-1 where one exists: gutenberg_ale_all -> 'ale', wikipedia_eng_all -> 'en'. A file without a two- or three-letter segment there counts as English, the language _zim_base_name leaves out of a name. Only the collision rule reads this. _zim_base_name keeps its own, older reading (it takes 'top' or 'css' after the language for one, and drops a code the table lacks), because changing that would rename ZIMs people have saved things under.""" parts = os.path.basename(filename).split(".zim")[0].split("_") code = parts[1] if len(parts) > 1 else "" if not _LANG_SEGMENT_RE.fullmatch(code): return "en" return _ISO639_3_TO_1.get(code, code) def _zim_lang_name(filename): """The name a ZIM takes when another language's build holds its base name: gutenberg_ale_all_2025-09.zim -> gutenberg_ale.""" return _zim_base_name(filename) + "_" + _zim_lang_key(filename) def _zim_short_name(filename): """The short name `filename` is served under: its base name, or its language name when the library holds the base name for another language's build (gutenberg_ale beside gutenberg_en). A file the library does not hold gets its base name, so for anything not installed this is _zim_base_name.""" filename = zimparts.book_filename(filename) name = _zim_base_name(filename) files = _zim_files_cache held = files.get(name) if files else None if held and zimparts.book_filename(held) != filename: lang_name = _zim_lang_name(filename) if zimparts.book_filename(files.get(lang_name) or "") == filename: return lang_name return name # Subdirectories the one-level scan must never treat as library content. # Learned from the first real deployment, not invented: Eric's NAS carries a # corrupt-quarantine/ full of ZIMs the kiwix-zim updater script deliberately # pulled OUT of service after failed integrity checks, and Synology mints # @eaDir metadata trees beside everything it touches. Serving quarantined # files back to readers is the exact opposite of what a quarantine means. _SCAN_SKIP_DIRS = { "@eadir", # Synology metadata "lost+found", # fsck droppings "system volume information", # Windows-formatted sticks "corrupt-quarantine", # kiwix-zim's convention for failed integrity checks "quarantine", } _SCAN_IGNORE_MARKER = ".nozim" # drop this file in any subfolder to opt it out _FLAVOR_TOKEN_RE = re.compile(r"_(maxi|nopic|mini)(?:_|\.zim$)") _DATE_TOKEN_RE = re.compile(r"(\d{4}-\d{2}[a-z]?)\.zim$") # Kiwix flavors are strictly nested — maxi carries everything, nopic is full # text without media, mini is intros only — so richer beats newer: an old # maxi still contains more than this month's mini. An untagged filename is # a full build and slots between maxi and nopic. _FLAVOR_RANKS = {"maxi": 4, None: 3, "nopic": 2, "mini": 1} def _zim_build_rank(filename): """Rank a build for same-name collisions in the same directory tier: flavor richness first, then English over another language, then the trailing date token (newer wins). The English step only ever separates two languages, since builds of one language all agree on it. It keeps the bare name with English, the language Kiwix names leave out: with dates deciding, gutenberg_ale's next edition would take 'gutenberg' from the English library, and everything saved under that name with it.""" fname = filename.lower() m = _FLAVOR_TOKEN_RE.search(fname) d = _DATE_TOKEN_RE.search(fname) return ( _FLAVOR_RANKS[m.group(1) if m else None], _zim_lang_key(fname) == "en", d.group(1) if d else "", ) def _zim_pick(cands): """The build that holds a name among same-name candidates, (tier, path) in scan order: the root tier first, then the richest by _zim_build_rank; a tie keeps the earlier file.""" top = min(tier for tier, _path in cands) return max( (path for tier, path in cands if tier == top), key=lambda path: _zim_build_rank(zimparts.book_filename(path)), ) def _own_copy_first(name, cands): """Zimi's own ZIM (the package's file, tier 3) against a same-name copy someone put in their library, e.g. zimi_games_2026-10.zim from a release page. Only the package's file counts as Zimi's own; the copy is an ordinary ZIM. The package's file serves the name unless the copy is a strictly newer edition (the package's pages, links and strings go with its own build, so an equal or older copy never stands in for it). The loser is shadowed like any other collision, and can be deleted once the package's file is removed from the library. Edits ``cands`` in place.""" from zimi import ownzims own = [i for i, (_tier, path) in enumerate(cands) if ownzims.is_own_path(path)] if not own or len(own) == len(cands): return def date(path): m = _DATE_TOKEN_RE.search(os.path.basename(path).lower()) return m.group(1) if m else "" newest_copy = max(date(p) for i, (_t, p) in enumerate(cands) if i not in own) for i in own: if date(cands[i][1]) >= newest_copy: cands[i] = (-1, cands[i][1]) def _scan_zim_files(): """Scan ZIM_DIR plus exactly one level of subdirectories for ZIM files. Returns {short_name: path} mapping. A split book (name.zimaa, name.zimab...) is one entry at its .zimaa path, named as name.zim would be (zimparts). Subfolder eligibility: dotted names are never scanned (glob semantics, so `.zimi` stays state, not content), the deny list above is skipped, and a subfolder containing a `.nozim` marker file is skipped — that is the documented way to keep a staging or archive folder beside the library. Collision rule (documented, deliberate): a ROOT-level file always beats a subfolder file with the same short name. The root of the library is where downloads land and where the operator curates; a same-name copy in a subfolder is a backup, an old edition, or a quarantined reject, and none of those should ever displace the file being served. The original larger-file-wins rule was retired after one real library: it would have preferred a quarantined corrupt copy over the healthy root file had their sizes leaned that way. Within the SAME tier (both root, or both in subfolders), the richer build wins — flavor first, then newer date, per _zim_build_rank — so a maxi is never shadowed by the mini beside it and two editions of the same flavor resolve to the newer one. Every collision is logged. A different language is not a lesser build of the same thing. Kiwix names drop English, and _zim_base_name drops any code the language table lacks, so gutenberg_ale_all and gutenberg_en_all both come out 'gutenberg'. The build that wins keeps that name, exactly as before; each other language's best build is served under its language name (gutenberg_ale) instead of vanishing. A language name some file already has as its own is never taken, so no ZIM with a name loses it. """ root_paths = zimparts.in_folder(ZIM_DIR) sub_paths = [] for sub in sorted(glob.glob(os.path.join(ZIM_DIR, "*", ""))): base = os.path.basename(sub.rstrip(os.sep)) if base.lower() in _SCAN_SKIP_DIRS: continue if os.path.exists(os.path.join(sub, _SCAN_IGNORE_MARKER)): log.info("Skipping %s (has %s marker)", base, _SCAN_IGNORE_MARKER) continue sub_paths.extend(zimparts.in_folder(sub)) # Folders another program owns (libfolders) are the last tier: read where # they are, and never shadowing a ZIM of Zimi's own. from zimi import libfolders libfolders.refresh() # Zimi's own ZIMs (ZimiGames, the Almanac) come last: committed in the # package, and never shadowing a file the operator put in the library. from zimi import ownzims groups = {} # base name -> [(tier, path)], in scan order for tier, paths in ( (0, root_paths), (1, sub_paths), (2, libfolders.zim_paths()), (3, ownzims.zim_paths()), ): for path in paths: name = _zim_base_name(zimparts.book_filename(path)) groups.setdefault(name, []).append((tier, path)) for name, cands in groups.items(): _own_copy_first(name, cands) zims = {name: _zim_pick(cands) for name, cands in groups.items()} for name, cands in groups.items(): if len(cands) > 1: _split_languages(name, cands, zims, groups) own_wins = _fold_own_copies(zims) served = set(zims.values()) _set_older_copies(groups, served, own_wins) libfolders.set_shadowed( { path: zims[name] for name, cands in groups.items() for tier, path in cands if tier == 2 and path not in served } ) return zims def _fold_own_copies(zims): """One Almanac, one Games: a ZIM whose Name metadata is an own ZIM's (a copy of it under another file name, such as zimi_eng_zimi_almanac_2026-11.zim beside the package's zimi_almanac) is that ZIM, not another one. The package's file is served under the name unless the copy is strictly newer by its Date metadata, in which case the copy is (and the package's file stands down, like a same-name copy in _own_copy_first). Edits ``zims`` in place; returns ``{loser path: winner path}``. A ZIM that only looks alike (another Name) is left alone, and so is a data pack: Almanac HD carries the Almanac's Name by design (almanachd) and is served under its own.""" from zimi import ownzims lost = {} for name in sorted(zims): if name in DATA_PACKS: continue path = zims.get(name) fam = ownzims.family_of(path) if path else None if not fam: continue own_name, newer = fam own_path = zims.get(own_name) if name == own_name or not own_path or not ownzims.is_own_path(own_path): continue if newer: lost[own_path] = path zims[own_name] = path else: lost[path] = own_path del zims[name] return lost #: Files in the library that no name serves because a newer build of the same thing does (a superseded edition, or a #: copy of an own ZIM): {path: path of what serves instead}. Only the root and one folder down: another program's #: folder is not Zimi's to tidy, and the package's own file is never listed. _older_copies = {} def _set_older_copies(groups, served, own_wins): global _older_copies found = {} for cands in groups.values(): for tier, path in cands: if tier in (0, 1, -1) and path not in served and not _is_own_zim_path(path): winner = next((p for _t, p in cands if p in served), None) if winner: found[path] = winner for loser, winner in own_wins.items(): if not _is_own_zim_path(loser): found[loser] = winner _older_copies = found def library_rel(path): """A library file as the book name under its folder, relative to ``ZIM_DIR`` with ``/`` separators: ``sub/name.zim`` for ``sub/name.zimaa`` too. Manage hands this back to name exactly one file.""" try: rel = os.path.relpath(os.path.dirname(path), ZIM_DIR) except ValueError: # another drive rel = os.pardir book = zimparts.book_filename(path) if rel == os.curdir or rel.split(os.sep)[0] == os.pardir: # outside the library (Zimi's own file): its name alone return book return "/".join(rel.split(os.sep) + [book]) def older_copies(): """The superseded files, for Manage > Storage: ``[{file, size_bytes, replaced_by}]``, biggest first. ``file`` is the path under the library root (a split book by its book name, its size across every chunk), so a Delete acts on that file and no other of the same name.""" out = [] for path, winner in _older_copies.items(): try: size = zimparts.size(path) except OSError: continue out.append({"file": library_rel(path), "size_bytes": size, "replaced_by": library_rel(winner)}) return sorted(out, key=lambda r: (-r["size_bytes"], r["file"])) def _rel_or_abs(path, start): """``path`` relative to ``start`` for a log line; the path itself when they are on different drives (Windows raises ValueError there) so a log line can never break a scan.""" try: return os.path.relpath(path, start) except ValueError: return path def _split_languages(name, cands, zims, groups): """One name's collision, resolved and logged: builds in the keeper's language stay shadowed, and each other language's best build takes its language name in `zims` unless a file already has that name as its own (a key of `groups`).""" keeper = zims[name] keeper_lang = _zim_lang_key(os.path.basename(keeper)) by_lang = {} for tier, path in cands: if path != keeper: lang = _zim_lang_key(os.path.basename(path)) by_lang.setdefault(lang, []).append((tier, path)) for lang, lang_cands in by_lang.items(): lang_name = f"{name}_{lang}" own = lang != keeper_lang and lang_name not in groups if own: zims[lang_name] = _zim_pick(lang_cands) for _tier, path in lang_cands: if own and zims[lang_name] == path: log.info( "ZIM name collision '%s': keeping %s, serving %s as '%s'", name, _rel_or_abs(keeper, ZIM_DIR), _rel_or_abs(path, ZIM_DIR), lang_name, ) continue log.info( "ZIM name collision '%s': keeping %s, ignoring %s", lang_name if own else name, _rel_or_abs(zims[lang_name] if own else keeper, ZIM_DIR), _rel_or_abs(path, ZIM_DIR), ) def get_zim_files(): """Get ZIM file mapping. Uses startup cache (ZIM dir is read-only mount). When a restricted user is logged in (current_allow() is not None), the mapping is filtered to their allowlist — a fresh dict, never a mutation of the cache. This is the single choke point every dict-based read path flows through.""" global _zim_files_cache if _zim_files_cache is None: _zim_files_cache = _scan_zim_files() allow = current_allow() if allow is None: return _zim_files_cache return {k: v for k, v in _zim_files_cache.items() if k in allow} #: ZIMs that are data for a part of Zimi, not something to read: served at /w// to the part that uses them, #: never on Home, in the library's grid, in search or in the title indexes (Almanac HD: the Almanac's tiles, in the Almanac's maxi flavour or 1.15.3's tile ZIM). DATA_PACKS = frozenset(("zimi_almanac_maxi", "zimi_almanac_ultra", "zimi_almanac_hd", "zimi_almanac_hd_moon", "zimi_almanac_hd_mars", "zimi_almanac_hd_mercury", "zimi_almanac_hd_earth")) # the last four: parts of a split set (almanachd.PARTS) def content_zims(): """get_zim_files() less the data packs: what search and the indexes walk.""" return {k: v for k, v in get_zim_files().items() if k not in DATA_PACKS} def server_zim_count(): """How many ZIMs this SERVER has, ignoring who is asking. get_zim_files() filters by the caller's allowlist, which is right for every read path and wrong for a server-level fact. /health used it, so from 1.8.0 — when per-user allowlists arrived and nothing revisited the callers — an unauthenticated health check on any instance that restricts anonymous access reported zim_count 0 while the library served 73. Three releases of a monitoring endpoint answering "empty" about a full library. """ global _zim_files_cache if _zim_files_cache is None: _zim_files_cache = _scan_zim_files() return len(_zim_files_cache) def open_archive(path): """Open a ZIM archive (a split book whole, or not at all: zimparts).""" return zimparts.open_book(path) def entry_item(archive, path): """The item at ``path`` in ``archive``, a redirect followed; None when the archive has no such entry. Only an absent entry is None: any other failure (a damaged cluster, a file cut short) raises, so what a caller keeps (a shelf, a feed, a details file) never takes a read that failed for "nothing there". Caller holds the archive's lock, or owns it.""" try: entry = archive.get_entry_by_path(path) except KeyError: return None if entry.is_redirect: entry = entry.get_redirect_entry() return entry.get_item() def entry_bytes(archive, path, limit, *, head=False): """The bytes at ``path`` by entry_item's rules: None when there is no such entry, or it is over ``limit`` bytes (checked before it is read). ``head``: the first ``limit`` bytes, whatever the entry's size.""" item = entry_item(archive, path) if item is None: return None if head: return bytes(item.content[:limit]) if item.size > limit: return None return bytes(item.content) #: openZIM's icon size; Illustration_48x48@1 is the mandatory key. ICON_SIZE = 48 ILLUSTRATION_PREFIX = "Illustration_" # Cache records carry it: has_icon counted any illustration size from 2. ICON_VERSION = 2 def illustration_png(archive): """The PNG a book's icon is drawn from, or None. The 48x48 (@1, then @2) when the book has it; else the nearest size it carries: the smallest at or above 48, then the largest below. Caller holds the archive's lock.""" for key in ("Illustration_48x48@1", "Illustration_48x48@2"): try: data = bytes(archive.get_metadata(key)) except Exception: data = b"" if data: return data try: sizes = sorted(archive.get_illustration_sizes()) except Exception: return None above = [s for s in sizes if s >= ICON_SIZE] below = [s for s in reversed(sizes) if s < ICON_SIZE] for size in above + below: try: data = bytes(archive.get_illustration_item(size).content) except Exception: continue if data: return data return None # A bounded walk of every entry stops here: enough for a folder of files, # under the archive's lock (health.py's full-scan bound). A wiki's page # tree is walked whole, in the background. MAX_WALK_ENTRIES = 120_000 def walk_entries(archive, bounded=True): """``(entry, item)`` for each entry of ``archive`` that is not a redirect, in the order they are stored: a dirent and its item's header, never its bytes. The first MAX_WALK_ENTRIES are looked at, or every one when not ``bounded``. An entry that will not read raises, as entry_item's failures do: a walk that skipped it would pass for whole.""" n = archive.entry_count if bounded: n = min(n, MAX_WALK_ENTRIES) for i in range(n): entry = entry_by_id(archive, i) if not entry.is_redirect: yield entry, entry.get_item() from zimi.previews import ( # noqa: E402 strip_html, _extract_preview, _resolve_img_path, extract_snippet, ) # ============================================================================ # ZIM Listing & Metadata Cache # ============================================================================ def list_zims(use_cache=True): """List all available ZIM files with metadata. Uses startup cache when available.""" global _zim_list_cache if use_cache and _zim_list_cache is not None: allow = current_allow() if allow is None: return _zim_list_cache # Restricted user: return a filtered copy, never mutate the shared cache. return [z for z in _zim_list_cache if z.get("name") in allow] zims = get_zim_files() info = [] for name, path in zims.items(): size_bytes = zimparts.size(path) article_count = None try: archive = open_archive(path) entry_count = archive.entry_count try: article_count = archive.article_count except Exception: article_count = None except Exception as e: log.debug("Failed to open archive for listing %s: %s", name, e) entry_count = "?" entry = { "name": name, "file": zimparts.book_filename(path), "size_gb": round(size_bytes / _BYTES_PER_GB, 6), "size_bytes": size_bytes, "entries": entry_count, **_split_facts(path), } if article_count is not None: entry["article_count"] = article_count info.append(entry) return info def _split_facts(path): """What a library row says about a split book: ``parts``, its chunk count, and ``missing_part`` when a chunk is gone. Empty for a whole file.""" if not zimparts.is_split(path): return {} facts = {"parts": len(zimparts.parts(path))} gap = zimparts.missing_part(path) if gap: facts["missing_part"] = gap log.warning("Split ZIM %s is missing chunk %s: not served until it is back", loggable(zimparts.book_filename(path)), loggable(gap)) return facts def get_archive(name): """Get a cached archive handle, or open it fresh. Thread-safe. Fails closed for a restricted user: a ZIM outside their allowlist resolves to None (as if not installed), gating every archive-based content path (/w/, /snippet, /catalog, /article-languages, /random) including already-pooled handles. Background/admin requests have current_allow()==None → no change.""" if not zim_allowed(name): return None if name in _archive_pool: return _archive_pool[name] zims = get_zim_files() if name in zims: with _archive_lock: # Double-check after acquiring lock if name in _archive_pool: return _archive_pool[name] try: archive = open_archive(zims[name]) except (RuntimeError, Exception) as e: log.warning( "Skipping corrupt ZIM '%s': %s", loggable(name), loggable(e) ) return None _archive_pool[name] = archive return archive return None def _cache_file_path(): """Path to the persistent metadata cache file.""" return os.path.join(ZIMI_DATA_DIR, "cache.json") def _load_disk_cache(): """Load persistent metadata cache from disk. Returns {filename: metadata} or None.""" try: with open(_cache_file_path(), encoding="utf-8") as f: data = json.load(f) if data.get("version") != _CACHE_VERSION: return None return data.get("files", {}) except (FileNotFoundError, json.JSONDecodeError, KeyError): return None _ident_disk = (None, {}) # (cache file's stamp, its records) def cached_identity(path): """``(Name, Date)`` of the book at ``path`` from the metadata cache on disk, or None when the cache has no record of this version of it with a Name (a record from before the Name was kept, or a new file).""" global _ident_disk try: stamp = os.stat(_cache_file_path()).st_mtime_ns except OSError: return None if _ident_disk[0] != stamp: _ident_disk = (stamp, _load_disk_cache() or {}) rec = _ident_disk[1].get(zimparts.book_filename(path)) try: size, mtime = zimparts.size(path), zimparts.mtime(path) # a split book is its chunks together, as load_cache keys it except OSError: return None if isinstance(rec, dict) and "mname" in rec and rec.get("size") == size and rec.get("mtime") == mtime: return (rec["mname"], rec.get("date") or "") return None def _keep_identity_stubs(disk_cache, file_cache): """Keep what the library read of each superseded file (its Name and Date, so the next scan opens nothing for it) in the metadata cache, as a stub record: a file no name serves has no full record. True when one was added or changed.""" from zimi import ownzims changed = False for path in list(_older_copies): fn = zimparts.book_filename(path) if fn in file_cache: continue try: size, mtime = zimparts.size(path), zimparts.mtime(path) except OSError: continue old = disk_cache.get(fn) if isinstance(old, dict) and old.get("size") == size and old.get("mtime") == mtime and "mname" in old: file_cache[fn] = old continue hit = ownzims._ident_cache.get(path) # only what the scan already read ident = hit[1] if hit else None if ident is None: continue file_cache[fn] = {"stub": True, "mtime": mtime, "size": size, "mname": ident[0], "date": ident[1]} changed = True return changed def _save_disk_cache(file_cache): """Save metadata cache to disk (atomic write via rename).""" data = { "version": _CACHE_VERSION, "generated": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "files": file_cache, } _atomic_write_json(_cache_file_path(), data, indent=2) def _extract_zim_date(filename): """Extract the date portion from a ZIM filename. Returns (base_name, date_str) or (base_name, None).""" m = re.search(r"_(\d{4}-\d{2})\.zim$", filename) if m: base = filename[: m.start()] return base, m.group(1) # StreetZim dates its builds to the day, with dashes: osm-hawaii-2026-09-08.zim m = re.match(r"^(osm-.+?)-(\d{4}-\d{2}-\d{2})\.zim$", filename) if m: return m.group(1), m.group(2) return filename.replace(".zim", ""), None # Where a capture that kept both of a site's faces records them (creator writes # it). Here, not in creator, so the core can read it without the capture code. FACES_METADATA_KEY = "X-Zimi-Faces" def _read_faces(archive): """``{"main": scheme, "other": {...}}`` when a capture kept both of the site's faces, else None. Never raises: a ZIM without it is every ZIM.""" if archive is None: return None try: raw = bytes(archive.get_metadata(FACES_METADATA_KEY)) except Exception: return None try: faces = json.loads(raw.decode("utf-8", errors="replace")) except Exception: return None if not isinstance(faces, dict): return None other = faces.get("other") if not isinstance(other, dict) or not other.get("path"): return None return faces def _own_display_title(title, tags): """Zimi's own ZIMs show their short name inside Zimi (the file's Title keeps "Zimi " for other readers).""" from zimi import ownzims return ( ownzims.display_title(title) if ownzims.OWN_TAG in (tags or "").split(";") else title ) def _extract_zim_metadata(name, path): """Open a ZIM archive and extract its metadata. Returns (info_dict, archive).""" size_bytes = zimparts.size(path) filename = zimparts.book_filename(path) size_gb = size_bytes / _BYTES_PER_GB meta_title = name meta_desc = "" meta_date = "" meta_lang = "" meta_creator = "" meta_scraper = "" map_facts = None meta_tags = "" meta_name = "" meta_counter = "" meta_history = "" has_icon = False main_path = "" archive = None article_count = None try: archive = open_archive(path) entry_count = archive.entry_count # Real article count (user-facing content entries, excluding redirects # and non-article assets). Additive over `entries` (all user entries): # cards/info panels prefer this when present, fall back to entry_count. try: article_count = archive.article_count except Exception: article_count = None for key in archive.metadata_keys: try: val = bytes(archive.get_metadata(key)) if key == "Title": meta_title = val.decode("utf-8", errors="replace").strip() or name elif key == "Description": meta_desc = val.decode("utf-8", errors="replace").strip() elif key == "Date": meta_date = val.decode("utf-8", errors="replace").strip() elif key == "Creator": meta_creator = val.decode("utf-8", errors="replace").strip() elif key == "Scraper": meta_scraper = val.decode("utf-8", errors="replace").strip() elif key == "Tags": meta_tags = val.decode("utf-8", errors="replace").strip() elif key == "Name": meta_name = val.decode("utf-8", errors="replace").strip() elif key == "Counter": meta_counter = val.decode("utf-8", errors="replace") elif key == "X-Zimi-History": meta_history = val.decode("utf-8", errors="replace") elif key == "Language": raw_lang = val.decode("utf-8", errors="replace").strip().lower() # Handle multilingual ZIMs (comma-separated codes) if "," in raw_lang: parts = [p.strip() for p in raw_lang.split(",") if p.strip()] meta_lang = ",".join(_ISO639_3_TO_1.get(p, p) for p in parts) else: meta_lang = _ISO639_3_TO_1.get(raw_lang, raw_lang) elif key.startswith(ILLUSTRATION_PREFIX): has_icon = True except Exception as e: log.debug( "Failed to read metadata key %s for %s: %s", loggable(repr(key)), loggable(name), loggable(e), ) pass try: me = archive.main_entry if me.is_redirect: me = me.get_redirect_entry() main_path = me.path except Exception as e: log.debug( "Failed to read main entry for %s: %s", loggable(name), loggable(e) ) pass cold_kind = _zim_kind(meta_scraper, meta_tags, meta_name) if cold_kind == "map": map_facts = _map_facts(archive, meta_scraper) elif cold_kind == "reddit": map_facts = _reddit_facts(archive) except Exception as e: log.debug( "Failed to open archive for metadata extraction %s: %s", loggable(name), loggable(e), ) entry_count = "?" # Fall back to date from filename if not in metadata if not meta_date: _, file_date = _extract_zim_date(filename) if file_date: meta_date = file_date # Fall back to language from filename (e.g. wikipedia_fr_all → "fr") if not meta_lang: m = re.match(r"^[a-zA-Z]+(?:\.\w+)*_([a-z]{2,3})_", filename) if m: code = m.group(1) meta_lang = _ISO639_3_TO_1.get(code, code) kind = _zim_kind(meta_scraper, meta_tags, meta_name) map_search = kind == "map" and _zim_map_search(meta_scraper) info = { "name": name, "file": filename, **_split_facts(path), "size_gb": round(size_gb, 6), # Exact byte size: peers verify a pulled .zim against this (a # truncated transfer is the realistic LAN failure mode). "size_bytes": size_bytes, "entries": entry_count, "title": _own_display_title(meta_title, meta_tags), "description": meta_desc, "date": meta_date, "language": meta_lang, "has_icon": has_icon, "category": _effective_category(name, path, kind), "main_path": main_path, "meta_name": meta_name, } # Additive: what the ZIM says it is, kept so a cache hit can re-derive the # category without reopening the archive. if kind: info["kind"] = kind if kind == "wiki": info["project"] = _wiki_project(meta_name, name) feeds = _zim_feeds( kind, info.get("project", ""), meta_scraper, meta_name, meta_counter, meta_history, ) if feeds: info["feeds"] = feeds if map_search: info["map_search"] = True if map_facts: info.update(map_facts) if "subreddits" in map_facts: info["title"] = _subreddit_title(info["title"], map_facts["subreddits"]) # Additive: the raw subfolder name behind a folder-derived category, so a # client can tell "filed under medical/" from a name-heuristic guess. Absent # for root-level files, which keep heuristic categorization untouched. folder = _zim_folder(path) if folder: info["folder"] = folder if article_count is not None: info["article_count"] = article_count # Both of the site's faces, when a capture kept them. Small, and it has to # ride with the library list rather than the detail panel: the reader picks # a face the moment an article is opened, and it cannot wait for a second # request to find out there was a choice. faces = _read_faces(archive) if faces: info["faces"] = faces # Additive flag: a ZIM Zimi itself exported (bookmark exports). The UI # shows these with their full creation date. if meta_creator == "Zimi": info["zimi_export"] = True return info, archive def _is_own_zim_path(path): """Whether ``path`` is one of Zimi's own ZIMs (zimi/ownzims.py).""" from zimi import ownzims return ownzims.is_own_path(path) def _own_zim_update(path, prior): """(updated_at, own) for one of Zimi's own ZIMs, where ``own`` = {"v": Zimi version, "src": the hash of the source it was built from (its .source file)}. Updated only when this Zimi is a different version than the one that last served it AND the content differs: a redeploy or rebuild of the same release, or a new release whose games did not change, is nothing new to look at.""" try: with open(path + ".source", encoding="utf-8") as f: src = f.read().strip() except OSError: src = "" prior = prior or {} was = prior.get("own") or {} # The releases that changed it, newest first: what its Updated dot and About say. own = { "v": ZIMI_VERSION, "src": src, "h": list(was.get("h") or [])[:_OWN_HISTORY_MAX], } if ( src and was.get("src") and was.get("v") != ZIMI_VERSION and was.get("src") != src ): now = time.time() own["h"] = ([{"v": ZIMI_VERSION, "ts": now}] + own["h"])[:_OWN_HISTORY_MAX] return now, own return prior.get("updated_at"), own _OWN_HISTORY_MAX = 10 _ZIM_UPDATES_MAX = 10 _whatsnew = None def _whatsnew_lines(version, own_name): """The release's highlight lines about one of Zimi's own ZIMs (assets/whatsnew.json, from the CHANGELOG).""" global _whatsnew if _whatsnew is None: try: with open( os.path.join( os.path.dirname(os.path.abspath(__file__)), "assets", "whatsnew.json", ), encoding="utf-8", ) as f: _whatsnew = json.load(f) except (OSError, ValueError): _whatsnew = {} return list((_whatsnew.get(version) or {}).get(own_name) or []) def zim_updates(name, history=None): """How ``name`` came to be what it is, newest first: each arrival and update of a library ZIM from the event history (its file, so its edition, and its size), or for one of Zimi's own ZIMs, each Zimi release that changed it with that release's highlights. For a dot that explains itself and About. ``history``: the event history when the caller already read it (several ZIMs in one request). """ out = [] for z in _zim_list_cache or []: if z.get("name") == name and z.get("own_h"): for h in z["own_h"]: out.append( { "event": "release", "ts": h.get("ts"), "version": h.get("v"), "notes": _whatsnew_lines(h.get("v"), name), } ) return out for ev in _load_history() if history is None else history: if ev.get("name") == name and ev.get("event") in ("download", "updated"): out.append( { "event": ev["event"], "ts": ev.get("ts"), "file": ev.get("filename", ""), "size_bytes": ev.get("size_bytes") or 0, } ) if len(out) >= _ZIM_UPDATES_MAX: break return out def _self_heal_mass_first_seen(info, file_cache, zims): """Repair a library-wide first_seen stamp left by a full cache rebuild. A pre-fix rebuild stamped ``first_seen = now`` for every ZIM at once, so the whole library badged "New". Detect that fingerprint — a majority of entries sharing one first_seen instant that does NOT match their file mtimes — and re-derive each affected stamp from the file's own mtime. Mutates ``info`` and ``file_cache`` in place; returns True if anything was repaired. The mtime check is the safety guard: a genuine batch download (10 ZIMs pulled within seconds) also shares one first_seen, but there the files' own mtimes match that instant, so those are left untouched. """ stamped = [e for e in info if e.get("first_seen")] if len(stamped) < 4: return False # too small a library to distinguish a rebuild from reality from collections import Counter buckets = Counter(round(e["first_seen"] / _MASS_STAMP_WINDOW) for e in stamped) bucket_key, count = buckets.most_common(1)[0] if count <= len(stamped) * 0.5: return False # no dominant shared instant → not a mass rebuild now = time.time() repaired = 0 for e in info: fs = e.get("first_seen") if not fs or round(fs / _MASS_STAMP_WINDOW) != bucket_key: continue path = zims.get(e["name"]) if not path: continue try: mtime = os.path.getmtime(path) except OSError: continue # Stamp is plausible if it lands near the file's own mtime — leave it. if abs(fs - mtime) <= _MASS_STAMP_MTIME_TOL: continue new_fs = min(mtime, now) e["first_seen"] = new_fs fc = file_cache.get(e["file"]) if fc is not None: fc["first_seen"] = new_fs repaired += 1 if repaired: log.info( "first_seen self-heal: re-derived %d/%d ZIM stamps from file mtime " "(a full cache rebuild had stamped them all at once)", repaired, len(stamped), ) return repaired > 0 def _self_heal_update_stamps(info, file_cache): """Repair 'New' badges on ZIMs that were actually UPDATED before the dated-filename inherit fix landed. The pre-fix updater re-stamped ``first_seen=now`` and left ``updated_at`` unset when an update arrived under a new dated filename, so a genuinely updated ZIM badges 'New' instead of 'Updated' — indistinguishable from a fresh install by its stamps alone. The persistent event history IS the authority: it records an ``updated`` event per real update. For any ZIM the history says was updated, sync its cache stamps to that truth — set ``updated_at`` from the update event and pull ``first_seen`` back to the earliest recorded event so ``updated_at > first_seen`` and the badge reads 'Updated', matching the activity log. Only touches ZIMs with a recorded update event, so it can never misfire on a real fresh install. Mutates ``info`` and ``file_cache`` in place; returns True if anything changed.""" try: history = _load_history() except Exception: return False if not history: return False # Per logical ZIM name: earliest recorded event (install) and latest update. earliest = {} latest_update = {} for ev in history: ts = ev.get("ts") name = ev.get("name") if not ts or not name: continue if name not in earliest or ts < earliest[name]: earliest[name] = ts if ev.get("event") == "updated" and ( name not in latest_update or ts > latest_update[name] ): latest_update[name] = ts if not latest_update: return False repaired = 0 for e in info: new_ua = latest_update.get(e.get("name")) if not new_ua: continue # Already correctly flagged 'Updated' (updated_at > first_seen)? Leave it. if (e.get("updated_at") or 0) > (e.get("first_seen") or 0): continue # first_seen must precede the update. Prefer the earliest recorded event; # if the only record IS the update (original install predates history), # nudge first_seen just below it so the ordering — hence badge — is right. new_fs = min(earliest.get(e.get("name"), new_ua), new_ua) if new_fs >= new_ua: new_fs = new_ua - 1 if e.get("updated_at") == new_ua and e.get("first_seen") == new_fs: continue e["updated_at"] = new_ua e["first_seen"] = new_fs fc = file_cache.get(e["file"]) if fc is not None: fc["updated_at"] = new_ua fc["first_seen"] = new_fs repaired += 1 if repaired: log.info( "update-stamp self-heal: re-flagged %d ZIM(s) as 'Updated' from the " "event history (pre-fix updates had mis-stamped them 'New')", repaired, ) return repaired > 0 def _boot_say(*args, **kwargs): """Boot and status chatter, on stderr. stdout is a PROTOCOL channel for two of the ways Zimi is run. The MCP server speaks JSON-RPC over stdio, so a friendly "No ZIM files found in ..." line printed to stdout lands in the middle of the handshake and a strict client rejects the stream. It was doing exactly that: the first thing a new Open WebUI user saw, on the run where they had not put any ZIMs in place yet, was a corrupted protocol rather than an empty library. Nothing is lost by moving it. A person running `zimi serve` sees stderr in the same terminal, in the same place; only the file descriptor changes. Actual command OUTPUT -- search results, `zimi list` -- still goes to stdout, where a pipe can read it. """ kwargs.setdefault("flush", True) kwargs["file"] = sys.stderr print(*args, **kwargs) def load_cache(force=False): """Load ZIM metadata, using persistent disk cache for instant startup. On first run: scans all ZIMs (slow), saves cache to .zimi_cache.json. On subsequent runs: reads cache, validates mtimes, only re-scans changed files. Archives are opened lazily on first access, not at startup. """ _init() global _zim_list_cache, _zim_files_cache, _cache_generation t0 = time.time() _zim_files_cache = _scan_zim_files() if force: _cache_generation += 1 zims = _zim_files_cache # Always load the persisted cache. Even on a forced rebuild we re-scan every # archive (fresh metadata) but must carry each ZIM's first_seen/updated_at # forward — otherwise a rebuild re-stamps the whole library and every ZIM # badges "New" at once (the bug this fix closes). disk_cache = _load_disk_cache() info = [] scanned = 0 kind_backfilled = False # a legacy record learned what it is; write it down backfilled = 0 # legacy entries whose first_seen we filled from file mtime file_cache = {} # for saving back to disk # Index prior cache entries by date-stripped short name. ZIM filenames carry # a date (…_2026-07.zim); an update downloads a NEW dated filename, so the # cache — keyed by full filename — misses and the update masquerades as a # brand-new install (first_seen≈now, no updated_at → badges "New" not # "Updated"). This lets the cache-miss path recognise that a new filename is # the SAME logical ZIM as a known one, inherit its original first_seen, and # stamp updated_at. Keep the earliest first_seen per name (true install). prior_by_name = {} if disk_cache: for _fn, _ce in disk_cache.items(): if not isinstance(_ce, dict): continue _sn = _zim_short_name(_fn) _prev = prior_by_name.get(_sn) if _prev is None or (_ce.get("first_seen") or float("inf")) < ( _prev.get("first_seen") or float("inf") ): prior_by_name[_sn] = _ce for name, path in zims.items(): filename = zimparts.book_filename(path) try: mtime = zimparts.mtime(path) size = zimparts.size(path) except OSError: continue cached = disk_cache.get(filename) if disk_cache else None if cached and cached.get("stub"): cached = None # only what a superseded copy said of itself (_keep_identity_stubs): scanned in full if it is served # When Zimi first sees a ZIM, stamp it so the UI can flag it "New" for # a few days (#34 — a fresh install is otherwise lost in a big # library). A ZIM already known (even if its file changed on an update) # keeps its original stamp; a ZIM present in a pre-feature cache with no # stamp is treated as long-installed, not retroactively "new". # A new filename whose date-stripped name matches a known ZIM is an # UPDATE arriving under a new dated filename, not a first install. prior = prior_by_name.get(name) if cached is None else None prior_first_seen = prior.get("first_seen") if prior else None is_update_rename = cached is None and prior_first_seen is not None if cached is None: if is_update_rename: # Same logical ZIM, newer file: inherit the ORIGINAL first_seen # (never re-stamp it) so updated_at>first_seen and the badge # reads "Updated", matching the activity log. first_seen = prior_first_seen else: # First time Zimi has ever seen this file. Stamp first_seen from # the file's own mtime — NOT wall-clock now. A genuinely new # download has mtime≈now, so it still lights up "New"; but a full # cache rebuild of an old library (force=True, or a # corrupt/unreadable cache.json) now re-derives quiet, honest # stamps from the files instead of badging the whole library at # once. min() guards against future mtimes. first_seen = min(mtime, time.time()) else: first_seen = cached.get("first_seen") # Legacy cache entries (written before #34) carry no first_seen. # Backfill from the ZIM file's own mtime so a recently-downloaded # ZIM lights up "Recently added" on an already-established library, # while a long-installed file (old mtime) stays quiet. Persisted by # the cache-hit write-back below, so it's computed once. If the file # vanished mid-scan, leave it None rather than stamping "now". if first_seen is None: try: first_seen = os.path.getmtime(path) backfilled += 1 except OSError: first_seen = None # An already-known ZIM whose file changed on disk is an update — stamp # updated_at so the UI can flag it "Updated" (distinct from "New"). file_unchanged = bool( cached and cached.get("mtime") == mtime and cached.get("size") == size ) # Skip re-opening the archive only on a normal load; a forced rebuild # re-scans even unchanged files, but must not mistake that for a change. cache_hit = file_unchanged and not force if cached is None: # Brand-new install → no update stamp; an update-under-new-filename # → stamp updated_at=now (it's a change to an already-known ZIM). updated_at = time.time() if is_update_rename else None elif file_unchanged: updated_at = cached.get("updated_at") else: updated_at = time.time() own = None if _is_own_zim_path(path): # Zimi's own ZIMs are rebuilt with Zimi itself, a new dated file every deploy. They are # Updated only when a new Zimi version brings different content (_own_zim_update). updated_at, own = _own_zim_update(path, cached or prior_by_name.get(name)) if cache_hit and cached: # Cache hit — use stored metadata, skip opening archive if ( "kind" not in cached or int(cached.get("kind_v") or 1) < KIND_VERSION or (cached.get("kind") == "map" and "map_search" not in cached) ): # A record from before Zimi knew what a map was (or what a map # with a search box was). Eric's world map was registered by # 1.9 half an hour before 1.10 booted and sat under Other with # nothing to say otherwise. cached["kind"], cached["map_search"] = _read_zim_kind(path) # Stamped, or the next boot finds the same old version and # opens every ZIM again, and rewrites the cache, forever. cached["kind_v"] = KIND_VERSION kind_backfilled = True if cached.get("kind") == "map" and ( "map_bounds" not in cached or cached.get("map_v") != MAP_FACTS_VERSION ): # A record from before Zimi kept a map's ground and publisher, # or from before it knew a world map's ground. cached.update(_read_map_facts(path)) cached["map_v"] = MAP_FACTS_VERSION kind_backfilled = True if cached.get("kind") == "reddit" and "subreddits" not in cached: cached.update(_read_reddit_facts(path)) kind_backfilled = True if cached.get("kind") == "wiki" and "project" not in cached: # A record from before Zimipedia kept the project by Name. project = _read_wiki_project(path, name) if project is not None: cached["project"] = project kind_backfilled = True if "feeds" not in cached or int(cached.get("feeds_v") or 1) < FEEDS_VERSION: # A record from before a ZIM could feed two apps, or from # before _zim_feeds's latest rule. feeds = _read_zim_feeds( path, cached.get("kind") or "", cached.get("project") or "" ) if feeds is not None: cached["feeds"] = feeds cached["feeds_v"] = FEEDS_VERSION kind_backfilled = True if not cached.get("has_icon") and int(cached.get("icon_v") or 0) < ICON_VERSION: # A record from before an icon could be any size the book carries. cached["has_icon"] = _read_has_icon(path) cached["icon_v"] = ICON_VERSION kind_backfilled = True entry = { "name": name, "file": filename, # Derived from the bytes on every read, NEVER taken from the # cache. A stored size_gb is a stored UNIT, and the day the # unit changed, 43 of 67 ZIMs went on serving the old one from # disk while freshly scanned ones served the new — the library # quoting two different numbers for the same kind of thing, # which is the whole complaint. Bytes are the fact and stat is # free; anything divided out of them is a view, and a view has # no business surviving in a cache. "size_gb": round(size / _BYTES_PER_GB, 6), # Exact bytes straight from stat — peers verify pulled ZIMs # against this, so it must be present even on a cache hit # (older disk caches predate the field). "size_bytes": size, "entries": cached.get("entries", "?"), "title": cached.get("title", name), "description": cached.get("description", ""), "date": cached.get("date", ""), "language": cached.get("language", ""), "has_icon": cached.get("has_icon", False), # Category and folder come from the live path, never the cache # record: moving a ZIM into (or out of) a folder changes neither # its mtime nor its size, so a cached copy of either would go # stale on exactly the move that should re-file it. Deriving # here is pure string work, so an existing library re-files on # the next boot with no rescan and no extra I/O. "category": _effective_category(name, path, cached.get("kind")), "main_path": cached.get("main_path", ""), "first_seen": first_seen, "updated_at": updated_at, } # A split book's chunks, read from the files like the folder (a stat each). entry.update(_split_facts(path)) folder = _zim_folder(path) if folder: entry["folder"] = folder if cached.get("kind"): entry["kind"] = cached["kind"] if "project" in cached: entry["project"] = cached["project"] if cached.get("feeds"): entry["feeds"] = cached["feeds"] if cached.get("map_search"): entry["map_search"] = True if "map_bounds" in cached: entry["map_bounds"] = cached["map_bounds"] entry["map_source"] = cached.get("map_source", "") if "subreddits" in cached: entry["subreddits"] = cached["subreddits"] entry["title"] = _subreddit_title(entry["title"], cached["subreddits"]) if "has_qids" in cached: entry["has_qids"] = cached["has_qids"] # Both of the site's faces, when a capture kept them. Cached like # every other fact about the file: the reader needs it the instant # an article is opened, and re-opening the archive to ask would put # a disk read on the path this cache exists to keep clear. if cached.get("faces"): entry["faces"] = cached["faces"] # Which ZIMs Zimi made, remembered rather than re-derived. See # kind_store: without this the Creator pane reopens every archive # in the library after each restart. if cached.get("zimi_kind"): entry["zimi_kind"] = cached["zimi_kind"] # Additive: real article count. Absent in caches built before this # field existed — the UI falls back to `entries` when it's missing. if cached.get("article_count") is not None: entry["article_count"] = cached["article_count"] # Additive: Zimi-exported flag (bookmark exports show full dates). if cached.get("zimi_export"): entry["zimi_export"] = True # What the ZIM is made of, measured once by the background worker # and remembered here. Absent until it has been — the scan does not # measure, deliberately: a cold library already takes long enough to # open without adding a read of every file to it. if cached.get("shape"): entry["shape"] = cached["shape"] # What each app counted of it (note_app_items), for the Apps page. if cached.get("items"): entry["items"] = cached["items"] # The file's own identity, carried on the entry. Small, and it is # what lets a picture request be answered from the client's copy # without opening the archive to find out — see _picture_etag. entry["mtime"] = mtime if own and own.get("h"): entry["own_h"] = own["h"] info.append(entry) cached_out = dict(cached) if "mname" not in cached_out: # A record from before the Name was kept: read it once (the scan has, to place copies of own ZIMs). from zimi import ownzims as _own_ids ident = _own_ids.identity(path) if ident is not None: cached_out["mname"] = ident[0] kind_backfilled = True # written down, or every start reads every archive again if first_seen is not None: cached_out["first_seen"] = first_seen if updated_at is not None: cached_out["updated_at"] = updated_at if own: cached_out["own"] = own file_cache[filename] = cached_out else: # Cache miss — scan this ZIM entry, archive = _extract_zim_metadata(name, path) if archive and entry.get("entries") != "?": _archive_pool[name] = archive if first_seen is not None: entry["first_seen"] = first_seen entry["updated_at"] = updated_at entry["mtime"] = mtime if own and own.get("h"): entry["own_h"] = own["h"] info.append(entry) scanned += 1 new_cached = { "name": name, "mtime": mtime, "size": size, "size_gb": entry["size_gb"], "entries": entry["entries"], "title": entry["title"], "description": entry["description"], "date": entry.get("date", ""), "language": entry.get("language", ""), "has_icon": entry["has_icon"], "main_path": entry["main_path"], # The ZIM's own Name, so a copy of one of Zimi's own ZIMs under another file name is known without # opening it (ownzims.family_of). "mname": entry.pop("meta_name", ""), } if entry.get("article_count") is not None: new_cached["article_count"] = entry["article_count"] if entry.get("zimi_export"): new_cached["zimi_export"] = True # Always, "" included: a decided non-map must not be re-read # on every boot as if it were a record from before the field. new_cached["kind"] = entry.get("kind") or "" new_cached["kind_v"] = KIND_VERSION if "project" in entry: new_cached["project"] = entry["project"] # Always, {} included: a ZIM that feeds no other app is decided. new_cached["feeds"] = entry.get("feeds") or {} new_cached["feeds_v"] = FEEDS_VERSION new_cached["icon_v"] = ICON_VERSION if entry.get("map_search"): new_cached["map_search"] = True # A map's ground and publisher, null included: a map whose config # Zimi could not read is decided too, not re-read every boot. if "map_bounds" in entry: new_cached["map_bounds"] = entry["map_bounds"] new_cached["map_source"] = entry.get("map_source", "") new_cached["map_v"] = MAP_FACTS_VERSION if "subreddits" in entry: new_cached["subreddits"] = entry["subreddits"] # Only when the capture kept two: most ZIMs have one face, and a # cache full of nulls is noise. An older Zimi reading this record # ignores the key, which is what keeps a downgrade safe. if entry.get("faces"): new_cached["faces"] = entry["faces"] if first_seen is not None: new_cached["first_seen"] = first_seen if updated_at is not None: new_cached["updated_at"] = updated_at if own: new_cached["own"] = own file_cache[filename] = new_cached # Self-heal a library that a pre-fix rebuild already mass-stamped. The code # fix above stops NEW rebuilds from doing it, but existing disk caches still # carry first_seen= for every ZIM; repair them from mtime. healed = _self_heal_mass_first_seen(info, file_cache, zims) # Repair 'New' badges on ZIMs the event history proves were UPDATED before # the dated-filename inherit fix (pre-fix updates mis-stamped them 'New'). healed_updates = _self_heal_update_stamps(info, file_cache) _set_listing(info) elapsed = time.time() - t0 # Persist cache if we scanned anything new, backfilled a legacy first_seen # (so the mtime stamp is computed once), or repaired mass-stamped entries. stubs_changed = _keep_identity_stubs(disk_cache or {}, file_cache) if ( scanned > 0 or stubs_changed or backfilled > 0 or kind_backfilled or disk_cache is None or healed or healed_updates ): # Wholesale, not a merge — but under the same lock, so it cannot land # in the middle of somebody else's read-modify-write. with _disk_cache_lock: _save_disk_cache(file_cache) cached_count = len(info) - scanned if cached_count > 0 and scanned > 0: _boot_say( f" Cache loaded: {len(info)} ZIMs ({cached_count} cached, {scanned} scanned) in {elapsed:.1f}s", flush=True, ) elif scanned > 0: _boot_say( f" Cache built: {len(info)} ZIMs scanned in {elapsed:.1f}s", flush=True ) elif len(info) > 0: _boot_say( f" Cache loaded: {len(info)} ZIMs from disk cache in {elapsed:.1f}s", flush=True, ) else: # Install-neutral empty state: this line is read by Docker admins, # stick users and source checkouts alike, so it names every location # that was actually searched instead of assuming a volume mount. searched = [ZIM_DIR] + [p for p in _discovery_probed if p != ZIM_DIR] missing = "" if os.path.isdir(ZIM_DIR) else " (directory does not exist)" _boot_say(f" No ZIM files found in {ZIM_DIR}{missing}", flush=True) if os.path.isdir(ZIM_DIR): # The scan covers ZIM_DIR plus one level of subfolders; only files # nested deeper than that are invisible now, so only they get the # hint (a recursive glob at boot is fine — the library is empty). deep_zims = glob.glob(os.path.join(ZIM_DIR, "**", "*.zim"), recursive=True) if deep_zims: _boot_say( f" Found {len(deep_zims)} ZIM file(s) nested deeper than one folder — " f"Zimi scans {ZIM_DIR} and its immediate subfolders only", flush=True, ) _boot_say( f" Searched: {', '.join(searched)}. Put .zim files in any of these, " f"or point ZIM_DIR / --zim-dir at your ZIM folder.", flush=True, ) # Rebuild domain map whenever the ZIM list changes. The build REBINDS # interlang's global; /resolve?domains=1 reads it as _srv._domain_zim_map, # which resolves live through this module's __getattr__ (see the # stale-alias note on the re-export block) rather than an import-time copy. _build_domain_zim_map() def _domain_map_entries_for_zim(name, filename, source_meta, main_path=""): """Domain→ZIM entries ONE ZIM contributes, without opening any archive. Mirrors the three discovery methods of interlang._build_domain_zim_map (filename prefix, Source metadata, name-based TLD inference) plus its www./mobile variant expansion — keep the two in sync. The full rebuild still owns startup and manual refresh; this exists because the rebuild calls get_archive() for every unmapped ZIM, and with a cold archive pool that re-opens the whole library — minutes under _zim_lock on a Pi with a NAS mount, the exact starvation register_zim_file removes (#51). Here the Source string is read from the registration's own private handle, so the merge is pure string work. """ domains = [] def _add(domain): domain = (domain or "").lower().strip() if not domain or "." not in domain: return domains.append(domain) if domain.startswith("www."): domains.append(domain[4:]) else: domains.append("www." + domain) m = re.match(r"^(\w{2,3})\.(wiki\w+\.org)$", domain) if m: domains.append(f"{m.group(1)}.m.{m.group(2)}") if domain in ("stackoverflow.com", "stackexchange.com"): domains.append("m." + domain) base = filename.split(".zim")[0] m = re.match(r"^([a-zA-Z0-9.-]+\.[a-z]{2,})_", base) if m: _add(m.group(1)) elif source_meta: from urllib.parse import urlparse # local: server.py has no other use try: if "://" in source_meta: _add(urlparse(source_meta).hostname or "") else: _add(source_meta.split("/")[0]) except Exception as e: log.debug( "Failed to parse Source %s for %s: %s", loggable(repr(source_meta)), loggable(name), loggable(e), ) elif main_path: # A capture's main entry path IS the site's address # ("draculatheme.com/contribute"), which is the discovery interlang # calls 2b and this function was missing despite the docstring above # promising the two are in sync. Without it a just-created capture # registered under four invented domains — dracula.com, .org, .io, # .net — and nothing linked to it until the next restart rebuilt the # map properly. host = (main_path or "").split("/", 1)[0] if re.match(r"^[a-z0-9-]+(\.[a-z0-9-]+)+$", host or ""): _add(host) elif not name.startswith("zimgit") and "_en_" not in name: for tld in (".com", ".org", ".io", ".net"): _add(name + tld) return {d: name for d in domains} def _zim_live_holder(name, path): """The file serving `name`, when that is a different file still on disk; None when the name is free or its file is gone (the new one takes over).""" held = _zim_files_cache.get(name) if not held or os.path.realpath(held) == os.path.realpath(path): return None try: os.stat(held) except OSError: return None return held def _note_shadowed(loser, winner): from zimi import libfolders libfolders.note_shadowed(loser, winner) def _zim_tier(path): """Where a ZIM sits in the collision rule: 0 the library root, 1 one of its subfolders, 2 a folder another program owns (libfolders).""" from zimi import libfolders if libfolders.owner(path) is not None: return 2 return ( 0 if os.path.dirname(os.path.realpath(path)) == os.path.realpath(ZIM_DIR) else 1 ) def _zim_holder_keeps(held, path): """register_zim_file's mirror of _scan_zim_files' rule: True when `held`, already serving a name, keeps it against the arriving `path`. A root file beats a subfolder one, and that beats another program's folder, whatever the build; within a tier the richer build (_zim_build_rank) holds, and an equal one yields to the arrival.""" held_tier, new_tier = _zim_tier(held), _zim_tier(path) if held_tier != new_tier: return held_tier < new_tier return _zim_build_rank(os.path.basename(held)) > _zim_build_rank( os.path.basename(path) ) def register_zim_file(path, removed_files=(), removed_paths=()): """Incrementally register ONE just-downloaded ZIM into the live library. Replaces the post-download ``load_cache(force=True)`` full rebuild, which re-opened and re-scanned EVERY archive in the library while the caller held ``_zim_lock``. On a small box (Raspberry Pi) serving a big library from network storage that held the lock for minutes — every request that touches libzim starved until the browser gave up, which reads as a server crash (#51). The forced rebuild also pooled every archive at once, a memory spike small boards can't absorb. Shape: the expensive work (archive open + metadata extraction — real I/O on a slow mount) runs BEFORE the lock on a private handle; ``_zim_lock`` is held only to splice the result into the in-memory registry. Opening a private Archive off-lock is safe: libzim's hazard is two threads on ONE Archive object, and this handle is not shared until after the splice (same practice as the post-download validation open in library.py). ``removed_files``: basenames of older versions the caller already deleted from disk; they are dropped from the registry and disk cache in the same splice. ``removed_paths``: full paths of older editions that are gone from disk (another program replaced them). The name each one served is dropped in the same splice, so an update is one swap with no gap and no rescan; a file with the same name in another folder is not touched. Returns True when the library reflects the file; False when the file could not be read — the caller should fall back to a full load_cache(). """ global _zim_files_cache, _zim_list_cache, _cache_generation _init() if _zim_files_cache is None or _zim_list_cache is None: # Library was never scanned (headless/startup edge): there is nothing # to splice into, and a plain load — which will pick the new file up # from disk along with everything else — is the cheap normal path. load_cache() return True filename = os.path.basename(path) name = _zim_base_name(filename) try: st = os.stat(path) except OSError as e: log.warning( "register_zim_file: cannot stat %s: %s", loggable(path), loggable(e) ) return False # Mirror _scan_zim_files' collision rule: a root-level file always beats a # subfolder file for the same short name — the root is where downloads # land and where the operator curates; a same-name subfolder copy is a # backup, an old edition, or a quarantined reject. Registration only ever # lands files in the root, so an existing ROOT holder that still stats is # only displaced by this new root file, while an existing SUBFOLDER holder # always yields. The routine case — an update replacing an older dated # file the caller just deleted — falls through because the old path no # longer stats. # # Another language holding the name (gutenberg_ale arriving beside # gutenberg_en) is not a collision to lose: as in the scan, the holder # keeps the bare name and this file takes its language name. existing_path = _zim_live_holder(name, path) if existing_path and _zim_lang_key( os.path.basename(existing_path) ) != _zim_lang_key(filename): if not _zim_holder_keeps(existing_path, path): # The scan would give THIS file the bare name and move the holder # to its language name; renaming a served ZIM is the rescan's job. log.info( "ZIM name collision '%s': %s outranks %s, a different language; " "rescanning", loggable(name), loggable(filename), loggable(os.path.basename(existing_path)), ) return False name = _zim_lang_name(filename) existing_path = _zim_live_holder(name, path) if existing_path and _zim_base_name(os.path.basename(existing_path)) == name: # That name is another file's own, never a language name to take. log.info( "ZIM name collision '%s': keeping %s, new %s stays shadowed", loggable(name), loggable(os.path.basename(existing_path)), loggable(filename), ) _note_shadowed(path, existing_path) return True # library correctly unchanged if existing_path and _zim_holder_keeps(existing_path, path): # A root file against a subfolder one, or a richer build in the same # tier: a freshly downloaded mini must never displace the maxi # already being served. log.info( "ZIM name collision '%s': keeping %s, new %s stays shadowed", loggable(name), loggable(os.path.basename(existing_path)), loggable(filename), ) _note_shadowed(path, existing_path) return True # library correctly unchanged # ---- Phase 1: metadata extraction, deliberately WITHOUT _zim_lock ---- entry, archive = _extract_zim_metadata(name, path) if entry.get("entries") == "?": # Unreadable despite the download path's libzim validation — let the # caller run the full-scan fallback rather than splice a broken entry. return False # Source metadata feeds the domain-map merge below; read it here on the # private handle so the merge itself never touches libzim. try: source_meta = ( bytes(archive.get_metadata("Source")).decode("utf-8", "replace").strip() ) except Exception: source_meta = "" # The capture's own address, for a ZIM warc2zim wrote: its main entry path # is the site's address. Read on the same private handle, for the same # reason. try: main_path = archive.main_entry.get_item().path except Exception: main_path = "" # New/Updated stamps, same semantics as load_cache: a new dated filename # of an already-known ZIM inherits the ORIGINAL first_seen and stamps # updated_at (badge reads "Updated"); a genuinely new ZIM derives # first_seen from its own mtime (badge reads "New"). disk_cache = _load_disk_cache() prior_first_seen = None if disk_cache: for _fn, _ce in disk_cache.items(): if _fn == filename or not isinstance(_ce, dict): continue if _zim_short_name(_fn) == name: _fs = _ce.get("first_seen") if _fs is not None and ( prior_first_seen is None or _fs < prior_first_seen ): prior_first_seen = _fs now = time.time() if prior_first_seen is not None: entry["first_seen"] = prior_first_seen entry["updated_at"] = now else: entry["first_seen"] = min(st.st_mtime, now) entry["updated_at"] = None # Disk-cache record, same shape load_cache's scan branch writes. new_cached = { "name": name, "mtime": st.st_mtime, "size": st.st_size, "size_gb": entry["size_gb"], "entries": entry["entries"], "title": entry["title"], "description": entry["description"], "date": entry.get("date", ""), "language": entry.get("language", ""), "has_icon": entry["has_icon"], "main_path": entry["main_path"], } for _opt in ("article_count", "zimi_export", "first_seen", "updated_at"): if entry.get(_opt) is not None: new_cached[_opt] = entry[_opt] removed = {os.path.basename(f) for f in removed_files} swapped = {os.path.normpath(p) for p in removed_paths} # ---- Phase 2: splice under _zim_lock — dict surgery + a small json ---- with _zim_lock: # Rebind fresh containers instead of mutating: readers iterate these # without the lock, and an atomic rebind can never trip them mid-walk. files = dict(_zim_files_cache) replaced = name in files # a file already served this name # Names whose registered file was one of the swapped-out editions. left = { n for n, p in files.items() if n != name and os.path.normpath(p) in swapped } for n in left: del files[n] files[name] = path _zim_files_cache = files # A file's basename is a disk-cache key, so it is only dead when no # surviving file carries it (the same name can live in two folders). kept = {os.path.basename(p) for p in files.values()} removed |= {os.path.basename(p) for p in swapped} - kept listing = [ z for z in (_zim_list_cache or []) if z.get("name") != name and z.get("name") not in left and z.get("file") not in removed ] listing.append(entry) _set_listing(listing) if replaced or left: # The file under a served name changed (replaced in place, or an # edition swapped out): drop every handle still on the old one. release_zim_handles({name} | left) with _archive_lock: # Hand the already-open archive to the pool (and drop any handle # still pointing at a replaced file) so nothing re-opens it. _archive_pool[name] = archive # Invalidates /w/ entry ETags and the interlang resolution caches — # cross-ZIM answers can genuinely change when a ZIM arrives. _cache_generation += 1 # Re-read the disk cache under the lock: the phase-1 copy fed the # stamp inheritance, but a concurrent full load_cache (manage # refresh) may have rewritten the file since — mutate the freshest # version so its work isn't clobbered. def _apply(disk_now): for _fn in list(disk_now): if _fn in removed or _zim_short_name(_fn) == name: disk_now.pop(_fn, None) disk_now[filename] = new_cached return True _update_disk_cache(_apply) # Domain map: merge ONLY this ZIM's domains. The full rebuild # (_build_domain_zim_map) opens every unmapped archive via # get_archive — with a cold pool (e.g. right after a previous # download's cache clear) that re-opens the whole library under this # lock, the same minutes-long starvation this function exists to # remove. Existing entries win, matching the rebuild's first-wins # rule; the map is rebound (not mutated) in interlang, whose # _resolve_url_to_zim is the live consumer. import zimi.interlang as _interlang merged = dict(_interlang._domain_zim_map) for _d, _n in _domain_map_entries_for_zim( name, filename, source_meta, main_path ).items(): merged.setdefault(_d, _n) _interlang._domain_zim_map = merged log.info( "Registered %s (%s entries) without a library rescan", loggable(filename), loggable(entry.get("entries")), ) return True def release_zim_handles(names): """Drop the pooled archive and index handles for these short names. Two callers, for what is one reason on POSIX and two on Windows. unregister_zim_file evicts so that no future read uses a mapping of a file that is gone. The delete route evicts BEFORE it unlinks, because Windows refuses to remove a file that anyone still holds open, and a pooled libzim Archive is exactly that: deleting a ZIM there answered 500 "Failed to delete file" every time. On POSIX the early release changes nothing — unlinking an open file has always worked, the inode simply outlives it. Best effort by construction: a search thread already inside a read holds its own reference, which no eviction can take away. It finishes in milliseconds, and the caller reports the failure honestly if it has not. """ with _archive_lock: for n in names: _archive_pool.pop(n, None) with _suggest_pool_lock: for n in names: _suggest_pool.pop(n, None) _suggest_zim_locks.pop(n, None) with _fts_pool_lock: for n in names: _fts_pool.pop(n, None) _fts_zim_locks.pop(n, None) def _drop_registered(gone, dead_files): """Splice names that left the library out of the live registry: the caches, the pooled handles, the disk-cache rows of ``dead_files`` and the domain map. Rebinds rather than mutates, for the lock-free readers.""" global _zim_files_cache, _zim_list_cache, _cache_generation with _zim_lock: if gone: _zim_files_cache = { n: p for n, p in _zim_files_cache.items() if n not in gone } _set_listing( [z for z in (_zim_list_cache or []) if z.get("name") not in gone] ) # Evict the pooled handles for the deleted files. Dropping them # from the dicts only stops FUTURE use: a search thread already # holding one keeps a valid mapping of an unlinked file until it # finishes, which is why this needs no per-ZIM lock. release_zim_handles(gone) # Invalidates /w/ entry ETags and the interlang resolution caches — # cross-ZIM answers genuinely change when a ZIM leaves. _cache_generation += 1 # Re-read under the lock: a concurrent load_cache may have rewritten # the file since phase 1, so mutate the freshest version. def _apply(disk_now): dropped = [ fn for fn in disk_now if fn in dead_files or _zim_short_name(fn) in gone ] for fn in dropped: disk_now.pop(fn, None) return bool(dropped) _update_disk_cache(_apply) if gone: # Drop this ZIM's domain claims so _resolve_url_to_zim stops # answering with a name that no longer resolves. Rebound, not # mutated, for the same reason as the caches above. import zimi.interlang as _interlang pruned = { d: n for d, n in _interlang._domain_zim_map.items() if n not in gone } _interlang._domain_zim_map = pruned def unregister_zim_paths(paths): """Drop the ZIMs whose REGISTERED file is one of ``paths`` (full paths, a folder another program owns that went away, or a file it removed), from the registry alone: no scan, no archive open. A path that is not what some name is registered under (a same-named file in another folder, a shadowed copy) is none of this function's business. Returns the names dropped.""" _init() if _zim_files_cache is None or _zim_list_cache is None: load_cache() return [] paths = {os.path.normpath(p) for p in paths} current = _zim_files_cache gone = {n for n, p in current.items() if os.path.normpath(p) in paths} if not gone: return [] kept = {os.path.basename(p) for n, p in current.items() if n not in gone} dead = {os.path.basename(current[n]) for n in gone} - kept _drop_registered(gone, dead) log.info("Unregistered %s without a library rescan", ", ".join(sorted(gone))) return sorted(gone) def unregister_zim_file(filename): """Incrementally drop ONE just-deleted ZIM from the live library. The removal counterpart of ``register_zim_file``, and it exists for the same reason: deleting a ZIM used to end in ``load_cache(force=True)`` under ``_zim_lock``, re-opening and re-scanning EVERY archive in the library while holding the one lock every libzim read needs. On a small box serving a big library off network storage that froze search, reading and suggest for the length of the rescan — issue #51's failure mode, on an ordinary button. A removal is strictly cheaper than a registration: nothing has to be read out of a ZIM, so there is no archive to open at all. Phase 1 is one directory listing off the lock; phase 2 is dict surgery under it, and rebinds rather than mutates so the lock-free readers of these caches can never be tripped mid-walk. ``filename`` is the basename of the file the caller already removed from disk. Returns True when the library reflects the removal; False when the reconciliation would need metadata Zimi doesn't have — the caller should fall back to a full ``load_cache(force=True)``. """ global _zim_files_cache, _zim_list_cache, _cache_generation _init() if _zim_files_cache is None or _zim_list_cache is None: # Library was never scanned: a plain load sees the post-delete state # of the directory anyway, and is the cheap normal path. load_cache() return True filename = os.path.basename(filename) # ---- Phase 1: one directory listing, deliberately WITHOUT _zim_lock ---- # _scan_zim_files globs ZIM_DIR and its immediate subfolders. No stat, no # archive open — this is the whole cost of a removal. try: on_disk = _scan_zim_files() except OSError as e: log.warning("unregister_zim_file: cannot scan %s: %s", ZIM_DIR, e) return False current = _zim_files_cache # The splice only handles names LEAVING the library. A name that appeared, # or one whose file changed — a subfolder copy promoted out of the deleted # root file's shadow, per _scan_zim_files' collision rule — needs metadata # that only an archive open can supply, so hand it to the full rescan. for name, path in on_disk.items(): if current.get(name) != path: return False gone = {n for n in current if n not in on_disk} # Disk-cache rows to drop: the deleted file, plus every file backing a name # that left. Safe to match rows by short name here precisely because the # check above proved no surviving file on disk still claims one. dead_files = {filename} | {os.path.basename(current[n]) for n in gone} _drop_registered(gone, dead_files) log.info( "Unregistered %s without a library rescan%s", loggable(filename), loggable(f" ({', '.join(sorted(gone))} left the library)" if gone else ""), ) return True # (HTTP Request Handler extracted to zimi/http.py) # ============================================================================ # CLI & Entry Points (ZimHandler class → zimi/http.py) # ============================================================================ def _cli_die(msg) -> NoReturn: """One-line CLI refusal, exit code 2 — the same convention main() uses for a ConfigError. No traceback: these are operator mistakes, not bugs. Annotated NoReturn so callers can treat it as terminal: without it a type checker reads every `except: _cli_die(...)` branch as falling through, and reports the variable the `try` was binding as possibly unbound.""" print(f"zimi: {msg}", file=sys.stderr) sys.exit(2) def _headless_state_boot(): """Point the state machinery at the resolved paths WITHOUT a running server. Backup-before-upgrade is the whole point of the CLI, so it must work while Zimi is stopped: load_cache() runs _init() (data-dir creation + migrations) and fills the library metadata cache, and the BT prefs path — normally wired up by start_background_services(), which never runs here — is set explicitly so sharing prefs actually reach the bundle.""" from zimi import p2p p2p.set_prefs_path(_bt_prefs_path()) load_cache() def _cli_backup(file_arg): """`zimi backup [FILE]` — write a server-scope bundle (the same payload as GET /manage/backup?scope=server) to a local file.""" from zimi import manage as _manage _headless_state_boot() bundle = _manage._build_backup_bundle(scope="server") path = os.path.abspath(file_arg or time.strftime("zimi-backup-%Y-%m-%d.json")) payload = json.dumps(bundle, ensure_ascii=False, indent=2) try: # 0600 from the first byte: the bundle carries password hashes, so # there must be no window in which another local user can read it. The # explicit chmod covers a pre-existing file — O_CREAT's mode argument # only applies when the file is actually created. fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(payload) os.chmod(path, 0o600) except OSError as e: _cli_die(f"cannot write {path}: {e.strerror or e}") pa = bundle.get("public_access") or {} coll = bundle.get("collections") or {} print(f"Backup written: {path}") print( f" scope: server (schema v{bundle['schema_version']}, " f"zimi {bundle['zimi_version']})" ) print( f" library manifest: {len(bundle.get('library') or [])} ZIM(s) " "(metadata only — ZIM files are re-downloadable, not bundled)" ) print( f" users: {len(bundle.get('users') or {})} account(s), " f"public access: {pa.get('mode', '?')}" ) print( f" collections: {len(coll.get('collections') or {})}, " f"favorites: {len(coll.get('favorites') or [])}" ) print( " settings: download schedule, auto-update, sharing prefs, " f"{len(bundle.get('seed_intents') or {})} seed intent(s), " f"{len(bundle.get('hot_zims') or [])} hot ZIM(s)" ) print( f" history: {len(bundle.get('history') or [])} event(s), " f"per-user data: {len(bundle.get('user_data') or {})} user(s)" ) print( "Note: this bundle includes user password hashes; " "file mode is 0600 — keep it private." ) def _cli_restore(path, overwrite): """`zimi restore FILE [--overwrite]` — apply a bundle with the same merge/overwrite semantics as POST /manage/backup. Headless and ungated: whoever can run the CLI against the data dir already owns it.""" from zimi import manage as _manage try: with open(path, encoding="utf-8") as f: data = json.load(f) except FileNotFoundError: _cli_die(f"backup file not found: {path}") except IsADirectoryError: _cli_die(f"not a file: {path}") except (json.JSONDecodeError, UnicodeDecodeError): _cli_die(f"not a valid backup (malformed JSON): {path}") except OSError as e: _cli_die(f"cannot read {path}: {e.strerror or e}") # The HTTP route tolerates a missing schema key (hand-assembled payloads); # the CLI does not — a stray JSON file (say, zimi.json) fed to `restore` # must refuse outright, not half-apply. if not isinstance(data, dict) or data.get("schema") != _manage._BACKUP_SCHEMA: _cli_die(f"not a Zimi backup bundle: {path}") _headless_state_boot() result, err = _manage._apply_backup_bundle(data, overwrite=overwrite) # `result is None` is the same condition as `err` in every current path # (_apply_backup_bundle returns (None, err) on refusal), but the two are # independent values — checking both is what makes the reads below safe # rather than merely correct-by-convention. if err or result is None: _cli_die(f"restore failed: {err or 'no result'}") applied = result["applied"] # Present-but-untouched keys: env-locked settings (ZIMI_HOT_ZIMS, # ZIMI_AUTO_UPDATE) or server keys riding on a device-scope bundle, which # the plan deliberately strips. Saying so beats a silent partial restore. skipped = [k for k in _manage._BUNDLE_STATE_KEYS if k in data and k not in applied] preview = result["preview"] print( f"Restored from {path} (scope: {preview['scope']}, " f"mode: {'overwrite' if overwrite else 'merge'})" ) print(" applied: " + (", ".join(applied) if applied else "nothing (empty bundle)")) if skipped: print(" skipped: " + ", ".join(skipped)) missing = preview.get("missing_zims") if missing: print( f" note: {missing} ZIM(s) in the bundle's library manifest are not " "installed; re-download them from the catalog" ) # The first-run banner is drawn in box characters, and a console that cannot # encode one raises rather than substituting it. Windows redirects stdout at # the locale encoding (cp1252, no box drawing), so on Windows the very first # `zimi serve > log.txt` — the run where no password is set and the setup key # has to be shown — died with UnicodeEncodeError before it ever reached READY. _BANNER_ASCII = {"┌": "+", "└": "+", "─": "-", "│": "|"} def _stdio_takes(text, stream=None): """Whether this stream can represent `text` at its own encoding.""" stream = stream if stream is not None else sys.stdout encoding = getattr(stream, "encoding", None) or "utf-8" try: text.encode(encoding) except (UnicodeEncodeError, LookupError): return False return True def _printable(text): """The same banner in characters this console will actually take.""" if _stdio_takes(text): return text for drawn, plain in _BANNER_ASCII.items(): text = text.replace(drawn, plain) return text def _make_stdio_resilient(): """No character in any message may ever kill the server. _printable keeps the banner legible; this is the layer under it, for the log line, the traceback, and the message nobody thought about. Only the error handler changes, never the encoding: a console that asked for cp1252 still gets cp1252, and an unrepresentable character arrives as an escape rather than as an exception.""" for stream in (sys.stdout, sys.stderr): encoding = (getattr(stream, "encoding", "") or "").lower().replace("-", "") if encoding in ("utf8", "utf8mb3", "utf8mb4"): continue try: stream.reconfigure(errors="backslashreplace") except (AttributeError, OSError, ValueError): pass def _add_mcp_args(p): """The flags of `zimi mcp`, which `zimi-mcp` takes as its own.""" p.add_argument( "zim_dir", nargs="?", default=None, help="Directory containing *.zim files (overrides ZIM_DIR; default: found as serve finds it)", ) p.add_argument( "--tools", default=None, help=( "lean: search, read, read_section (default); full: every tool; or a comma " "list of tool names, e.g. search,read,list_entries or lean,list_entries. " "A named set fixes its tools' flavour; a bare name alone is the full tool " "(overrides ZIMI_MCP_TOOLS)" ), ) p.add_argument("--data-dir", default=None, help="Directory for Zimi's own state") p.add_argument("--config", default=None, help="Path to a JSON config file") def _resolve_boot(args): """Fold the flags, the env and the config file into the globals, as every subcommand needs before it reads a path. Returns (settings, config_path, data_dir_problem); the problem is set only for `zimi config`, which reports it instead of exiting.""" # Before anything can read a path: argparse runs long after the module-level # env read, so the flags (and the config file, which only argparse can point # us at) have to be folded back into the globals here. Done for every # subcommand, not just `serve`, so one file describes the whole instance — # with no config file present this resolves to exactly today's values. # getattr with a default: only `serve` and `config` carry these flags, and # the rest of the subcommands still want the file's zim_dir/data_dir. if getattr(args, "portable", False): os.environ["ZIMI_PORTABLE"] = ( "1" # one switch, read by portable_root() wherever paths resolve ) # `zimi serve /path/to/zims` is `--zim-dir /path/to/zims` (as `zimi mcp DIR` is). given = getattr(args, "dir_arg", None) if given: if getattr(args, "zim_dir", None) and os.path.abspath( args.zim_dir ) != os.path.abspath(given): print( f"zimi: {given} and --zim-dir {args.zim_dir} name different folders; give one", file=sys.stderr, ) sys.exit(2) args.zim_dir = given flags = { k: getattr(args, k, None) for k in ("zim_dir", "data_dir", "host", "port", "config") } # The one impure discovery probe, shared by every resolution below so all # of them agree on the same answer. Cheap (a few globs), and inert unless # zim_dir would otherwise fall to the hardcoded default. discovered = discover_zim_dir() try: config, config_path = load_config( flags["zim_dir"], flags["data_dir"], flags["config"], discovered_zim_dir=discovered, ) settings = resolve_settings( zim_dir_flag=flags["zim_dir"], data_dir_flag=flags["data_dir"], host_flag=flags["host"], port_flag=flags["port"], config=config, config_path=config_path, discovered_zim_dir=discovered, ) except ConfigError as e: print(f"zimi: {e}", file=sys.stderr) sys.exit(2) # Hand the file's answer to the modules that own each setting, before any of # them is asked for it. Done for every subcommand: `backup` and `restore` # have to see the same instance `serve` would. apply_env_settings(settings) apply_data_paths( flags["zim_dir"], flags["data_dir"], config=config, discovered_zim_dir=discovered, ) # Read-only media check, up front for every subcommand: an explicitly # configured unwritable data dir is an operator mistake (one line, exit 2, # same convention as ConfigError), while an unwritable DERIVED default # reroutes to the per-library cache dir — and `zimi config` must report # the reroute as the provenance of the value actually in effect. # # EXCEPT `zimi config` itself: it is the diagnostic you reach for to debug # exactly this misconfiguration, so it must never refuse to print. It # reports the problem beneath the table instead of dying above it. data_dir_problem = None try: _ensure_writable_data_dir() except DataDirError as e: if args.command == "config": data_dir_problem = str(e) else: print(f"zimi: {e}", file=sys.stderr) sys.exit(2) if _data_dir_fallback_from: settings["data_dir"] = ( ZIMI_DATA_DIR, f"fallback: {_data_dir_fallback_from} not writable", ) return settings, config_path, data_dir_problem def _run_mcp(args, settings): """Serve MCP on stdio: `zimi mcp` and `zimi-mcp`.""" try: from zimi import mcp_server as _mcp_server except SystemExit: print( "zimi mcp needs the MCP package: pip install 'zimi[mcp]'", file=sys.stderr, ) sys.exit(1) _mcp_server.run( _mcp_server.tools_setting(args.tools or settings["mcp_tools"][0], "lean") ) def mcp_main(argv=None): """`zimi-mcp [ZIM_DIR] [--tools TOOLS]`: `zimi mcp` as a command of its own, the entry point of the zimi-mcp package. It builds no other subcommand's parser, so nothing outside the search-and-read core loads.""" _make_stdio_resilient() parser = argparse.ArgumentParser( prog="zimi-mcp", description="Zimi's MCP server on stdio: search and read ZIM files offline.", ) parser.add_argument( "--version", action="version", version=f"zimi-mcp {ZIMI_VERSION}" ) _add_mcp_args(parser) args = parser.parse_args(argv) args.command = "mcp" settings, _config_path, _problem = _resolve_boot(args) _run_mcp(args, settings) def main(): _make_stdio_resilient() parser = argparse.ArgumentParser(description="ZIM Knowledge Base Reader") sub = parser.add_subparsers(dest="command") p_search = sub.add_parser("search", help="Full-text search across ZIM files") p_search.add_argument("query", help="Search query") p_search.add_argument("--limit", type=int, default=5) p_search.add_argument("--zim", help="Search specific ZIM only") p_read = sub.add_parser("read", help="Read an article") p_read.add_argument("zim", help="ZIM short name") p_read.add_argument("path", help="Article path within ZIM") p_read.add_argument("--max-length", type=int, default=MAX_CONTENT_LENGTH) p_suggest = sub.add_parser("suggest", help="Title autocomplete") p_suggest.add_argument("query") p_suggest.add_argument("--zim", help="Specific ZIM") p_suggest.add_argument("--limit", type=int, default=10) sub.add_parser("list", help="List available ZIM files") # MCP over stdio and nothing else: no web server, no port, no BitTorrent, # mDNS, catalog or index builds. The ZIM directory is the one argument # most people need, so it is positional; everything else resolves the way # `serve` resolves it (env, config file, discovery). p_mcp = sub.add_parser( "mcp", help="Serve MCP on stdio for AI agents (no web server)" ) _add_mcp_args(p_mcp) # Every path/bind flag defaults to None, not to its real default: that is # how resolve_settings tells "flag omitted" (fall through to env, then the # config file) from "flag given". Shared by `serve` and `config` so the # latter reports exactly what the former would boot with. def add_boot_flags(p): p.add_argument( "--port", type=int, default=None, help=f"Port to bind (overrides ZIMI_PORT, default: {DEFAULT_PORT})", ) p.add_argument( "--zim-dir", default=None, help=f"Directory containing *.zim files (overrides ZIM_DIR, default: {DEFAULT_ZIM_DIR})", ) p.add_argument( "--data-dir", default=None, help=f"Directory for Zimi's own state (overrides ZIMI_DATA_DIR, default: /{DEFAULT_DATA_DIR_NAME})", ) p.add_argument( "--host", default=None, help=f"Address to bind (default: {DEFAULT_HOST})", ) p.add_argument( "--portable", action="store_true", help=f"Keep state in /{PORTABLE_DATA_NAME} beside the executable (automatic when that folder exists)", ) p.add_argument( "--config", default=None, help=f"Path to a JSON config file (overrides {CONFIG_ENV_VAR}, default: /{CONFIG_FILENAME} if present)", ) p_serve = sub.add_parser("serve", help="Start HTTP API server") p_serve.add_argument( "dir_arg", metavar="DIR", nargs="?", default=None, help="Directory containing *.zim files, the same as --zim-dir: `zimi serve /path/to/zims`", ) add_boot_flags(p_serve) p_serve.add_argument( "--ui", action="store_true", help="Open in a native desktop window (requires pywebview)", ) p_serve.add_argument( "-d", "--daemon", action="store_true", help="Run in the background, with zimi.pid and zimi.log in the data directory", ) p_config = sub.add_parser( "config", help="Print the resolved configuration and where each value came from" ) add_boot_flags(p_config) # backup/restore take the same boot flags as serve/config so they operate # on exactly the paths a `serve` with the same arguments would use — the # point is backing up the RIGHT instance, not whichever one env defaults # happen to name. p_backup = sub.add_parser( "backup", help="Write a full-server backup bundle (users, access policy, " "settings, collections) to a JSON file", ) p_backup.add_argument( "file", nargs="?", default=None, help="Output path (default: ./zimi-backup-.json)", ) add_boot_flags(p_backup) p_restore = sub.add_parser( "restore", help="Apply a backup bundle (merges by default)" ) p_restore.add_argument("file", help="Backup bundle (JSON) to apply") p_restore.add_argument( "--overwrite", action="store_true", help="Replace matching state wholesale instead of merging", ) add_boot_flags(p_restore) # create takes the boot flags for the same reason backup/restore do: the # default output directory is THIS instance's ZIM dir, resolved exactly # the way `serve` would resolve it. # The crawl defaults belong to the crawler, and the help text has to show # them, so they are read from it rather than restated here. Import cost is # stdlib-only and the module is loaded for `zimi create` regardless. from zimi import crawler as _crawler p_create = sub.add_parser( "create", help="Create a ZIM from a folder of files (HTML/Markdown/PDF), from a " "single web page, or from a bounded crawl of one site (--site)", ) # Repeatable: several URLs are ONE ZIM holding all of those pages plus a # generated index. One source keeps every existing behaviour exactly — # folder, single page, --site crawl, video URL — because one page is one # page and wrapping it in an index nobody asked for is a worse ZIM. p_create.add_argument( "source", nargs="*", help="Folder path, a subreddit (r/kiwix), or one or more http(s):// URLs (several URLs are " "captured into a single ZIM with an index page). Optional only with --setup-reddit.", ) p_create.add_argument( "--title", default=None, help="ZIM title (default: folder name / page title)" ) p_create.add_argument("--description", default=None, help="ZIM description") p_create.add_argument( "--language", default=None, help="ISO 639-3 content language for metadata and the full-text index. " "Default: read it off the source — the page's own lang attribute, a " "folder's HTML, the platform's video metadata — falling back to eng " "when the source declares nothing", ) p_create.add_argument( "--creator", default=None, help="Author metadata (default: the stored default, else Zimi)", ) p_create.add_argument( "--publisher", default=None, help="Publisher metadata (default: the stored default, else Zimi)", ) p_create.add_argument( "--tags", default=None, metavar="A;B", help="Tags added to the ZIM's own, separated by semicolons", ) p_create.add_argument( "--only", nargs="+", default=None, metavar="PATH", help="Folder only: package just these files and subfolders (paths " "inside the folder) rather than all of it", ) p_create.add_argument( "--out", default=None, help="Explicit output .zim path (default: the ZIM directory, with " "library registration)", ) # Crawl flags. Every one of them defaults to None rather than to its real # default so the CLI can tell "the user asked for this" from "nobody # said" — that difference is what lets a flag that only applies to a # site crawl be refused instead of silently ignored, and what keeps a # flag Zimi guessed at from being sent to another engine. p_create.add_argument( "--setup-reddit", action="store_true", help="Install the Reddit maker (ArcticZim) into its sidecar now, while " "connected, so a subreddit can be made offline later", ) p_create.add_argument( "--site", action="store_true", help="Capture a bounded same-origin crawl instead of a single page", ) p_create.add_argument( "--engine", choices=("builtin", "rendered", "alive", "singlefile", "zimit"), default=None, help="Capture engine (default: the stored default, else builtin): " "builtin (no JavaScript, no install), rendered " "(runs a headless Chromium in this process — needs " "`pip install 'zimi[browser]'` and `playwright install chromium`), " "alive (records the browser session to a web archive and converts it " "with warc2zim, so the saved site's JavaScript still runs — needs the " "browser above plus `zimi import --setup`), or zimit (openZIM's " "browser-based crawler, needs docker)", ) # On by default for the two browser engines, and the pair of flags exists # so "nobody said" stays distinguishable from "somebody asked for it" — # which is what lets --block-ads against the fast engine, where it would do # nothing, be refused rather than quietly accepted. p_create.add_argument( "--block-ads", dest="block_ads", action="store_true", default=None, help="Refuse ad, tracker and consent-manager requests while capturing " "(--engine rendered/alive; on by default). Smaller ZIMs, and pages " "that gate themselves on those endpoints render their real content", ) p_create.add_argument( "--no-block-ads", dest="block_ads", action="store_false", help="Capture every request the page makes, advertising included", ) p_create.add_argument( "--max-pages", type=int, default=None, help=f"Pages to capture at most; 0 for no limit (--site default: {_crawler.DEFAULT_MAX_PAGES})", ) p_create.add_argument( "--max-depth", type=int, default=None, help="Link hops from the starting page " f"(--site default: {_crawler.DEFAULT_MAX_DEPTH})", ) # Which pages a --site capture walks into. browsertrix's names, so a zimit # command translates one to one (all substance in crawler.CrawlScope). p_create.add_argument( "--scope", choices=_crawler.SCOPES, default=None, help="Pages a --site capture visits: prefix (the start page's section, " "the default), host (the whole site), domain (the site and its " "subdomains) or any (wherever links lead; depth bounds it)", ) p_create.add_argument( "--include", action="append", default=None, metavar="REGEX", help="Also capture pages whose URL matches, repeatable (--site only)", ) p_create.add_argument( "--exclude", action="append", default=None, metavar="REGEX", help="Never capture pages whose URL matches, repeatable; wins over " "--scope and --include (--site only)", ) p_create.add_argument( "--extra-hops", type=int, default=None, help="Follow links out of scope this many pages further (--site only; " f"0-{_crawler.MAX_EXTRA_HOPS})", ) # How a --site capture presents itself and when it stops. The table that # says what each means and which engines honor it is crawler.CAPTURE_OPTIONS. p_create.add_argument( "--time-limit", default=None, metavar="DURATION", help="Stop crawling after this long and keep what is captured: 90m, 8h, " "or seconds (--site only)", ) p_create.add_argument( "--sitemap", nargs="?", const=True, default=None, metavar="URL", help="Also visit the pages a sitemap lists: bare, the one named in " "robots.txt or /sitemap.xml; or give its address (--site only)", ) p_create.add_argument( "--no-sitemap", dest="sitemap", action="store_const", const=False, help="Do not read a sitemap, whatever the stored default says", ) p_create.add_argument( "--user-agent", default=None, metavar="STRING", help="The User-Agent to present instead of Zimi's own (--site only)", ) p_create.add_argument( "--mobile", action=argparse.BooleanOptionalAction, default=None, help="Capture as a phone: a mobile user agent, and with a browser " "engine a 390px touch screen (--site only)", ) p_create.add_argument( "--page-timeout", default=None, metavar="SECONDS", help="How long a browser engine waits for one page (--site only; " "--engine rendered, alive or zimit)", ) p_create.add_argument( "--cookies", default=None, metavar="COOKIES", help="Cookies to send, as a Cookie header copied from your browser's " 'developer tools: "a=1; b=2". Sent only to the page\'s own host and its ' "subdomains, never stored or written down (--site only; not zimit or " "singlefile)", ) p_create.add_argument( "--skip", dest="skip_types", default=None, metavar="KINDS", help="Kinds of file to leave out, separated by commas: " "video,audio,pdf,archives,images (--site only; not singlefile)", ) p_create.add_argument( "--max-file-size", dest="max_file_bytes", default=None, metavar="SIZE", help="Leave out any one file larger than this, e.g. 50M (--site only; " "not singlefile)", ) p_create.add_argument( "--workers", default=None, metavar="N", help="Pages fetched at once, 1 to 16 (--site only; --engine zimit)", ) # Video-source flags (playlist/channel URLs; all substance in zimi/video.py). p_create.add_argument( "--format", default=None, help="Video sources: yt-dlp format selector (default: ~720p cap)", ) p_create.add_argument( "--audio-only", action="store_true", help="Video sources: keep audio only", ) p_create.add_argument( "--limit", type=int, default=None, help="Video sources: package at most N playlist/channel entries", ) p_create.add_argument( "--max-bytes", default=None, help="Total size budget, e.g. 512MiB or 4G; 0 for no limit. For --site: pages plus " f"assets (default {_crawler.DEFAULT_MAX_BYTES // 1000**3}G); for " "video sources: total media (default 16G)", ) p_create.add_argument( "--delay", type=float, default=None, help="Seconds to wait between page requests; robots.txt Crawl-delay " f"wins when it asks for more (--site default: {_crawler.DEFAULT_DELAY})", ) p_create.add_argument( "--ignore-robots", action="store_true", help="Crawl pages robots.txt disallows (--site only; prints a warning)", ) p_create.add_argument( "--engine-arg", action="append", default=None, metavar="ARG", help="Extra argument passed straight to the engine, repeatable " "(--engine zimit only). Write it attached — --engine-arg=--workers=2 " "— because argparse reads a bare flag-shaped value as a missing one", ) add_boot_flags(p_create) p_import = sub.add_parser( "import", help="Convert a web archive (.warc/.warc.gz/.wacz) into a library " "ZIM via the warc2zim sidecar", ) p_import.add_argument( "file", nargs="?", default=None, help="Web archive to convert" ) p_import.add_argument( "--name", default=None, help="ZIM name (default: derived from the filename)" ) p_import.add_argument("--title", default=None, help="ZIM title") p_import.add_argument("--description", default=None, help="ZIM description") p_import.add_argument("--creator", default=None, help="Author metadata") p_import.add_argument("--publisher", default=None, help="Publisher metadata") p_import.add_argument( "--tags", default=None, metavar="A;B", help="Tags, separated by semicolons" ) p_import.add_argument( "--out", default=None, help="Explicit output .zim path (default: the ZIM directory, with " "library registration)", ) p_import.add_argument( "--status", action="store_true", help="Report the warc2zim sidecar's state and version", ) p_import.add_argument( "--setup", action="store_true", help="Install the warc2zim sidecar venv now (network; pre-seeds " "offline machines)", ) add_boot_flags(p_import) sub.add_parser( "desktop", help="Start server and open in a native desktop window (requires pywebview)", ) p_doctor = sub.add_parser( "doctor", help="Which optional features this install has, and how to get the rest", ) p_doctor.add_argument( "--check", action="store_true", help="Exit 1 when a feature this kind of install should include is missing", ) p_doctor.add_argument( "--kind", choices=("docker", "desktop", "portable", "pip"), help=argparse.SUPPRESS, ) add_boot_flags(p_doctor) p_check = sub.add_parser( "check", help="Is a ZIM well formed: checksum, metadata, icon, redirects, links" ) p_check.add_argument("files", nargs="+", metavar="FILE", help="the .zim files to check (a split book: its .zimaa)") p_check.add_argument( "--quick", action="store_true", help="skip the checksum and the link scan" ) p_service = sub.add_parser( "service", help="The systemd unit that runs Zimi at boot (Linux)" ) p_service.add_argument( "action", choices=("print", "install"), help="print the unit, or install it for systemd", ) p_service.add_argument( "--to", help="where install writes it (default /etc/systemd/system/zimi.service)", ) args = parser.parse_args() if args.command == "service": from zimi import service as _service return _service.cli_service(args) if args.command == "check": from zimi import zimcheck as _zimcheck return _zimcheck.cli_check(args) settings, config_path, data_dir_problem = _resolve_boot(args) host = settings["host"][0] port = settings["port"][0] if args.command == "config": print(format_config_report(settings)) if data_dir_problem: # Diagnosis, not death: the whole point of this command is seeing # the resolution that a failing serve/backup would die over. print(f"\nwarning: {data_dir_problem}") if not config_path: # The most common config-file support question is "why is my file # not being read", and the answer is nearly always that it is not # where Zimi looked. print( f"\nno config file in use (looked for {os.path.join(ZIMI_DATA_DIR, CONFIG_FILENAME)})" ) elif args.command == "search": results = search_all(args.query, limit=args.limit, filter_zim=args.zim) print(json.dumps(results, indent=2, ensure_ascii=False)) elif args.command == "read": result = read_article(args.zim, args.path, max_length=args.max_length) if "error" in result: print(json.dumps(result, indent=2), file=sys.stderr) sys.exit(1) # Print content directly for LLM consumption print(f"# {result['title']}") print(f"Source: {result['zim']} / {result['path']}") if result["truncated"]: print(f"(Showing {args.max_length} of {result['full_length']} chars)") print() print(result["content"]) elif args.command == "suggest": results = suggest(args.query, zim_name=args.zim, limit=args.limit) print(json.dumps(results, indent=2, ensure_ascii=False)) elif args.command == "mcp": _run_mcp(args, settings) elif args.command == "list": load_cache() zims = list_zims() for z in zims: entries = z["entries"] if isinstance(z["entries"], int) else 0 print( f" {z['name']:40s} {format_bytes(z['size_bytes']):>10s} " f"{entries:>10} entries ({z['file']})" ) elif args.command == "backup": _cli_backup(args.file) elif args.command == "restore": _cli_restore(args.file, args.overwrite) elif args.command == "create": from zimi import creator as _creator _init() # installed add-ons onto PATH and sys.path before the capture looks for its browser or yt-dlp _creator.cli_create(args) elif args.command == "doctor": from zimi import runtimes as _runtimes _runtimes.cli_doctor(args) elif args.command == "import": from zimi import importer as _importer _init() # the warc2zim add-on's sidecar and uv, found the same way _importer.cli_import(args) elif args.command == "desktop" or (args.command == "serve" and args.ui): # Inside the package since 1.10: a pip install has it. pywebview is # the one thing it needs that the package does not require. try: import webview # noqa: F401 except ImportError: print( "Desktop mode needs pywebview: pip install 'zimi[desktop]'", file=sys.stderr, ) sys.exit(1) from zimi.desktop import main as desktop_main desktop_main() elif args.command == "serve": if getattr(args, "daemon", False): from zimi import service as _service _service.daemonize(ZIMI_DATA_DIR, host, port) print(f"ZIM Reader API starting on port {port}") print(f"ZIM directory: {ZIM_DIR}") # Asked before the first scan writes one: whether this install ran # before, for the first-run page (manage.init_setup_gate). ran_before = any( os.path.exists(p) for p in (_cache_file_path(), os.path.join(ZIM_DIR, ".zimi_cache.json")) ) load_cache() from zimi import libfolders libfolders.ensure_watch() # Startup partial-download sweep. Keep partials that a download record # still wants (resume_pending_downloads() picks those up via Range). # For the rest (orphaned), auto-delete only the stale ones (>24h) — a # recent orphaned partial is left in place so the user can re-add it and # resume; the interactive "clean up" action can clear it on demand. from zimi import library as _lib _protected, _orphaned = _lib.classify_partials() for info in _protected: log.info("Partial download found (resumable): %s", info["filename"]) for info in _orphaned: if info["age_hours"] * 3600 <= 86400: log.info("Partial download found (orphaned): %s", info["filename"]) continue try: os.remove(os.path.join(ZIM_DIR, info["filename"])) log.info("Cleaned up stale partial download: %s", info["filename"]) except OSError: pass warm_indexes() start_background_services(port) # Start auto-update thread if enabled global _auto_update_thread if _auto_update_enabled: import random as _rand_mod _auto_update_thread = threading.Thread( target=_auto_update_loop, # Jittered first check: a fleet booting together (power # restored, coordinated deploy) must not stampede Kiwix # with simultaneous catalog fetches at startup. kwargs={"initial_delay": int(_rand_mod.uniform(60, 900))}, daemon=True, ) _auto_update_thread.start() print("Endpoints: /search, /read, /suggest, /list, /health") if ZIMI_MANAGE: from zimi import manage as _mng_open if os.environ.get("ZIMI_MANAGE_EXTERNAL") is not None: # Deprecated with the outside switch: whether a visitor is # outside is a guess a reverse proxy breaks. Still honoured, so # an operator's 0 does not quietly open settings to the web. log.warning( "ZIMI_MANAGE_EXTERNAL (manage_external) is deprecated and will " "be removed: keep /manage/ off the internet at your proxy " "instead. It still applies for now." ) if _mng_open.manage_open(): # Never quietly. A switch that turns authentication off has to # be visible in the log of anyone who inherits this instance, # and the banner is where a person looks when they wonder why # nothing asked them for a password. log.warning( "Library management is OPEN: no password, no setup key, " "anyone who can reach this server can administer it " "(Settings > Access > Managing Zimi, or manage_open / " "ZIMI_MANAGE_OPEN). Turn it off if this " "instance is reachable from anywhere you do not control." ) elif _get_manage_password_hash(): log.info("Library management enabled (password protected)") elif _mng_open.access_mode() == "lan": log.info("Library management enabled: anyone on the local network") else: # Nobody has said who can change settings. This machine may say # so freely; any other device needs the setup key below # (GHSA-5mw2-53vv-9pw6). A fresh install opens only once it is # answered. gated = _mng_open.init_setup_gate(host, ran_before=ran_before) key = _mng_open.ensure_setup_key() log.info("Library management enabled — no admin password set yet.") first = ( " │ Zimi opens once you choose who can manage it.\n" if gated else " │ Choose who can manage Zimi from this machine,\n" ) print( _printable( "\n" " ┌─ Zimi first-run setup ──────────────────────────────\n" + first + " │ Open Zimi on this machine, or on another device\n" " │ with this one-time setup key:\n" " │\n" f" │ SETUP KEY: {key}\n" " │\n" " │ (also saved to the setup-key file in the data dir;\n" " │ it stops working once setup is done)\n" " └─────────────────────────────────────────────────────\n", ), flush=True, ) from zimi import sso as _sso _sso.log_boot_state() # docker stop / systemd / CI teardown send SIGTERM, which by default # kills Python without running atexit — skipping the clean engine # shutdown that flushes fastresume + the final upload accounting. # Route it through sys.exit so cleanup handlers run. import signal signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) server = ZimiHTTPServer((host, port), ZimHandler) # Emit READY so wrapper scripts (CI smoke tests, the # desktop launcher) can capture the bound port — important when # --port 0 is used to let the OS pick a free port. actual_port = server.server_address[1] announce_ready(actual_port) # The Creator pane's engines (a browser launch, two sidecars) are # found out in the background, so the first look at that pane is not # "Checking…" for as long as a browser takes to start. After READY # and after a pause, never before: it launches Chromium, and boot is # the one moment nothing else should be competing for the machine # (it pushed READY past 30s on a loaded one). def _probe_engines_later(): time.sleep(_CREATOR_PROBE_DELAY_S) try: from zimi import manage as _manage_boot _manage_boot._creator_capabilities() except Exception: pass threading.Thread( target=_probe_engines_later, daemon=True, name="creator-probe-boot" ).start() try: server.serve_forever() except KeyboardInterrupt: pass finally: _suggest_cache_persist() log.info("Suggest cache saved to disk") else: parser.print_help() # ============================================================================ # Hot ZIM cache (Pro feature) # # Hot ZIMs are pre-warmed at startup; cold ones stay lazy. Targets users with # 1000+ ZIMs who want fast searches against a small frequently-used subset. # # Source priority: # 1. ZIMI_HOT_ZIMS env var (csv) — overrides file # 2. ZIMI_DATA_DIR/hot.json — persistent across restarts # 3. empty — fall back to existing warm-everything # ============================================================================ _HOT_ZIMS_FILENAME = "hot.json" def _hot_zims_file(): return os.path.join(ZIMI_DATA_DIR, _HOT_ZIMS_FILENAME) def _parse_hot_csv(raw): """Split a comma-separated env value into a clean list of names.""" return [item.strip() for item in raw.split(",") if item.strip()] def get_hot_zims(): """Names of ZIMs configured as hot, in priority order. Never raises.""" raw = os.environ.get("ZIMI_HOT_ZIMS") if raw is not None: return _parse_hot_csv(raw) path = _hot_zims_file() if os.path.exists(path): try: with open(path, encoding="utf-8") as f: data = json.load(f) if isinstance(data, list): return [s for s in data if isinstance(s, str) and s] except (OSError, json.JSONDecodeError): log.warning("hot.json corrupt or unreadable; treating as empty") return [] def set_hot_zims(names): """Persist the hot-ZIMs list to ZIMI_DATA_DIR/hot.json. Atomic. Validates: every entry must be a string. Duplicates are dropped while preserving first-seen order. """ if not isinstance(names, list): raise TypeError("names must be a list of strings") seen = set() deduped = [] for n in names: if not isinstance(n, str): raise TypeError(f"hot-zim name must be string, got {type(n).__name__}") if not n or n in seen: continue seen.add(n) deduped.append(n) os.makedirs(ZIMI_DATA_DIR, exist_ok=True) _atomic_write_json(_hot_zims_file(), deduped) log.info("hot.json updated: %d ZIM(s)", len(deduped)) # Long enough that a boot, its index warm-up and the first page are done # with the machine before a browser is launched to see whether one exists. _CREATOR_PROBE_DELAY_S = 20 def warm_indexes(): """Pre-warm indexes for fast first queries. Called by serve() at startup and by mcp_server.py on init. Eager Archive pre-warm is gated on a non-empty hot list (env `ZIMI_HOT_ZIMS` or `hot.json`). With no hot list — the default for fragile / lightweight hosts — Archive handles open lazily on first use. Search itself is unaffected: title indexes are SQLite, not libzim, and the startup worker still builds them. The lazy default keeps peak startup memory bounded regardless of ZIM count; users with beefy hosts can opt back in by populating hot.json. """ zims = get_zim_files() hot = get_hot_zims() names_to_warm = [] if hot: # Validate every named hot ZIM exists; warn on misses. unknown = [h for h in hot if h not in zims] if unknown: log.warning("Hot ZIMs not found in library: %s", ", ".join(unknown)) names_to_warm = [h for h in hot if h in zims] log.info( "Pre-warming %d hot archive(s) of %d total (cold ZIMs stay lazy)", len(names_to_warm), len(zims), ) for name in names_to_warm: try: get_archive(name) except Exception as e: log.warning("Skipping %s: %s", name, e) log.info("Hot archives ready") else: log.info( "%d ZIM(s) registered; archives open lazily on first use " "(set ZIMI_HOT_ZIMS to pre-warm)", len(zims), ) # Single sequential startup worker. Five parallel fan-out threads (with a # ThreadPoolExecutor inside one of them) used to open Archive handles for # every ZIM concurrently, blowing memory on weak hosts. We now run the # phases in order on one daemon thread — peak memory at startup is one # Archive handle plus one SQLite tmp instead of N×5 mmaps. def _startup_worker(): # Phase 1: build/refresh title indexes (one Archive open at a time). try: _build_all_title_indexes() except Exception as e: log.warning("Title index build phase failed: %s", e) # Phase 1b: ZimiTube's video details (descriptions, channels, dates # kept in a file per video), so they are read before anyone opens # ZimiTube rather than when someone does. Before the Q-ID phase, # which can take hours on a big Wikipedia. try: from zimi import tube as _tube _tube.build_all_details() except Exception as e: log.warning("ZimiTube details phase failed: %s", e) # Phase 1c: Bookshelf's book records (authors' years, subjects, the # day each book came to Gutenberg), read from each book's head. Half # an hour for all of English Gutenberg on a NAS; the shelf opens # without them and gains eras and subjects when they are there. try: if bundled("books"): from zimi import books as _books _books.build_all_details() except Exception as e: log.warning("Bookshelf details phase failed: %s", e) # Phase 1d: the towns on each Kiwix map, read from its tiles, so a # town its search pages leave out is found by name. try: from zimi import mapplaces as _mapplaces _mapplaces.build_all() except Exception as e: log.warning("Map places phase failed: %s", e) # Phase 1e: the documents of each PDF collection (titles from its # listing, the PDFs' text), so a search finds a factsheet by its words. try: from zimi import docindex as _docindex _docindex.build_all() except Exception as e: log.warning("Document index phase failed: %s", e) # Phase 2: build/refresh Q-ID indexes (one Archive open at a time). try: _build_all_qid_indexes() except Exception as e: log.warning("Q-ID index build phase failed: %s", e) # Phase 3: warm suggestion indexes for hot ZIMs only. With no hot # list, suggest archives open lazily on first /suggest call — # paying the open once per ZIM at first use is cheaper than # holding N libzim mmaps continuously. if hot: try: zim_files = get_zim_files() targets = {n: zim_files[n] for n in names_to_warm if n in zim_files} warmed = 0 for name, path in targets.items(): _wait_until_idle() # a person opening something goes first try: _get_suggest_archive(name) archive = open_archive(path) try: ss = SuggestionSearcher(archive) s = ss.suggest("a") result_paths(s, 0, 1) finally: del archive warmed += 1 except Exception as e: log.debug("Failed to warm suggest index for %s: %s", name, e) log.info("Suggestion indexes warmed: %d/%d", warmed, len(targets)) except Exception as e: log.warning("Suggest warm phase failed: %s", e) # Phase 4: warm FTS archive pool — hot list only, same rationale. if hot: try: for name in names_to_warm: _wait_until_idle() try: _get_fts_archive(name) except Exception as e: log.debug("Failed to warm FTS archive for %s: %s", name, e) log.info("FTS pool warmed: %d archives", len(_fts_pool)) except Exception as e: log.warning("FTS warm phase failed: %s", e) # Phase 5: warm title-index SQLite B-trees (no Archive opens — cheap). try: zim_files = get_zim_files() opened = 0 for name in zim_files: conn = _get_title_db(name) if conn is not None: try: for prefix in ("a", "m", "s"): conn.execute( "SELECT title FROM titles WHERE title_lower >= ? LIMIT 1", (prefix,), ).fetchone() except Exception as e: log.debug("Failed to warm title B-tree for %s: %s", name, e) opened += 1 log.info("Title indexes warmed: %d/%d", opened, len(zim_files)) except Exception as e: log.warning("Title B-tree warm phase failed: %s", e) # A container whose data folder is not a volume: said once in the log (Settings says it in words). try: from zimi import runtimes if runtimes.config_kept() is False: log.warning( "This container's data folder (%s) is not on a volume: settings, indexes and add-ons go when " "it is replaced. Mount a volume at /config.", ZIMI_DATA_DIR, ) except Exception: pass # Phase 6: the did-you-mean vocabulary, loaded from disk or built now # that the title indexes are final and the phases above are done with # the machine. Waiting for the first misspelled search meant that # search, and every one for the next few minutes, got no suggestion. try: from zimi import search as _search_mod _search_mod._build_vocab_here() except Exception as e: log.warning("Did-you-mean vocab phase failed: %s", e) threading.Thread( target=_startup_worker, daemon=True, name="zimi-startup-worker" ).start() loaded = _suggest_cache_restore() if loaded: log.info("Suggest cache restored: %d entries", loaded) # ============================================================================ # Re-exports from extracted modules # ============================================================================ # These keep ``zimi.server.search_all`` etc. working so callers (tests, # mcp_server.py, handler code still in this file) need zero changes. # # THE STALE-ALIAS TRAP — read before adding a name below. # # ``from zimi.x import name`` copies the *current binding* into this module's # namespace once, at import time. Whether that copy stays correct depends # entirely on what the owning module does to the name afterwards: # # function / class immune. The object is never replaced. # container, mutated only safe. ``d[k] = v`` / ``d.clear()`` / ``lst.append`` # in place mutate the shared object; both names still point # at it. Most caches here are this class. # constant, never assigned safe. Includes module-level values finalised # after import during the owning module's own body (e.g. # SEARCH_UI_HTML, which http.py rewrites several # times before server.py ever imports it). # REBOUND after import BROKEN. ``global name; name = something_else`` # inside a function rebinds only the owning # module's global. The alias here keeps pointing # at the original object forever, and every # consumer that reads it through ``_srv.name`` # sees import-time state for the life of the # process. # # That last class shipped a silent production bug: /resolve?domains=1 served # ``_srv._domain_zim_map``, but _build_domain_zim_map rebinds interlang's # global, so a normally-booted server handed the browser an empty domain map # forever and cross-ZIM link resolution was quietly dead. # # So rebind-class names are NOT imported by value. They are listed in # _REBOUND_ALIASES and resolved on every access by the module __getattr__ # below, which cannot go stale. If you add a ``global`` rebind to a name that # server.py re-exports, move it into that table — tests/test_alias_freshness.py # re-derives the classification from the AST and fails if you don't. # Names whose owning module rebinds them at runtime. Resolved live instead of # copied, so ``_srv.`` is always the owner's current value. _REBOUND_ALIASES = { "_domain_zim_map": "zimi.interlang", # rebuilt by _build_domain_zim_map "_download_counter": "zimi.library", # bumped per download / import "_env_pw_hash_cache": "zimi.manage", # memoised on first password check } def __getattr__(name): """Resolve rebind-class re-exports live (PEP 562). See the trap note above.""" owner = _REBOUND_ALIASES.get(name) if owner is not None: return getattr(sys.modules[owner], name) raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from zimi.search import ( # noqa: E402, F401 _random_map_place, _map_home_view, find_places, suggest_places, parse_latlng, # Search / suggest caches (dicts + constants + functions) _search_cache, SEARCH_CACHE_MAX, _search_cache_key, _search_cache_get, _search_cache_put, _search_cache_clear, search_cached, result_snippet, first_screen, _suggest_cache, _suggest_cache_get, _suggest_cache_put, _suggest_cache_clear, _suggest_cache_persist, _suggest_cache_restore, # SQLite pooling helpers (used by Q-ID code above) _get_pooled_db, _close_pooled_db, _index_is_current, # Title index _get_title_db, _close_title_db, _title_index_dir, _title_index_path, _title_index_is_current, _build_title_index, _build_fts_for_index, _title_index_search, _get_title_index_stats, _get_title_index_status_brief, _build_all_title_indexes, _clean_stale_title_indexes, # Archive pools for suggest/FTS _get_suggest_archive, _get_fts_archive, _get_pooled_archive, # Search functions suggest_search_zim, search_zim, _score_result, _clean_query, search_all, read_article, chunk_article, best_answer_for, CHUNK_SIZE_MIN, CHUNK_SIZE_MAX, CHUNK_SIZE_DEFAULT, CHUNK_OVERLAP_DEFAULT, suggest, extract_pdf_text, get_catalog, parse_catalog, list_entries, # Content serving & discover random_entry, _get_dated_entry, _xkcd_date_lookup, _pick_html_entry, _get_factbook_countries, # Constants & compiled patterns (used by tests) _meta_title_re, STOP_WORDS, ) from zimi.interlang import ( # noqa: E402, F401 # Language data _LANG_NATIVE_NAMES, _STOPWORDS, _detect_query_language, # Q-ID matching _build_all_qid_indexes, _qid_passive_cache, _qid_passive_extract, _qid_lookup, _qid_extract_from_html, _qid_cache_store, _qid_find_in_zim, _qid_has_index, # Almanac deep-links (closed-set Q-ID → article batch resolution) resolve_almanac_qids, ALMANAC_QID_BATCH_MAX, # Cross-ZIM resolution (_domain_zim_map is rebind-class — see _REBOUND_ALIASES) _xzim_refs, _xzim_refs_lock, _build_domain_zim_map, _resolve_url_to_zim, zim_domain, canonical_url, # Article language matching get_article_languages, _zim_project_name, _zim_quality_score, _find_article_in_lang_zims, ) # The web app's halves, re-exported like the rest. zimi-mcp ships none of # them; see bundled(). if bundled("library"): from zimi.library import ( # noqa: E402, F401 # Auto-update _auto_update_config_path, _auto_update_env_locked, _load_auto_update_config, _save_auto_update_config, _load_auto_update_skips, set_auto_update_skip, _auto_update_enabled, _auto_update_freq, _auto_update_last_check, _auto_update_thread, _auto_update_loop, _FREQ_SECONDS, # Downloads & catalog _active_downloads, _download_lock, # _download_counter is rebind-class — see _REBOUND_ALIASES _opds_cache, _OPDS_CACHE_TTL, _start_download, _start_peer_download, _start_import, _get_downloads, _fetch_kiwix_catalog, maintenance_catalog_refresh, USER_AGENT, _check_updates, _fetch_thumb, _clear_thumb_cache, _thumb_dir, _download_thread, _fetch_mirrors, _download_from_url, _title_from_filename, KIWIX_OPDS_BASE, ) if bundled("manage"): from zimi.manage import ( # noqa: E402, F401 # Password & authentication _hash_pw, _PW_ITERATIONS, # _env_pw_hash_cache is rebind-class — see _REBOUND_ALIASES _get_manage_password_hash, _api_token_file, _get_api_token, _generate_api_token, _revoke_api_token, _check_manage_auth, # Manage route handlers handle_manage_get, handle_manage_post, ) if bundled("http"): from zimi.http import ( # noqa: E402, F401 # Rate limiting RATE_LIMIT, RATE_LIMIT_CONTENT, _rate_buckets, _rate_buckets_content, _rate_lock, _check_rate_limit, # Metrics _metrics, _metrics_lock, _record_metric, _get_metrics, # Usage stats _usage_stats, _usage_lock, _record_usage, _get_usage_stats, _get_disk_usage, # UI templates COMPRESSIBLE_TYPES, SEARCH_UI_HTML, # HTTP handler ZimHandler, ) if __name__ == "__main__": main()