"""Публичный снимок загруженных нормативных документов для главной страницы. Только два заведомо общих корпуса. Каталоги пользователей и файлы диалогов здесь не просматриваются: их названия могут содержать персональные данные. """ from __future__ import annotations import html import json import time from datetime import datetime from pathlib import Path import ext_state _CACHE_SECONDS = 300 _cache_until = 0.0 _cache_value: dict | None = None def clear_cache() -> None: """Сброс снимка для тестов и оператора после ручного обновления корпуса.""" global _cache_until, _cache_value _cache_until = 0.0 _cache_value = None def _read_meta(path: Path) -> dict | None: try: value = json.loads(path.read_text(encoding="utf-8")) return value if isinstance(value, dict) else None except (OSError, ValueError): return None def _date(value: object) -> tuple[str, str] | None: if not isinstance(value, str): return None try: d = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None return (d.isoformat(), d.strftime("%d.%m.%Y")) def _collect() -> dict: base = ext_state.ext_dir() / "snapshots" found = [] tsn = base / "niac_tsn" for path in tsn.glob("*/*/meta.json"): if not (path.parent / "extract.json").is_file(): continue meta = _read_meta(path) if not meta or not isinstance(meta.get("title"), str) or not meta["title"].strip(): continue found.append({"title": meta["title"].strip(), "source": "ТСН Москвы", "loaded": _date(meta.get("fetched_at"))}) bim = base / "fgis" / "bim_letters" for path in bim.glob("*/meta.json"): if not (path.parent / "letter.pdf").is_file(): continue meta = _read_meta(path) if not meta or meta.get("source") != "fgis_bim": continue found.append({"title": "Письмо-индекс Минстроя", "source": "ФГИС ЦС", "loaded": _date(meta.get("fetched_at"))}) dated = [doc for doc in found if doc["loaded"]] dated.sort(key=lambda doc: doc["loaded"][0], reverse=True) return {"count": len(found), "recent": dated[:4]} def snapshot() -> dict: """Снимок на пять минут: не читать сотни файлов на каждый просмотр главной.""" global _cache_until, _cache_value now = time.monotonic() if _cache_value is None or now >= _cache_until: _cache_value = _collect() _cache_until = now + _CACHE_SECONDS return _cache_value def render() -> str: data = snapshot() count = data["count"] if data["recent"]: items = "".join( '
Документы пока не загружены.
' return ( '