"""ZimiGames and the encyclopedia, linked both ways. The games' Wikidata Q-IDs live in the ZIM's source (builtin/games/games.json: Q-ID, the game's page, its English article title). Which installed Wikipedia article carries each Q-ID is worked out in the background whenever the library changes (``refresh_async``), from what Zimi already keeps: the per-ZIM Q-ID index and the passive Q-ID cache, both plain SQLite reads, and for an English ZIM with neither an exact-title probe. Nothing is built for this: a ZIM with no Q-ID index only gets the links its cache holds (plus the English title probe). ``links()`` hands that answer to ``GET /games-links``, which the reader asks for the first time a wiki article opens (never on page load). The reader then checks its article's path in memory: a hit shows Play; the games' "About" link (about.html?qid=) opens the article for the reader's language. """ import html import json import logging import os import random import re import threading import time from urllib.parse import quote import zimi.server as _srv from zimi import ownzims from zimi.safety import loggable from zimi.interlang import ( _ALMANAC_ENC_RE, _almanac_title_entry_path, _qid_find_in_zim, ) log = logging.getLogger("zimi") _GAMES_ZIM = "zimi_games" _ALMANAC_ZIM = "zimi_almanac" _ALMANAC_LINKS_JS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "almanac-links.js") #: The Almanac's kinds that are something to look at in the sky (not a holiday, a city or a term). _SKY_KINDS = ("planet", "star", "const", "shower", "eclipse", "belt", "probe") _ALMANAC_ENTRY = re.compile(r"'([a-z]+:[A-Za-z0-9_.\-]+)':\s*\{\s*q:\s*'(Q\d+)'") _lock = threading.Lock() _rows = None # games.json, read once _memo = {"token": None, "articles": {}} _building = threading.Lock() _dirty = threading.Event() #: After a build fails, the next try waits this long (seconds), however often #: the answer is asked for: a broken index must not cost every request a rebuild. _RETRY_AFTER_FAILURE_S = 300 _failed_at = None # time.monotonic() of the last failed build, or None def _here(name): return ( ownzims.enabled() and any(z.get("name") == name for z in _srv._zim_list_cache or []) and _srv.zim_allowed(name) ) def games_here(): """Whether the games ZIM is in the library for this request: removed or deleted (or off the account's list), nothing of it is offered.""" return _here(_GAMES_ZIM) def almanac_here(): """Whether the Almanac ZIM is in the library for this request.""" return _here(_ALMANAC_ZIM) _almanac_keys = None # {qid: entity key}, read once _thumbs = {} # game path -> the picture's /w/ URL or None, found once def almanac_qids(): """{Q-ID: the Almanac's key for it ("planet:moon")}: the closed set the Almanac links into the encyclopedia (static/almanac-links.js holds it, once; this reads it so a Wikipedia article on one can offer the Almanac).""" global _almanac_keys if _almanac_keys is None: try: with open(_ALMANAC_LINKS_JS, encoding="utf-8") as f: _almanac_keys = {q: k for k, q in _ALMANAC_ENTRY.findall(f.read()) if k.split(":")[0] in _SKY_KINDS} except OSError as e: log.warning("almanac-links.js unreadable: %s", e) _almanac_keys = {} return _almanac_keys _EARTH_DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "earth") _ALMANAC_PLANET = re.compile(r"'planet:([a-z]+)':\s*\{\s*q:\s*'(Q\d+)'") _almanac_3d = None # {qid: the 3D view's address for it}, read once def _earth_json(name): try: with open(os.path.join(_EARTH_DATA, name), encoding="utf-8") as f: return json.load(f) except (OSError, ValueError) as e: log.warning("%s unreadable: %s", name, e) return {} def almanac_3d_links(): """{Q-ID: the Almanac address (#almanac?...) that opens the 3D view on it}: a mission's replay, a spacecraft or a landing (its row of Sent), a body, a landmark. Read once from the view's own data files (static/earth: their Q-IDs are Wikidata's), so an article on any of them can offer the view, and nothing is built or probed per article. Where two name one Q-ID the first kind here wins: a mission's replay, then the craft, then the body, then the landmark.""" global _almanac_3d if _almanac_3d is not None: return _almanac_3d out = {} sent = _earth_json("sent-v1.json").get("objects", []) by_id = {o.get("id", "").replace("-", ""): o for o in sent} for mid, m in (_earth_json("missions-v1.json").get("missions") or {}).items(): o = by_id.get(mid) if o and o.get("qid"): body = (m.get("handoff") or {}).get("body") or (o.get("where") or {}).get("body") or "earth" start = m.get("start") or 0 out.setdefault(o["qid"], "v=%s&m=mission&k=%s,%s,0,1" % (body, mid, ("%g" % start))) for o in sent: if o.get("qid"): where = o.get("where") or {} # The ISS is a view of its own (v=iss follows it); the rest open on their world, their row choosing the rest. view = "iss" if where.get("iss") else where.get("body") or "earth" out.setdefault(o["qid"], "v=%s&x=sent:%s" % (view, o["id"])) try: with open(_ALMANAC_LINKS_JS, encoding="utf-8") as f: for body, qid in _ALMANAC_PLANET.findall(f.read()): out.setdefault(qid, "v=%s" % body) except OSError: pass for name in ("landmarks-v1.json", "landmarks-earth-v1.json"): data = _earth_json(name) fields = data.get("fields") or [] if "qid" not in fields: continue qi = fields.index("qid") for body, rows_ in data.items(): if not isinstance(rows_, list) or body in ("fields", "sources"): continue for r in rows_: if len(r) > qi and r[qi]: out.setdefault(r[qi], "v=%s&x=lm:%s:%s" % (body, body, quote(str(r[0]), safe=""))) _almanac_3d = out return out def almanac_view(zim, path): """The 3D view's address for the article at ``zim``/``path``, or None: its Q-ID (the reader's own lookup, which learns it from the article when no index has it) against the view's closed set. Only for a request that may see the article, and while the Almanac is in the library.""" if not almanac_here() or not _srv.zim_allowed(zim): return None links3d = almanac_3d_links() qid = _srv._qid_lookup(zim, path) if qid is None: _srv._qid_passive_extract(zim, path) # the article was just read: what its own page says qid = _srv._qid_lookup(zim, path) return links3d.get("Q%d" % qid) if qid is not None else None def rows(): """games.json: [{qid, wiki, path, title, blurb}].""" global _rows if _rows is None: path = os.path.join(ownzims.SOURCE_ROOT, "games", "games.json") try: with open(path, encoding="utf-8") as f: _rows = json.load(f) except (OSError, ValueError) as e: log.warning("games.json unreadable: %s", e) _rows = [] return _rows #: The shelf as the page writes it: a section heading, a family card, the end of a family, a tile (page, English name). _SHELF_TOKEN = re.compile( r'