From c5e210c918055f9f32872b1161c29b3b9aabe76b Mon Sep 17 00:00:00 2001 From: anor Date: Sat, 18 Jul 2026 10:04:17 +1000 Subject: [PATCH] =?UTF-8?q?feat(ext):=20=D0=A4=D0=B0=D0=B7=D0=B0=204/5=20?= =?UTF-8?q?=E2=80=94=20=D0=BE=D1=85=D0=B2=D0=B0=D1=82=20=D0=B2=D1=81=D0=B5?= =?UTF-8?q?=D1=85=20=D0=B8=D1=81=D1=82=D0=BE=D1=87=D0=BD=D0=B8=D0=BA=D0=BE?= =?UTF-8?q?=D0=B2/=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20+=20=D0=B2=D1=81=D0=B5=20=D1=80=D0=B5=D0=B3=D0=B8?= =?UTF-8?q?=D0=BE=D0=BD=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fgis_client: opendata_list/meta/download (15 датасетов: КСР/ФСНБ/СПСРП/оплата труда/9 ПССР), bim_leaf_docs (дерево писем-индексов), download_by_guid, all_subject_ids. xsd_client: скрейп .zip-схем экспертизы (html.parser, fail-loud на 0 ссылок). ext_pull: pull_opendata/bim/xsd, --source opendata/bim/xsd/all-sources, --regions all (все 86). ext_check: check_opendata (lastChangeDate)/check_bim(guid)/check_xsd(ссылки) + режим all-regions — чекер мониторит ВСЁ. 10 новых тестов. --- ext_check.py | 72 +++++++++++++++++++- ext_pull.py | 120 ++++++++++++++++++++++++++++++---- fgis_client.py | 80 +++++++++++++++++++++++ tests/test_ext_check.py | 29 ++++++++ tests/test_ext_new_sources.py | 60 +++++++++++++++++ xsd_client.py | 59 +++++++++++++++++ 6 files changed, 405 insertions(+), 15 deletions(-) create mode 100644 tests/test_ext_new_sources.py create mode 100644 xsd_client.py diff --git a/ext_check.py b/ext_check.py index 7849739..93559fd 100644 --- a/ext_check.py +++ b/ext_check.py @@ -23,10 +23,75 @@ import pravo_client as pc def _regions() -> list[int]: - raw = os.environ.get("EXT_REGIONS", "") + raw = os.environ.get("EXT_REGIONS", "").strip() + if raw.lower() == "all": + try: + return [s["id"] for s in fc.country_subjects()] + except ext_fetch.FetchError: + return [] return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()] +def check_opendata(seen: dict, *, client=None) -> tuple[list[dict], dict]: + """Обновлённые датасеты открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР) по lastChangeDate.""" + prev = seen.get("opendata_lastchange", {}) + try: + datasets = fc.opendata_list(client=client) + except ext_fetch.FetchError as e: + return [{"source": "opendata", "level": "problem", "message": f"OpenData недоступен: {e}"}], seen + findings = [] + for ds in datasets: + did = str(ds["id"]) + lc = ds.get("lastChangeDate") + if prev.get(did) != lc: + findings.append({ + "source": "fgis_opendata", "level": "update", + "message": f"Обновлён датасет «{ds.get('datasetName')}» (изм. {lc})", + "action": f"python3 ext_pull.py --source opendata --dataset {ds['id']}", + }) + prev[did] = lc + seen["opendata_lastchange"] = prev + return findings, seen + + +def check_bim(seen: dict, *, client=None) -> tuple[list[dict], dict]: + """Новые письма-индексы (БИМ) — новые guid листовых документов дерева.""" + seen_g = set(seen.get("bim_guids", [])) + try: + docs = fc.bim_leaf_docs(client=client) + except ext_fetch.FetchError as e: + return [{"source": "bim", "level": "problem", "message": f"БИМ-письма недоступны: {e}"}], seen + findings = [] + for d in docs: + if d["guid"] not in seen_g: + findings.append({"source": "fgis_bim", "level": "update", + "message": f"Новое письмо-индекс: {d.get('name') or d['guid']}", + "action": "python3 ext_pull.py --source bim"}) + seen_g.add(d["guid"]) + seen["bim_guids"] = sorted(seen_g)[-2000:] + return findings, seen + + +def check_xsd(seen: dict, *, client=None) -> tuple[list[dict], dict]: + """Новые/изменённые пакеты XSD-схем экспертизы (по списку ссылок).""" + import xsd_client + seen_l = set(seen.get("xsd_links", [])) + try: + links = xsd_client.schema_links(client=client) + except ext_fetch.FetchError as e: + return [{"source": "xsd", "level": "problem", "message": f"XSD-схемы: {e}"}], seen + findings = [] + for href in links: + if href not in seen_l: + findings.append({"source": "xsd_schema", "level": "update", + "message": f"Новый/изменённый пакет схем: {xsd_client._fname(href)}. " + f"NB: вступает в силу через ~3 мес после публикации.", + "action": "python3 ext_pull.py --source xsd"}) + seen_l.add(href) + seen["xsd_links"] = sorted(seen_l) + return findings, seen + + def check_fgis(regions: list[int], seen: dict, *, client=None) -> tuple[list[dict], dict]: """Новый период по каждой зоне сконфигурированных регионов. Дедуп через seen.""" findings: list[dict] = [] @@ -153,7 +218,10 @@ def run_check(regions: list[int] | None = None, *, notify: bool = True) -> dict: "message": "EXT_REGIONS не задан — ФГИС не мониторится (проверяются только приказы)"}) f_fgis, seen = check_fgis(regions, seen) f_pravo, seen = check_pravo(seen) - findings += f_fgis + f_pravo + f_od, seen = check_opendata(seen) + f_bim, seen = check_bim(seen) + f_xsd, seen = check_xsd(seen) + findings += f_fgis + f_pravo + f_od + f_bim + f_xsd _write_report(findings, regions) updates = [f for f in findings if f["level"] in ("update", "problem")] diff --git a/ext_pull.py b/ext_pull.py index bd64f55..588444d 100644 --- a/ext_pull.py +++ b/ext_pull.py @@ -113,10 +113,70 @@ def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) -> return {**meta, "items": data.get("total")} +def pull_opendata(dataset_id: int) -> dict: + """Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР).""" + dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id) + with tempfile.TemporaryDirectory() as td: + tmp = Path(td) / "download.bin" + _res, name = fc.download_opendata(dataset_id, tmp) + named = Path(td) / (Path(name).name or f"dataset_{dataset_id}") + tmp.replace(named) + meta = ext_state.register_snapshot( + dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}", + url=fc.BASE + f"/api/OpenData/{dataset_id}") + return {**meta, "dataset_id": dataset_id} + + +def pull_all_opendata() -> list[dict]: + out = [] + for ds in fc.opendata_list(): + out.append(pull_opendata(ds["id"])) + time.sleep(POLITE_PAUSE_S) + return out + + +def pull_bim() -> list[dict]: + """Скачать все письма-индексы (БИМ) — листовые документы дерева NormLegalDocPublished.""" + out = [] + docs = fc.bim_leaf_docs() + for d in docs: + dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"] + with tempfile.TemporaryDirectory() as td: + tmp = Path(td) / (Path(str(d.get("filePath") or "letter")).name or "letter.pdf") + fc.download_by_guid(d["guid"], tmp, expect_min_size=500) + meta = ext_state.register_snapshot( + dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}", + url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}") + out.append({**meta, "letter": d.get("name")}) + time.sleep(POLITE_PAUSE_S) + return out + + +def pull_xsd() -> list[dict]: + """Скачать все .zip-пакеты XSD-схем экспертизы со страницы Минстроя.""" + import xsd_client + out = [] + for href in xsd_client.schema_links(): + fname = xsd_client._fname(href) + dest_dir = ext_state.ext_dir() / "snapshots/xsd" / fname + with tempfile.TemporaryDirectory() as td: + tmp = Path(td) / fname + xsd_client.download_schema(href, tmp) + meta = ext_state.register_snapshot( + dest_dir, tmp, source="xsd_schema", key=f"xsd/{fname}", url=href) + out.append(meta) + time.sleep(POLITE_PAUSE_S) + return out + + def _zones_of(subject_id: int) -> list[int]: return [z["id"] for z in fc.price_zones(subject_id)] +def all_subject_ids() -> list[int]: + return [s["id"] for s in fc.country_subjects()] + + def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]: out = [] for zone_id in _zones_of(subject_id): @@ -130,33 +190,69 @@ def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[ def _regions_from_env(cli_regions: str | None) -> list[int]: - raw = cli_regions or os.environ.get("EXT_REGIONS", "") + raw = (cli_regions or os.environ.get("EXT_REGIONS", "")).strip() + if raw.lower() == "all": + return all_subject_ids() return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()] +def _p(r: dict) -> None: + print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}" + + (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else "")) + + def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Скачать данные ФГИС ЦС в снапшоты (осознанный шаг).") - ap.add_argument("--source", choices=["split_form", "indices", "salary", "all"], required=True) + ap = argparse.ArgumentParser(description="Скачать данные ФГИС/схемы в снапшоты (осознанный шаг).") + ap.add_argument("--source", required=True, choices=[ + "split_form", "indices", "salary", "all", # цены ФГИС по региону + "opendata", "bim", "xsd", "all-sources"]) # справочники/письма/схемы ap.add_argument("--subject", type=int, help="id региона") ap.add_argument("--zone", type=int, help="id ценовой зоны (если не задан — все зоны региона)") ap.add_argument("--period", type=int, help="id периода (по умолчанию последний)") - ap.add_argument("--regions", help="id регионов через запятую (или env EXT_REGIONS) для --source all") + ap.add_argument("--dataset", type=int, help="id датасета для --source opendata (иначе все)") + ap.add_argument("--regions", help="id регионов через запятую, или 'all', или env EXT_REGIONS") args = ap.parse_args(argv) - if not fc.alive(): + # источники без региона (opendata/bim/xsd) — не требуют ФГИС-alive-пречека кроме ФГИС-овских + if args.source in ("opendata", "bim", "all-sources") and not fc.alive(): print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr) return 2 + if args.source == "opendata": + for r in ([pull_opendata(args.dataset)] if args.dataset else pull_all_opendata()): + _p(r) + return 0 + if args.source == "bim": + for r in pull_bim(): + _p(r) + return 0 + if args.source == "xsd": + for r in pull_xsd(): + _p(r) + return 0 + if args.source == "all-sources": + for r in pull_all_opendata() + pull_bim() + pull_xsd(): + _p(r) + return 0 + + # ФГИС по регионам (цены/индексы/оплата) + if not fc.alive(): + print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr) + return 2 if args.source == "all": subjects = [args.subject] if args.subject else _regions_from_env(args.regions) if not subjects: - print("не заданы регионы: --subject, --regions или env EXT_REGIONS", file=sys.stderr) + print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr) return 2 + failed = 0 for sid in subjects: - for r in pull_all_for_subject(sid, args.period): - print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}" - + (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else "")) - return 0 + try: + for r in pull_all_for_subject(sid, args.period): + _p(r) + except Exception as e: # noqa: BLE001 — один регион не валит остальные + failed += 1 + print(f" ✗ регион {sid}: {type(e).__name__}: {e}", file=sys.stderr) + return 1 if failed else 0 if not args.subject: print("--subject обязателен", file=sys.stderr) @@ -164,9 +260,7 @@ def main(argv=None) -> int: zones = [args.zone] if args.zone else _zones_of(args.subject) fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source] for zone_id in zones: - r = fn(args.subject, zone_id, args.period) - print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}" - + (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else "")) + _p(fn(args.subject, zone_id, args.period)) return 0 diff --git a/fgis_client.py b/fgis_client.py index 72373ee..75cf632 100644 --- a/fgis_client.py +++ b/fgis_client.py @@ -99,6 +99,86 @@ def download_indices(period_id: int, price_zone_id: int, dest, client=None) -> d expect_min_size=50_000, expected_content_type=_SPREADSHEET, client=client) +def download_by_guid(guid: str, dest, client=None, expect_min_size: int = 100) -> dict: + """Скачать файл ФГИС по guid (общий механизм: /api/values/GetFileContent/{guid}).""" + return ext_fetch.fetch_file(f"{BASE}/api/values/GetFileContent/{guid}", dest, + expect_min_size=expect_min_size, client=client) + + +# --- Открытые данные (15 датасетов: КСР, ФСНБ-2020/2022, СПСРП, оплата труда, 9 ПССР) --- + +def opendata_list(client=None) -> list[dict]: + """Список датасетов: [{id, datasetName, lastChangeDate, ...}]. Ответ {total, items}.""" + data = ext_fetch.fetch_json(f"{BASE}/api/OpenData", client=client) + items = data.get("items") if isinstance(data, dict) else data + if not isinstance(items, list): + raise FgisFormatError("OpenData: нет списка items") + for it in items: + if not (isinstance(it, dict) and "id" in it and "lastChangeDate" in it): + raise FgisFormatError(f"OpenData: элемент без id/lastChangeDate: {str(it)[:80]}") + return items + + +def opendata_meta(dataset_id: int, client=None) -> dict: + """Метаданные датасета: datasetName, lastChangeDate, datasetFile:{path,name}, ...""" + data = ext_fetch.fetch_json(f"{BASE}/api/OpenData/{dataset_id}", client=client) + if not (isinstance(data, dict) and isinstance(data.get("datasetFile"), dict)): + raise FgisFormatError(f"OpenData/{dataset_id}: нет datasetFile") + return data + + +def download_opendata(dataset_id: int, dest, client=None) -> tuple[dict, str]: + """Скачать текущий файл датасета. Возвращает (fetch-результат, имя файла).""" + meta = opendata_meta(dataset_id, client=client) + df = meta["datasetFile"] + guid, name = df.get("path"), df.get("name") or f"dataset_{dataset_id}" + if not guid: + raise FgisFormatError(f"OpenData/{dataset_id}: пустой datasetFile.path") + return download_by_guid(guid, dest, client=client), name + + +# --- БИМ-письма (индексы изменения сметной стоимости): дерево NormLegalDocPublished --- + +def _norm_tree(parent_guid: str | None, client=None) -> list[dict]: + params = {"normLegalDocPublishedType": 10, "state": 20, "normLegalDocBaseKind": 40} + if parent_guid: + params["parentGuid"] = parent_guid + data = ext_fetch.fetch_json(f"{BASE}/api/NormLegalDocPublished", params=params, client=client) + # Ответ вида {"": [ ... ]} или список — берём значения. + if isinstance(data, dict): + nodes = [] + for v in data.values(): + if isinstance(v, list): + nodes.extend(v) + return nodes + return data if isinstance(data, list) else [] + + +def bim_leaf_docs(max_nodes: int = 4000, client=None) -> list[dict]: + """Все листовые документы дерева БИМ-писем (у листа есть filePath). Обход по parentGuid + с потолком узлов (защита от зацикливания при дрейфе схемы).""" + out: list[dict] = [] + stack = [None] + seen: set[str] = set() + visited = 0 + while stack and visited < max_nodes: + pg = stack.pop() + for node in _norm_tree(pg, client=client): + visited += 1 + g = node.get("guid") + if not g or g in seen: + continue + seen.add(g) + if node.get("filePath"): # лист-документ + out.append({"guid": g, "name": node.get("name"), "date": node.get("date"), + "number": node.get("number"), "filePath": node.get("filePath")}) + else: # папка (год/квартал) — углубляемся + stack.append(g) + if visited >= max_nodes: + break + return out + + def salary_registry(price_zone_id: int, period_id: int, client=None) -> dict: """Реестр оплаты труда рабочих по разрядам (JSON: {total, items:[...]}).""" data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/RimWorkerSalaryRegistry", diff --git a/tests/test_ext_check.py b/tests/test_ext_check.py index b8117cf..f6f0fcc 100644 --- a/tests/test_ext_check.py +++ b/tests/test_ext_check.py @@ -15,6 +15,15 @@ import fgis_client as fc # noqa: E402 import pravo_client as pc # noqa: E402 +@pytest.fixture(autouse=True) +def _mock_new_sources(monkeypatch): + """По умолчанию opendata/bim/xsd не дают находок (не ходят в сеть). Тесты переопределяют.""" + import xsd_client + monkeypatch.setattr(fc, "opendata_list", lambda client=None: []) + monkeypatch.setattr(fc, "bim_leaf_docs", lambda client=None: []) + monkeypatch.setattr(xsd_client, "schema_links", lambda client=None: []) + + @pytest.fixture def _tmp(monkeypatch, tmp_path): monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path)) @@ -143,6 +152,26 @@ def test_rollback_reports_again(_tmp, monkeypatch): assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep["findings"]) +def test_new_sources_detected_and_deduped(_tmp, monkeypatch): + """opendata (по lastChangeDate), bim (по guid), xsd (по ссылке) — находки + дедуп на 2-м прогоне.""" + import xsd_client + _mock_fgis(monkeypatch, latest=426) + _mock_pravo(monkeypatch, []) + monkeypatch.setattr(fc, "opendata_list", + lambda client=None: [{"id": 2, "datasetName": "КСР", "lastChangeDate": "2026-05-20"}]) + monkeypatch.setattr(fc, "bim_leaf_docs", + lambda client=None: [{"guid": "G1", "name": "письмо 1 кв", "filePath": "/x.pdf"}]) + monkeypatch.setattr(xsd_client, "schema_links", lambda client=None: ["/a/KAC.zip"]) + with es.update_state() as st: + st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} + rep = ec.run_check(regions=[323], notify=False) + srcs = {f["source"] for f in rep["findings"]} + assert {"fgis_opendata", "fgis_bim", "xsd_schema"} <= srcs + # второй прогон — те же не повторяются (дедуп) + rep2 = ec.run_check(regions=[323], notify=False) + assert not [f for f in rep2["findings"] if f["source"] in ("fgis_opendata", "fgis_bim", "xsd_schema")] + + def test_notify_called_only_with_findings(_tmp, monkeypatch): _mock_fgis(monkeypatch, latest=426) _mock_pravo(monkeypatch, []) diff --git a/tests/test_ext_new_sources.py b/tests/test_ext_new_sources.py new file mode 100644 index 0000000..eb53823 --- /dev/null +++ b/tests/test_ext_new_sources.py @@ -0,0 +1,60 @@ +"""Фаза 4/5: парсеры новых источников (opendata, БИМ-дерево, XSD-скрейп). Моки MockTransport.""" +import sys +from pathlib import Path + +import httpx +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import fgis_client as fc # noqa: E402 +import xsd_client # noqa: E402 + + +def test_opendata_list_parses_items(): + resp = {"total": 2, "items": [ + {"id": 2, "datasetName": "КСР", "lastChangeDate": "2026-05-20"}, + {"id": 4, "datasetName": "ФСНБ-2022", "lastChangeDate": "2026-05-15"}]} + with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json=resp))) as c: + items = fc.opendata_list(client=c) + assert [i["id"] for i in items] == [2, 4] + + +def test_opendata_list_format_error(): + with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, json={"x": 1}))) as c: + with pytest.raises(fc.FgisFormatError): + fc.opendata_list(client=c) + + +def test_bim_tree_recursion_collects_leaf_docs(): + # корень (parentGuid отсутствует) → папка F1; F1 → лист L1 (есть filePath) + папка F2; F2 → лист L2 + def handler(r): + pg = r.url.params.get("parentGuid") + if pg is None: + return httpx.Response(200, json={"": [{"guid": "F1", "name": "2026", "filePath": None}]}) + if pg == "F1": + return httpx.Response(200, json={"": [ + {"guid": "L1", "name": "письмо A", "filePath": "/a.pdf"}, + {"guid": "F2", "name": "2 кв", "filePath": None}]}) + if pg == "F2": + return httpx.Response(200, json={"": [{"guid": "L2", "name": "письмо B", "filePath": "/b.pdf"}]}) + return httpx.Response(200, json={"": []}) + with httpx.Client(transport=httpx.MockTransport(handler)) as c: + docs = fc.bim_leaf_docs(client=c) + guids = {d["guid"] for d in docs} + assert guids == {"L1", "L2"} # только листья с filePath, папки — не документы + + +def test_xsd_schema_links_extracted(): + html = 'КАЦ нет ' \ + 'ЛСР' + with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text=html))) as c: + links = xsd_client.schema_links(client=c) + assert links == ["/upload/x/KAC-4_02.zip", "/upload/y/LSR.zip"] + assert xsd_client._fname("/upload/x/KAC-4_02.zip") == "KAC-4_02.zip" + + +def test_xsd_fail_loud_on_zero_links(): + """0 ссылок = вёрстка сменилась → FetchError, а не тихое «обновлений нет».""" + with httpx.Client(transport=httpx.MockTransport(lambda r: httpx.Response(200, text="no links"))) as c: + with pytest.raises(Exception): + xsd_client.schema_links(client=c) diff --git a/xsd_client.py b/xsd_client.py new file mode 100644 index 0000000..f63e93e --- /dev/null +++ b/xsd_client.py @@ -0,0 +1,59 @@ +"""xsd_client — XSD-схемы сметной документации/экспертизы с minstroyrf.gov.ru (срез 5.1). + +Единственный НЕ-API источник: HTML-страница /tim/xml-skhemy/ со ссылками на .zip-пакеты +схем (ЛСР, ОСР, КАЦ и т.д.). Скрейп стандартным html.parser (без новых зависимостей). +fail-loud: 0 ссылок = вёрстка изменилась (НЕ «обновлений нет» — типовая тихая ложь скрейпера). +Скачивание/версионирование только; валидация gge_export по схемам (нужен lxml) — отдельный +срез 5.2 по согласованию. +""" +from __future__ import annotations + +import os +from html.parser import HTMLParser + +import ext_fetch + +BASE = os.environ.get("MINSTROY_BASE", "https://minstroyrf.gov.ru") +PAGE = os.environ.get("MINSTROY_XSD_PAGE", "/tim/xml-skhemy/") + + +class _ZipLinkParser(HTMLParser): + def __init__(self): + super().__init__() + self.links: list[str] = [] + + def handle_starttag(self, tag, attrs): + if tag == "a": + href = dict(attrs).get("href", "") or "" + if href.lower().endswith(".zip"): + self.links.append(href) + + +def _page_html(client=None) -> str: + c = client or ext_fetch.make_client() + try: + r = c.get(f"{BASE}{PAGE}") + r.raise_for_status() + return r.text + finally: + if client is None: + c.close() + + +def schema_links(client=None) -> list[str]: + """Ссылки на .zip-пакеты схем со страницы. fail-loud при 0 (вёрстка сменилась).""" + p = _ZipLinkParser() + p.feed(_page_html(client=client)) + links = sorted(set(p.links)) + if not links: + raise ext_fetch.FetchError("страница XSD-схем: 0 ссылок .zip — изменилась вёрстка/страница?") + return links + + +def _fname(href: str) -> str: + return href.rstrip("/").split("/")[-1] or "schema.zip" + + +def download_schema(href: str, dest, client=None) -> dict: + url = href if href.startswith("http") else f"{BASE}{href}" + return ext_fetch.fetch_file(url, dest, expect_min_size=100, client=client)