Download scripts/legal_monitor.py from railnexus/value: direct link, hf CLI and curl.
- Browser
- Download file 186 kB
-
https://huggingface.co/spaces/railnexus/value/resolve/main/scripts/legal_monitor.py
- Command line
-
hf download hf://spaces/railnexus/value/scripts/legal_monitor.py
-
curl -L -o legal_monitor.py https://huggingface.co/spaces/railnexus/value/resolve/main/scripts/legal_monitor.py
186 kB
#!/usr/bin/env python3
"""
legal_monitor.py — Spanish Construction Law Monitor (v18)
Queries the BOE OpenData sumario API + CCAA bulletin feeds (RSS/Atom, open-data
JSON datasets, JSON row services and the DOGC summary API) for
construction-related legal changes.
v18 (2026-09-16, rounds 4-5 — every URL below was fetched and parsed live):
- Round 4 (sonnet): six bulletins wired with real RSS (BOCM, BOCYL, DOE, BOIB,
BOC Cantabria, BOME); eight investigated and left without feed.
- Round 5 (fable): three of those eight are now scanned through their own
JSON services, and Catalunya is scanned through the DOGC's own summary API:
* **DOGC (Catalunya), ALL sections** — the "Sumari del DOGC" page is fed by
``POST https://portaldogc.gencat.cat/eadop-rest/api/dogc/summaryDOGC``
(form fields ``numDOGC`` + ``language``; ``calendarDOGC`` with ``month`` /
``year`` lists the issue numbers of a month). Sections returned live on
2026-09-16: Disposicions generals, Altres disposicions, Càrrecs i personal,
Anuncis, Administració local, Altres subjectes emissors — i.e. the edictes
of the Comissions Territorials d'Urbanisme and the municipal planning
approvals that the Section-1-only Socrata dataset (kept as a second feed)
never carried. The host only completes a TLS handshake at OpenSSL security
level 1 (``SSLV3_ALERT_HANDSHAKE_FAILURE`` at the default level 2), so a
session with a scoped, still certificate-verifying context is used for that
host only (:func:`legacy_tls_session`).
* **BOA (Aragón)** — the SPA's open-data JSON service
``cgi-bin/EBOA/BRSCGI?...&SEC=OPENDATABOAJSON&@PUBL-GE=YYYYMMDD`` (the URL
the region's own CKAN catalogue publishes for the "Decretos y Leyes"
dataset) returns one record per disposition with title, section, rank,
issuer, publication date, ELI URI and text. The producer emits invalid JSON
escapes (``\\_`` inside ``Texto``) and ISO-8859-1; both are repaired before
parsing (``lenient_json``). Sections I + III are requested (same default as
the BOE); V. Anuncios is available by changing ``SECC-C``.
* **BORM (Murcia)** — the SPA's ``services/boletin/fecha/DD-MM-YYYY/sumario``
returns the day's issue with every announcement (``anunciosBoletin``:
``sumario`` = title, ``apartado`` / ``subApartado``, ``numero``). Scanned
one day at a time like the BOE (HTTP 404 = no issue that day); the
"Autoridades y Personal" sub-section is excluded as noise.
* Asturias, Canarias, Castilla-La Mancha, Navarra, La Rioja and Ceuta stay
without a machine-readable feed after a second, different set of attempts
(regional CKAN/open-data APIs, datos.gob.es, Joomla/Liferay conventions);
what was tried is in each ``rss_last_check``. Asturias publishes a yearly
open-data archive of BOPA dispositions (the 2025 file appeared in
August 2026) — an archive, not a monitoring feed.
- Feed kinds: ``rss`` | ``socrata_json`` | ``json_rows`` (generic JSON list,
optional per-day URL template) | ``dogc_summary`` | ``bocm_xml`` (v19: the
BOCM's per-issue native XML, issue calendar from sumarios.rss). A feed that could read
only part of its window reports ``PARTIAL`` and keeps what it read; the
CCAA aggregate is then ``PARTIAL`` (coverage != COMPLETE, exit 1).
- Entries of one CCAA are de-duplicated by normalised title across its feeds
(the DOGC summary and the Socrata dataset both list a new Decret).
- Catalan keyword equivalents were added to the keyword lists so Catalan
titles (DOGC, BOIB) match without a second language fetch.
v17 (2026-09-16, third correction round — the four CCAA feeds left BLOCKED in
v16.0.1 were re-investigated with live autodiscovery on each bulletin's own site
and on the official open-data portals; every URL below was fetched and parsed):
- País Vasco (BOPV): ``https://www.euskadi.eus/bopv2/datos/Ultimo.xml`` — the
"RSS" link on the official "Último boletín" page. RSS 2.0, one entry per
disposition of the LATEST issue only (nº 176 of 15/09/2026: 16 dated entries,
2 construction matches). The old ``/contenidos/informacion/ehaa_rss/...`` is 404.
- Andalucía (BOJA): ``/boja/distribucion/s51.xml`` (1. Disposiciones generales)
and ``s54.xml`` (3. Otras disposiciones) — Atom feeds advertised with
``<link rel="alternate">`` on every issue page and documented in the BOJA FAQ
"Distribución de RSS". Current issue only (nº 180 of 16/09/2026). WARNING: the
legacy ``/boja/distribucion/s0..s5.2.xml`` still answer 200 but are frozen at
issue 2021/217 (lastBuildDate 2021-11-11) with undated entries — never use them.
The old ``/eboja/rss/rss.html`` is 404.
- Catalunya (DOGC): no RSS/Atom exists (e-mail "Alertes DOGC" only; portaldogc
403). The DOGC "Dades obertes" page points to the official Socrata dataset
``n6hn-rmy7`` "Normativa del DOGC i del Portal Jurídic de Catalunya"
(attribution EADOP, refreshed daily — newest row DOGC nº 9751 of 2026-09-15).
Scanned through the JSON API with a server-side date filter. Scope: Section 1
normative acts (laws, decrets, ordres) — not Section 3 nor announcements.
- Valencia (DOGV): genuinely no machine-readable feed. ``/datos/rss/*`` answers
403 for every file name and for the folder, with default and browser
User-Agent; ``/es/rss`` and ``/rss/dogv_es.xml`` redirect to the HTML home;
"Alertas y subscripciones" redirects to the personal-area login; the GVA
open-data portal has no DOGV dataset (package_list, 1309 packages) and its
search API answers 500; datos.gob.es lists no DOGV bulletin dataset. Kept as a
dead URL that is retried and reported ``UNREACHABLE`` on every run.
- A CCAA may now declare several feeds (``feeds``); per-feed outcomes are
reported and a source whose feeds partly failed is ``PARTIAL`` (never
collapsed into OK/EMPTY), which keeps ``coverage.status != COMPLETE``.
Sources:
- BOE OpenData sumario API (https://www.boe.es/datosabiertos/api/boe/sumario/YYYYMMDD,
``Accept: application/json``) — one disposition per item, keyword scan on the
disposition title. Live-verified 2026-09-15 (HTTP 200 JSON; 404 + API code 404
on days without an issue, e.g. Sundays).
v16.0.0 scanned the HTML page ``/boe/dias/YYYY/MM/DD/`` as one blob; its footer
carries a site-wide "Accesibilidad" link, so every day matched the keyword
"accesibilidad", every entry was a synthetic "BOE dd/mm — disposiciones…" line
with an empty summary, and a failed fetch was silently skipped.
- CCAA RSS feeds where they exist (see CCAA_SOURCES); others are listed with
search URLs only and are NOT scanned automatically. Every requested source
reports a status (OK / EMPTY / UNREACHABLE / NOT_CONFIGURED) in the JSON, in
the text digest and through the exit code — an unreachable feed is never
reported the same way as a feed with nothing relevant.
CLI contract (v16 — v14 audit F-09):
- ``--help`` performs no network access and no file writes.
- Nothing is written to disk unless ``--output`` or ``--save-email-preview`` is
given an explicit path. v15 still wrote ``legal_changes_YYYYMM.json`` (``--json``)
and ``digest_YYYYMM.txt`` (``--email``) into the current directory, and the
``--email`` flag looked like sending when it only saved a file.
- ``--days`` is honoured by the BOE scan (one page per day) AND by the CCAA RSS
scan (entries older than the window are dropped by pubDate; entries without a
parseable date are kept and flagged ``date_unparsed``). In v15 the value reached
``RSSParser.fetch_and_filter`` but was never used.
- Progress lines go to stderr so ``--format json`` yields clean JSON on stdout.
- Exit code (v16.0.1): 0 when every requested source was scanned (COMPLETE),
1 when at least one requested source was unreachable / not configured or the
BOE scan failed for some day (PARTIAL or FAILED), 2 for input errors.
Output: text digest (ca/es/en) or structured JSON of legal changes.
"""
import requests
from requests.adapters import HTTPAdapter
import json
import re
import ssl
import sys
import os
import shutil
import subprocess
import tempfile
import unicodedata
import xml.etree.ElementTree as ET
from datetime import date, datetime, timedelta, timezone
from email.utils import parsedate_to_datetime
from html import unescape as html_unescape
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass, asdict, field
import hashlib
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from agent_version import AGENT_VERSION # noqa: E402
# Identify ourselves on every request. The default "python-requests/x.y" agent
# is a common WAF block trigger; a named agent is also the polite thing to send
# to public bodies. (Live check 2026-09-15: DOGV still answers 403 even with a
# browser User-Agent, so this is hygiene, not the fix for that source.)
HTTP_HEADERS = {
"User-Agent": f"RailNexus-LegalMonitor/{AGENT_VERSION} (+https://value.railnexus.io)",
}
# Per-source scan status vocabulary (v16.0.1). Distinguishes "we looked and
# found nothing relevant" from "we could not look".
SOURCE_OK = "OK" # fetched, at least one relevant entry
SOURCE_EMPTY = "EMPTY" # fetched, nothing relevant in window
SOURCE_UNREACHABLE = "UNREACHABLE" # HTTP error / network / parse failure
SOURCE_NOT_CONFIGURED = "NOT_CONFIGURED" # no machine-readable feed known
SOURCE_NO_ISSUE = "NO_ISSUE" # BOE: no issue published that day (API 404)
SOURCE_PARTIAL = "PARTIAL" # v17: some feeds of a source fetched, others failed
# v17: kinds of machine-readable feed a CCAA source may declare in ``feeds``.
FEED_KIND_RSS = "rss" # RSS 2.0 / Atom, parsed by RSSParser.parse_feed
FEED_KIND_SOCRATA = "socrata_json" # Socrata open-data resource (JSON rows)
# v18: generic JSON list service (one GET, or one GET per day with a ``{date}``
# placeholder) mapped to entries by the same field configuration as Socrata.
FEED_KIND_JSON_ROWS = "json_rows"
# v18: the DOGC summary API (calendar + one POST per issue, every section).
FEED_KIND_DOGC_SUMMARY = "dogc_summary"
# v19: the BOCM's own per-issue XML (issue list from sumarios.rss, one GET per
# issue), one <disposicion> per item with a real <titulo>.
FEED_KIND_BOCM_XML = "bocm_xml"
# v19: maximum BOCM issues fetched per run (the RSS lists the 20 newest; each
# XML is 1-5 MB).
BOCM_MAX_ISSUES_PER_RUN = 40
# v18: maximum issues fetched per run by the DOGC summary feed (the DOGC has at
# most one issue per calendar day; 60 covers a --days window of two months).
DOGC_MAX_ISSUES_PER_RUN = 60
# v20 (round 7): four CCAA whose bulletin has no RSS/Atom but DOES have a
# classic server-rendered HTML sumario, live-verified 2026-09-16 — one GET
# (Castilla-La Mancha, Asturias: per calendar day) or one calendar lookup +
# one GET per issue (Canarias, Navarra) returns real, dated, per-disposition
# titles with a PDF link. See CCAA_SOURCES["castilla_mancha"|"canarias"|
# "navarra"|"asturias"]["rss_last_check"] for the exact URLs and evidence.
FEED_KIND_DOCM_SUMARIO = "docm_sumario"
FEED_KIND_CANARIAS_BOC = "canarias_boc"
FEED_KIND_BON_SUMARIO = "bon_sumario"
FEED_KIND_BOPA_SUMARIO = "bopa_sumario"
# v20: Ceuta (BOCCE) publishes no feed of any kind, not even HTML — only a
# daily PDF behind a jdownloads component. This kind downloads the PDF and
# extracts disposition titles with the ``pdftotext`` CLI (poppler; no new
# Python dependency — see BOCCEClient).
FEED_KIND_PDF_ISSUE = "pdf_issue"
# v20: safety caps on per-run network/subprocess calls for the four new HTML
# sources (same purpose as BOCM_MAX_ISSUES_PER_RUN / DOGC_MAX_ISSUES_PER_RUN).
CANARIAS_MAX_ISSUES_PER_RUN = 40
BON_MAX_ISSUES_PER_RUN = 45
BOCCE_MAX_ISSUES_PER_RUN = 20
class _LegacyTLSAdapter(HTTPAdapter):
"""HTTPS adapter whose context accepts an OpenSSL security-level-1 server.
v18: ``portaldogc.gencat.cat`` (the DOGC API host) answers
``SSLV3_ALERT_HANDSHAKE_FAILURE`` to a default OpenSSL 3 client (security
level 2) and completes the handshake at ``DEFAULT:@SECLEVEL=1`` (verified
live 2026-09-16 with OpenSSL 3.0.21). Certificate verification and hostname
checking stay ON — only the minimum key/cipher strength is relaxed, and only
on the session that mounts this adapter for that host prefix.
"""
def init_poolmanager(self, *args, **kwargs):
context = ssl.create_default_context()
context.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0x4)
context.set_ciphers("DEFAULT:@SECLEVEL=1")
kwargs["ssl_context"] = context
return super().init_poolmanager(*args, **kwargs)
def legacy_tls_session(host_prefix: str) -> requests.Session:
"""Return a Session that uses :class:`_LegacyTLSAdapter` for one host only."""
session = requests.Session()
session.mount(host_prefix, _LegacyTLSAdapter())
return session
def repair_json_escapes(text: str) -> str:
"""Escape backslashes that do not start a valid JSON escape (pure).
v18: the BOA open-data JSON service emits ``\\_`` inside ``Texto`` (an
invalid escape that makes ``json.loads`` fail on the whole document). Only
a backslash NOT followed by ``" \\ / b f n r t u`` is doubled; valid escapes
are untouched.
"""
return re.sub(r'\\(?!["\\/bfnrtu])', r"\\\\", text or "")
def normalise_title(title: str) -> str:
"""Lower-case, accent-strip and whitespace-collapse a title (de-dup key)."""
stripped = unicodedata.normalize("NFKD", title or "")
stripped = "".join(ch for ch in stripped if not unicodedata.combining(ch))
return re.sub(r"\s+", " ", stripped).strip(" .;:").lower()
# BOE sumario sections scanned by default. Codes observed live 2026-09-10:
# "1" I. Disposiciones generales · "2A"/"2B" II. Autoridades y personal ·
# "3" III. Otras disposiciones · "4" IV. Administración de Justicia ·
# "5A" V.A Contratación del Sector Público · "5B" V.B Otros anuncios.
# Legal changes live in I and III. Sections V.A/V.B are procurement notices
# ("Anuncio de licitación… obras de construcción"): in the 2026-09-16 live run
# they were 94 of 105 keyword hits — noise for a legislation monitor. Pass
# ``--boe-sections all`` to scan everything.
BOE_DEFAULT_SECTIONS = ("1", "3")
# ═══════════════════════════════════════════════════════════
# DATA MODEL
# ═══════════════════════════════════════════════════════════
@dataclass
class LegalChange:
"""A single legal change detected."""
source: str # "BOE", "DOGC", "DOGV", etc.
date: str # Publication date
title: str # Title of the disposition
category: str # "CTE", "urbanismo", "vivienda", "eficiencia_energetica", etc.
impact_level: str # "ALTO", "MEDIO", "BAJO"
summary: str # Context line (BOE: sección · departamento · epígrafe; RSS: description)
url: str # Direct link to the official publication
affects_visado: bool # Does it change visado requirements?
ccaa: str # "nacional", "cataluña", "valencia", etc.
keywords_matched: List[str] # Which keywords triggered the match
date_unparsed: bool = False # v16: RSS entry kept although pubDate could not be parsed
identifier: str = "" # v16.0.1: BOE identifier (BOE-A-2026-18902) when known
section: str = "" # v16.0.1: BOE section code (1, 2A, 3, 5A...) when known
# ═══════════════════════════════════════════════════════════
# KEYWORDS — Construction & Architecture
# ═══════════════════════════════════════════════════════════
CONSTRUCTION_KEYWORDS = [
# Core building regulation
"código técnico de la edificación", "CTE", "documento básico",
"DB-HE", "DB-SI", "DB-SUA", "DB-HS", "DB-HR", "DB-SE", "DB-S",
"LOE", "ley de ordenación de la edificación",
# Urban planning
"urbanismo", "urbanística", "plan general", "PGOU", "POUM",
"plan parcial", "suelo urbanizable", "clasificación de suelo",
"ordenación del territorio", "planeamiento",
# Housing
"vivienda", "vivienda protegida", "VPO", "alquiler asequible",
"ley de vivienda", "rehabilitación energética",
# Energy & sustainability
"eficiencia energética", "certificación energética",
"emisiones", "huella de carbono", "nZEB", "passivhaus",
"renovación de edificios", "descarbonización",
# Construction process
"edificación", "construcción", "licencia de obra",
"visado colegial", "proyecto técnico", "dirección de obra",
"seguridad y salud", "coordinador de seguridad",
# Inspections
"ITE", "inspección técnica de edificios",
"informe de evaluación del edificio", "IEE",
# Accessibility
"accesibilidad", "barreras arquitectónicas",
# Specific regulations
"RITE", "reglamento de instalaciones térmicas",
"RSCIEI", "seguridad contra incendios",
"REBT", "reglamento electrotécnico",
# Catalan specific
"decret d'habitabilitat", "codi d'accessibilitat",
"llei d'urbanisme", "text refós urbanístic",
# v18: Catalan equivalents of the Spanish core terms, so DOGC / BOIB titles
# (Catalan only, no second-language fetch) match the same concepts.
"urbanisme", "urbanística", "planejament", "pla general", "pla parcial",
"pla de millora urbana", "modificació puntual", "sòl urbanitzable",
"classificació del sòl", "ordenació del territori",
"comissió territorial d'urbanisme", "habitatge", "habitatge protegit",
"habitatges de protecció oficial", "lloguer assequible", "llei d'habitatge",
"rehabilitació energètica", "eficiència energètica", "certificació energètica",
"edificació", "construcció", "llicència d'obres", "llicència urbanística",
"projecte tècnic", "direcció d'obra", "inspecció tècnica d'edificis",
"accessibilitat", "barreres arquitectòniques", "cèdula d'habitabilitat",
"expropiació", "expropiación",
# Valencian specific
"LOTUP", "ley de ordenación del territorio valenciana",
"ROGTU",
]
# Impact classification rules
HIGH_IMPACT_KEYWORDS = [
"CTE", "código técnico", "LOE", "ley de vivienda",
"DB-HE", "DB-SI", "DB-SUA", "visado", "eficiencia energética",
"certificación energética", "ITE", "nZEB",
# v18 Catalan
"llei d'habitatge", "eficiència energètica", "certificació energètica",
"llei d'urbanisme",
]
VISADO_KEYWORDS = [
"visado", "proyecto técnico", "documentación", "tramitación",
"licencia de obra", "certificado final de obra",
"dirección de obra", "coordinador de seguridad",
# v18 Catalan
"visat", "projecte tècnic", "llicència d'obres", "direcció d'obra",
]
def keyword_matches(text: str, keywords: List[str]) -> List[str]:
"""Return the keywords present in ``text`` as whole words (case-insensitive).
v15 used plain substring matching (``kw.lower() in text``), so the keyword
"ITE" matched "límite", "comité" or "literal" and "LOE" matched inside other
words; practically every BOE page therefore matched and was rated ALTO.
Word boundaries are implemented with look-arounds so hyphenated tokens such
as "DB-SI" and multi-word phrases keep working.
"""
lowered = (text or "").lower()
found = []
for kw in keywords:
pattern = r"(?<![\w])" + re.escape(kw.lower()) + r"(?![\w])"
if re.search(pattern, lowered) and kw not in found: # v18: no duplicates
found.append(kw)
return found
# ═══════════════════════════════════════════════════════════
# BOE API CLIENT
# ═══════════════════════════════════════════════════════════
class BOEClient:
"""
Client for the BOE OpenData API.
Docs: https://www.boe.es/datosabiertos/api/api.php
The BOE API provides:
- Daily summaries (sumario)
- Legislation search
- Document retrieval
"""
BASE_URL = "https://www.boe.es"
API_URL = "https://www.boe.es/datosabiertos/api"
@staticmethod
def get_sumario(date: str) -> Dict:
"""Fetch the structured daily sumario from the BOE OpenData API.
``date`` is ``YYYYMMDD``. Returns one of:
- ``{"status": "ok", "payload": <json>}``
- ``{"status": "no_issue"}`` — HTTP 404 whose body says the requested
information does not exist (no BOE that day: Sundays, some holidays).
Verified live 2026-09-06 -> ``<code>404</code><text>La información
solicitada no existe</text>``.
- ``{"status": "error", "code": N}`` / ``{"status": "error", "message": s}``
"""
url = f"{BOEClient.API_URL}/boe/sumario/{date}"
headers = dict(HTTP_HEADERS)
headers["Accept"] = "application/json"
try:
response = requests.get(url, timeout=20, headers=headers)
except Exception as e:
return {"status": "error", "message": str(e)}
if response.status_code == 404:
return {"status": "no_issue"}
if response.status_code != 200:
return {"status": "error", "code": response.status_code}
try:
payload = response.json()
except ValueError as e:
return {"status": "error", "message": f"non-JSON body: {e}"}
code = str((payload.get("status") or {}).get("code", "200"))
if code == "404":
return {"status": "no_issue"}
if code != "200":
return {"status": "error", "code": code,
"message": str((payload.get("status") or {}).get("text", ""))}
return {"status": "ok", "payload": payload}
@staticmethod
def parse_sumario(payload: Dict) -> List[Dict]:
"""Flatten an OpenData sumario payload into one record per disposition.
Pure function. The API nests ``data.sumario.diario[].seccion[]
.departamento[].(item[] | epigrafe[].item[])`` and — as is usual with
XML-derived JSON — emits a dict instead of a one-element list whenever
a level has a single child, so every level is normalised with
:func:`_as_list`. Record keys: ``identificador``, ``titulo``,
``url_html``, ``url_pdf``, ``seccion_codigo``, ``seccion_nombre``,
``departamento``, ``epigrafe``, ``fecha_publicacion``.
"""
records: List[Dict] = []
sumario = ((payload or {}).get("data") or {}).get("sumario") or {}
fecha = str((sumario.get("metadatos") or {}).get("fecha_publicacion", ""))
for diario in _as_list(sumario.get("diario")):
for seccion in _as_list(diario.get("seccion")):
sec_code = str(seccion.get("codigo", ""))
sec_name = str(seccion.get("nombre", ""))
for dep in _as_list(seccion.get("departamento")):
dep_name = str(dep.get("nombre", ""))
groups = [("", _as_list(dep.get("item")))]
for ep in _as_list(dep.get("epigrafe")):
groups.append((str(ep.get("nombre", "")), _as_list(ep.get("item"))))
for ep_name, items in groups:
for item in items:
if not isinstance(item, dict):
continue
url_pdf = item.get("url_pdf")
if isinstance(url_pdf, dict):
url_pdf = url_pdf.get("texto", "")
records.append({
"identificador": str(item.get("identificador", "")),
"titulo": str(item.get("titulo", "")).strip(),
"url_html": str(item.get("url_html", "")),
"url_pdf": str(url_pdf or ""),
"seccion_codigo": sec_code,
"seccion_nombre": sec_name,
"departamento": dep_name,
"epigrafe": ep_name,
"fecha_publicacion": fecha,
})
return records
@staticmethod
def get_daily_summary(date: str) -> Dict:
"""LEGACY (not used by the scanner since v16.0.1): fetch the HTML page
``/boe/dias/YYYY/MM/DD/``.
The page is the whole site template; its footer contains
``<a href="/informacion/accesibilidad/">Accesibilidad</a>`` on every
day, so a keyword scan over this content matches "accesibilidad" for
every date (26/26 in the 2026-09-15 live capture). Use
:meth:`get_sumario` + :meth:`parse_sumario` instead.
"""
url = f"{BOEClient.BASE_URL}/boe/dias/{date[:4]}/{date[4:6]}/{date[6:8]}/"
try:
response = requests.get(url, timeout=15, headers=HTTP_HEADERS)
if response.status_code == 200:
return {"status": "ok", "content": response.text}
return {"status": "error", "code": response.status_code}
except Exception as e:
return {"status": "error", "message": str(e)}
@staticmethod
def search_legislation(query: str, fecha_desde: str,
fecha_hasta: str) -> Dict:
"""
Search BOE legislation database.
Uses the BOE search endpoint:
/buscar/act.php?campo[0]=...
fecha format: DD/MM/YYYY
"""
params = {
"campo[0]": "ORI",
"dato[0]": "",
"operador[0]": "and",
"campo[1]": "TXT",
"dato[1]": query,
"operador[1]": "and",
"campo[2]": "FPU",
"dato[2]": f"{fecha_desde}-{fecha_hasta}",
"page_hits": "40",
"sort_field[0]": "fpu",
"sort_order[0]": "desc",
}
url = f"{BOEClient.BASE_URL}/buscar/act.php"
try:
response = requests.get(url, params=params, timeout=15)
return {"status": "ok", "url": response.url,
"content_length": len(response.text)}
except Exception as e:
return {"status": "error", "message": str(e)}
@staticmethod
def get_consolidated_code(code_id: str = "424") -> Dict:
"""
Get a consolidated legal code from BOE.
code_id 424 = Código Técnico de la Edificación
URL pattern: /biblioteca_juridica/codigos/codigo.php?id=XXX
"""
url = (f"{BOEClient.BASE_URL}/biblioteca_juridica/codigos/"
f"codigo.php?id={code_id}_Codigo_Tecnico_de_la_Edificacion_CTE"
f"&modo=2")
try:
response = requests.get(url, timeout=15)
return {"status": "ok", "url": url,
"last_modified": _extract_last_modified(response.text)}
except Exception as e:
return {"status": "error", "message": str(e)}
def _extract_last_modified(html: str) -> Optional[str]:
"""Extract 'Última modificación' date from BOE code page."""
match = re.search(r'ltima modificaci[óo]n:\s*(\d{1,2}\s+de\s+\w+\s+de\s+\d{4})', html)
return match.group(1) if match else None
def _as_list(value) -> List:
"""Normalise the BOE API's dict-or-list nesting to a list of dicts."""
if value is None:
return []
if isinstance(value, list):
return [v for v in value if isinstance(v, dict)]
if isinstance(value, dict):
return [value]
return []
# ═══════════════════════════════════════════════════════════
# CCAA RSS FEED SOURCES
# ═══════════════════════════════════════════════════════════
# ``rss_last_check`` records the most recent LIVE result for each source so a
# reader (or the digest) never assumes a configured URL works. Dead URLs are
# kept on purpose: every run retries them and reports UNREACHABLE; a feed that
# comes back is picked up without a code change. Checks were made both with the
# default python-requests agent and with a browser User-Agent.
#
# v17 source model: ``rss_url`` is the primary RSS/Atom URL (or None) and the
# optional ``feeds`` list declares every machine-readable feed of the bulletin
# (``kind`` = rss | socrata_json). ``feeds_for_source`` resolves either form.
CCAA_SOURCES = {
"cataluña": {
"name": "DOGC — Diari Oficial de la Generalitat de Catalunya",
# v18 (2026-09-16, round 5): the DOGC still publishes NO RSS/Atom, but
# its own "Sumari del DOGC" page is rendered from a REST API that the
# page's JavaScript calls: POST portaldogc.gencat.cat/eadop-rest/api/
# dogc/summaryDOGC (form: numDOGC, language) and .../calendarDOGC
# (month, year, language). Verified live: DOGC 9752 (16/09/2026) with
# six sections — Disposicions generals (e.g. "Edicte ... acord de la
# Comissió Territorial d'Urbanisme de l'Arc Metropolità"), Altres
# disposicions, Càrrecs i personal, Anuncis, Administració local (24
# ajuntaments that day), Altres subjectes emissors — every document
# with title and PDF link; language=es gives Spanish titles. The host
# needs an OpenSSL security-level-1 TLS context (see _LegacyTLSAdapter);
# round 3 saw "403" because a GET on the host root is 403 — the API
# POST is not. The Socrata dataset (Section 1 normative acts, with ELI
# HTML links and Spanish titles) is kept as a second, independent feed;
# duplicates across the two are removed by title.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_SOCRATA,
"label": "Normativa del DOGC (secció 1: lleis, decrets, ordres) — dades obertes",
"url": "https://analisi.transparenciacatalunya.cat/resource/n6hn-rmy7.json",
"dataset_id": "n6hn-rmy7",
"date_field": "data_de_publicaci_del_diari",
"title_fields": ["t_tol_de_la_norma"],
"description_template": "{rang_de_norma} · DOGC núm. {n_mero_de_diari} · {t_tol_de_la_norma_es}",
"url_field": "format_html.url",
"limit": 1000,
}, {
"kind": FEED_KIND_DOGC_SUMMARY,
"label": "Sumari del DOGC — API oficial (totes les seccions excepte Càrrecs i personal)",
"url": "https://portaldogc.gencat.cat/eadop-rest/api/dogc/summaryDOGC",
"language": "ca",
"sections_exclude": ["Càrrecs i personal"],
}],
"rss_note": "summary API covers every DOGC section (disposicions, altres disposicions, "
"anuncis, administració local, altres subjectes emissors; 'Càrrecs i "
"personal' excluded as noise) one issue at a time; Socrata dataset adds "
"Section 1 normative acts with ELI links; run daily",
"web_url": "https://dogc.gencat.cat",
"search_url": "https://dogc.gencat.cat/ca/sumari-del-dogc/",
"rss_last_check": {"date": "2026-09-16", "result": "no RSS/Atom feed exists; summaryDOGC "
"API verified: POST form numDOGC=9752&language=ca -> HTTP 200 JSON "
"35 KB, 6 sections, per-document titles + PDF links; calendarDOGC "
"month=9&year=2026 -> issue numbers per day (9742..9752); host needs "
"TLS SECLEVEL=1 (handshake failure at default level); Socrata "
"n6hn-rmy7: HTTP 200, newest row 2026-09-15 (DOGC núm. 9751), rang "
"values Llei/Decret/Decret llei/Decret legislatiu/Ordre only"},
},
"valencia": {
"name": "DOGV — Diari Oficial de la Generalitat Valenciana",
# v17 (2026-09-16): confirmed genuinely dead, no replacement found. Kept
# so every run retries it and reports UNREACHABLE (never silently absent).
"rss_url": "https://dogv.gva.es/datos/rss/dogv_es.xml",
"web_url": "https://dogv.gva.es",
"search_url": "https://dogv.gva.es/es/resultat-de-cerca",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 403 with default AND browser "
"User-Agent for dogv_es.xml, dogv_va.xml, dogv.xml and the /datos/rss/ "
"folder (server-side block); /es/rss, /rss/dogv_es.xml and "
"/es/rss/dogv_es.xml redirect to the HTML home; no <link rel=alternate> "
"feed on any page; 'Alertas y subscripciones' redirects to the "
"personal-area login; GVA open data (dadesobertes.gva.es): "
"package_search HTTP 500, package_list (1309 packages) has no DOGV "
"dataset; datos.gob.es: no DOGV bulletin dataset. NO machine-readable "
"feed exists today — manual search only"},
},
"madrid": {
"name": "BOCM — Boletín Oficial de la Comunidad de Madrid",
# v18 (round 4): ``sumarios.rss`` wired but issue-level (one entry per
# "Boletín Nº NNN", description "Descargar PDF") — nothing to match.
# v19 (2026-09-16, round 6): new feed kind ``bocm_xml`` — the RSS is
# used as the issue calendar (its links carry date + number) and each
# issue's native XML (``/boletin/CM_Boletin_BOCM/YYYY/MM/DD/BOCM-
# YYYYMMDDNNN.xml``) is parsed: one <disposicion> per item with a real
# <titulo> (84 distinct on 16/09/2026, 49 on 14/09/2026; e.g. "– Madrid.
# Urbanismo. ... Plan especial", "– Pinto. Urbanismo. Plan urbanístico").
# "IV. ADMINISTRACIÓN DE JUSTICIA" and the apartado "B) Autoridades y
# Personal" are excluded as noise (same criterion as DOGC "Càrrecs i
# personal"). Limit: the RSS lists only the 20 newest issues (~24
# calendar days), stated in the feed record as ``oldest_issue``.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_BOCM_XML,
"label": "BOCM — XML nativo por número (todas las secciones salvo IV. Justicia y B) Personal)",
"url": "https://www.bocm.es/sumarios.rss",
"sections_exclude": ["IV. ADMINISTRACIÓN DE JUSTICIA"],
"apartados_exclude": ["B) Autoridades y Personal"],
}],
"rss_note": "per-issue native XML with real disposition titles; the RSS calendar "
"covers the 20 newest issues only — run daily (or at least every 3 weeks)",
"web_url": "https://www.bocm.es",
"search_url": "https://www.bocm.es/buscador-702",
"rss_last_check": {"date": "2026-09-16", "result": "sumarios.rss HTTP 200, 20 issues "
"(2026-08-24..2026-09-16) linking boletin-completo/BOCM-YYYYMMDD/NNN; "
"CM_Boletin_BOCM/2026/09/16/BOCM-20260916221.xml HTTP 200 text/xml 3.9 MB, "
"3570 <disposicion> nodes = 84 distinct identificador with <titulo>; "
"14/09 1.4 MB 49 distinct; 12/09 180 KB 18 distinct; a no-issue date "
"(13/09, Sunday) answers 404"},
},
"andalucia": {
"name": "BOJA — Boletín Oficial de la Junta de Andalucía",
# v17 (2026-09-16): the old /eboja/rss/rss.html is 404. Every BOJA issue
# page advertises <link rel="alternate" type="application/atom+xml"> feeds
# under /boja/distribucion/ and the official FAQ "Distribución de RSS"
# (eboja/preguntas-frecuentes/faq4.html) names s51.xml explicitly. Scheme
# verified live: s51 = "1. Disposiciones generales", s52 = "2.1.
# Nombramientos", s53 = "2.2. Oposiciones", s54 = "3. Otras disposiciones",
# s55 = "4. Administración de justicia"; boja.xml = whole issues. Sections
# 1 and 3 are scanned (same choice as the BOE default). Each feed holds the
# CURRENT issue only (nº 180 of 16/09/2026 at verification), so daily runs
# are needed for continuous coverage.
# TRAP: the legacy s0.xml..s5.2.xml still answer HTTP 200 and parse, but are
# frozen at issue 2021/217 (lastBuildDate 2021-11-11) with undated entries —
# the age filter would keep them as "current". Never configure them.
"rss_url": "https://www.juntadeandalucia.es/boja/distribucion/s51.xml",
"feeds": [
{"kind": FEED_KIND_RSS, "label": "1. Disposiciones generales",
"url": "https://www.juntadeandalucia.es/boja/distribucion/s51.xml"},
{"kind": FEED_KIND_RSS, "label": "3. Otras disposiciones",
"url": "https://www.juntadeandalucia.es/boja/distribucion/s54.xml"},
],
"rss_note": "current-issue feeds (sections 1 and 3); run daily for continuous coverage",
"web_url": "https://www.juntadeandalucia.es/boja",
"search_url": "https://www.juntadeandalucia.es/eboja/buscador",
"rss_last_check": {"date": "2026-09-16", "result": "s51.xml HTTP 200 Atom '1. "
"Disposiciones generales' (2 dated entries, issue 180 of 16/09/2026); "
"s54.xml HTTP 200 Atom '3. Otras disposiciones' (12 entries); old "
"/eboja/rss/rss.html 404; legacy s0..s5.2.xml 200 but frozen at "
"2021/217 — excluded"},
},
"pais_vasco": {
"name": "BOPV — Boletín Oficial del País Vasco (EHAA)",
# v17 (2026-09-16): the old /contenidos/informacion/ehaa_rss/... is 404.
# The official "Último boletín" page (web01-bopv/es/bopv2/datos/Ultimo.shtml)
# links "RSS" -> /bopv2/datos/Ultimo.xml: RSS 2.0, channel "Boletín Nº 176,
# fecha 15/09/2026", 16 entries with disposition titles, pubDate and URL;
# fetch_feed(30 days) -> OK with 2 construction matches. It covers the
# LATEST issue only, so daily runs are needed for continuous coverage.
"rss_url": "https://www.euskadi.eus/bopv2/datos/Ultimo.xml",
"rss_note": "latest-issue feed (all sections of the newest BOPV number); run daily "
"for continuous coverage",
"web_url": "https://www.euskadi.eus/web01-bopv/es/",
"search_url": "https://www.euskadi.eus/y22-bopv/es/bopv2/datos/buscador.shtml",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 application/xml RSS 2.0, "
"16 dated entries (Boletín Nº 176, 15/09/2026), 2 construction matches "
"within 30 days; old ehaa_rss URL 404"},
},
"galicia": {
"name": "DOG — Diario Oficial de Galicia",
# v16.0.1: previous URL (…/dog/publicados/rss/dog_es.xml) answered 404.
# This one is advertised on /diario-oficial-galicia/suscricionsRSS.do and
# answered HTTP 200 application/rss+xml on 2026-09-15 — but each entry is
# a whole ISSUE ("Sumario", link to the Indice PDF), not a disposition,
# so the keyword scan cannot match anything in it. Kept so the source is
# honestly FETCHED (status EMPTY with the note below) rather than dead.
"rss_url": "https://www.xunta.gal/diario-oficial-galicia/rss/Seccion1_es.rss",
"rss_note": "issue-level feed: entries are the daily 'Sumario' PDF, no disposition "
"titles — keyword scan cannot match; manual search required",
"web_url": "https://www.xunta.gal/diario-oficial-galicia",
"search_url": "https://www.xunta.gal/dog/publicados/buscaDog.do",
"rss_last_check": {"date": "2026-09-15", "result": "HTTP 200 application/rss+xml, "
"2 entries, both 'Sumario' (issue index)"},
},
"castilla_leon": {
"name": "BOCYL — Boletín Oficial de Castilla y León",
# v18 (2026-09-16, round 4): the "RSS" link on /indiceRss.do ("BOCYL
# completo") resolves to /rss (redirects to /rss.do): RSS 2.0, ONE
# entry per day ("Boletín del día 15/09/2026 edición 179") whose
# description embeds the day's item list as HTML, which is enough
# for the keyword scan to match (live-verified: 1 construction match
# in the 2026-09-16 capture). Per-section feeds also exist
# (rss.do?seccion=I..V) but were not live-verified in this round.
# JCyL's own open-data portal separately publishes the whole BOCYL
# index (64,072 rows, dataset "bocyl", modified 2026-09-15) as CSV on
# an OpenDataSoft platform (datosabiertos.jcyl.es) — a genuine
# alternative, left unwired because it needs a new feed kind
# (OpenDataSoft's Explore API v2.1 differs from the Socrata shape
# already supported for DOGC).
"rss_url": "https://bocyl.jcyl.es/rss",
"rss_note": "latest-issue feed (one entry per day, whole boletín); run daily for "
"continuous coverage",
"web_url": "https://bocyl.jcyl.es",
"search_url": "https://bocyl.jcyl.es/buscador.do",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 text/xml RSS 2.0, 1 "
"dated entry (edición 179, 15/09/2026), 1 construction match "
"within 30 days"},
},
"aragon": {
"name": "BOA — Boletín Oficial de Aragón",
# v18 (2026-09-16, round 5): NO RSS/Atom (round 4 findings stand:
# Angular SPA, /rss 404, SEC=RSS returns the SPA shell) — but Aragón's
# CKAN lives at opendata.aragon.es/aod/api/3/ (round 4 tried
# /datos/catalogo/api/3/, 404) and its dataset "Decretos y Leyes
# aprobados por el Gobierno de Aragón" publishes the BOA's own
# open-data JSON service as the resource URL: cgi-bin/EBOA/BRSCGI
# ?CMD=VERLST&OUTPUTMODE=JSON&SEC=OPENDATABOAJSON&@PUBL-GE=YYYYMMDD...
# Verified live with a 30-day window: HTTP 200, 608 records (I:12,
# II:196, III:157, V:243), fields NOrden/DOCN/FechaPublicacion/
# Numeroboletin/Seccion/Subseccion/Fechadisposicion/Rango/Emisor/
# Titulo/UriEli/Texto/CodigoMateria/UrlPdf/UrlBCOM; newest record
# dated today (20260916). Quirks handled: ISO-8859-1 body declared as
# text/html; invalid "\_" JSON escapes inside Texto (lenient_json);
# the FULL parameter set is required (a minimal query returns the SPA
# HTML); SECC-C=Disposiciones yields sections I + III (169 rows, 2 MB
# because Texto is included). Document page: BRSCGI?CMD=VERDOC&
# BASE=BZHT&DOCN=<DOCN>&SEC=BUSQUEDA_AVANZADA (verified: title in body).
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_JSON_ROWS,
"label": "BOA datos abiertos JSON (secciones I y III, ventana por fecha de publicación)",
"url": "https://www.boa.aragon.es/cgi-bin/EBOA/BRSCGI",
"params": {"CMD": "VERLST", "OUTPUTMODE": "JSON", "BASE": "BZHT", "DOCS": "1-2000",
"SEC": "OPENDATABOAJSON", "SORT": "-PUBL", "SEPARADOR": "",
"@PUBL-GE": "{since:%Y%m%d}", "@PUBL-LE": "", "NUMB": "", "RANG": "",
"TITU-C": "", "FDIS-C": "", "TITU": "", "ORGA-C": "", "TEXT-C": "",
"SECC-C": "Disposiciones", "SECC": "", "SUBS-C": ""},
"lenient_json": True,
"timeout": 120,
"title_fields": ["Titulo"],
"scan_fields": ["Titulo"],
"date_field": "FechaPublicacion",
"date_format": "%Y%m%d",
"url_template": "https://www.boa.aragon.es/cgi-bin/EBOA/BRSCGI?CMD=VERDOC&BASE=BZHT"
"&DOCN={DOCN}&SEC=BUSQUEDA_AVANZADA",
"description_template": "{Seccion} · {Subseccion} · {Rango} · {Emisor} · BOA nº "
"{Numeroboletin} · ELI: {UriEli}",
}],
"rss_note": "open-data JSON service of the BOA itself, sections I + III (set SECC-C to "
"'Disposiciones+o+Anuncios' to add V. Anuncios); one request per run with "
"a server-side publication-date window",
"web_url": "https://www.boa.aragon.es",
"search_url": "https://www.boa.aragon.es/cgi-bin/EBOA/BRSCGI",
"rss_last_check": {"date": "2026-09-16", "result": "no RSS/Atom (SPA); BOA open-data "
"JSON verified: HTTP 200, 608 dispositions in 30 days (169 in I+III), "
"newest 20260916, per-disposition title/section/rank/ELI; producer "
"emits invalid JSON escapes and ISO-8859-1 (repaired); found via "
"opendata.aragon.es/aod/api/3 package 'decretos-y-leyes-...'"},
},
"castilla_mancha": {
"name": "DOCM — Diario Oficial de Castilla-La Mancha",
# v18 (2026-09-16, round 4): NO RSS/Atom found. docm.jccm.es has no
# <link rel=alternate> feed; /docm/rss.do (500), /docm/rss.xml,
# /portaldocm/rss.xml, /docm/rss/docm.xml (all 404) and
# /docm/alertas.do is an e-mail subscription form, not a feed. The
# region's open-data portals have no CKAN-style API at the usual
# paths and datosabiertos.jccm.es does not resolve in DNS.
# v20 (2026-09-16, round 7): wired as a classic HTML sumario instead.
# docm.jccm.es/docm/sumario.do is a plain server-rendered page (no
# JS), and its own calendar links each day to
# /docm/cambiarBoletin.do?fecha=YYYYMMDD (no session needed — a fresh
# GET per date). Verified live: 16/09/2026 (Núm. 178) -> 17 dated
# per-disposition entries with real titles ("Régimen Local.
# Resolución de 08/09/2026, de la Viceconsejería de Administración
# Local..."), PDF links, categories ("I.- DISPOSICIONES GENERALES",
# "II.- AUTORIDADES Y PERSONAL", "III.- OTRAS DISPOSICIONES Y ACTOS",
# "V.- ANUNCIOS"); 15/09/2026 -> 32 entries; Sunday 13/09/2026 -> HTTP
# 200 with NO fechaDiario header and 0 entries (the "no issue" signal
# — never a 404). "II.- AUTORIDADES Y PERSONAL" excluded as noise.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_DOCM_SUMARIO,
"label": "DOCM — sumario HTML diario (cambiarBoletin.do, un GET por día)",
"url": "https://docm.jccm.es/docm/sumario.do",
"sections_exclude": ["II.- AUTORIDADES Y PERSONAL"],
}],
"rss_note": "per-disposition titles from the daily HTML sumario (one GET per day of "
"the window); 'II.- AUTORIDADES Y PERSONAL' excluded as noise",
"web_url": "https://docm.jccm.es",
"search_url": "https://docm.jccm.es/portaldocm/busquedaAvanzada.do",
"rss_last_check": {"date": "2026-09-16", "result": "no <link rel=alternate> feed; "
"/docm/rss.do HTTP 500, /docm/rss.xml, /portaldocm/rss.xml, "
"/docm/rss/docm.xml all 404; /docm/alertas.do is an e-mail "
"subscription form; datos.castillalamancha.es and transparencia."
"castillalamancha.es both resolve (200) but /api/3/action/"
"package_search and /data.json are 404 on both; "
"datosabiertos.jccm.es does not resolve; round 5: /docm/rss.do?"
"seccion=1 and /portaldocm/rss.do HTTP 500, /docm/rss -> HTML "
"home, datosabiertos.castillalamancha.es 404, datos.gob.es lists "
"no DOCM dataset — NO machine-readable feed exists today; "
"round 7: HTML sumario wired instead — "
"cambiarBoletin.do?fecha=20260916 HTTP 200, 17 dated entries "
"(Núm. 178, Miércoles 16 de septiembre de 2026); "
"?fecha=20260915 HTTP 200, 32 entries; ?fecha=20260913 (Sunday) "
"HTTP 200 with no fechaDiario header (no issue that day)"},
},
"canarias": {
"name": "BOC — Boletín Oficial de Canarias",
# v18 (2026-09-16, round 4): confirmed genuinely dead, with a trap.
# The BOC's own "/boc/rss/" index page LINKS an extensive scheme
# (./capitulo/*.rss, ./cabildo/*.rss, ./ayuntamiento/*.rss — one feed
# per chapter/council/town) but every ./capitulo/, ./cabildo/ and
# ./ayuntamiento/ URL answers 404 "Control de Errores" on the BOC's
# own server — these are broken links published by the site itself,
# not a working scheme with a different base path. A handful of
# root-level topic feeds (ayudas_y_subvenciones.rss, educacion.rss,
# empleo_publico.rss, oposiciones_y_consursos.rss) DO answer HTTP 200
# application/rss+xml, but every entry is frozen at "BOC 2012/201"
# (October 2012) — the same kind of dead-but-200 trap documented for
# BOJA's legacy s0..s5.2.xml feeds. suscripcionesrss.html redirects to
# an unrelated internal employee portal.
# v20 (2026-09-16, round 7): wired via the sede.gobiernodecanarias.org
# portal's own client-side calendar — not RSS, but a plain date-to-
# issue lookup (www.gobiernodecanarias.org/boc/boc_index.js, called
# by the "Consulta por fecha" widget) followed by a static per-issue
# HTML page. Verified live: boc_index.js's newest entry
# A(20260916186) = issue 186 published today; /boc/2026/186/
# index.html -> HTTP 200, real per-disposition titles ("ORDEN de 4 de
# septiembre de 2026, por la que se aprueban las bases reguladoras
# de..."), sections "I. Disposiciones generales" .. "V. Anuncios".
# The server declares no charset for text/html — requests must force
# UTF-8 or accents garble (same fix as the BOA in v18). "II.
# Autoridades y personal" excluded as noise.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_CANARIAS_BOC,
"label": "BOC — sumario HTML por número (calendario boc_index.js + index.html)",
"url": "https://www.gobiernodecanarias.org/boc/boc_index.js",
"sections_exclude": ["II. Autoridades y personal"],
}],
"rss_note": "per-disposition titles via a date->issue-number calendar (boc_index.js) "
"plus one GET per issue; 'II. Autoridades y personal' excluded as noise",
"web_url": "http://www.gobiernodecanarias.org/boc/",
"search_url": "http://www.gobiernodecanarias.org/boc/archivo/",
"rss_last_check": {"date": "2026-09-16", "result": "the site's own /boc/rss/ index "
"links ./capitulo/*.rss, ./cabildo/*.rss and ./ayuntamiento/*.rss, "
"but every one of those URLs is 404 'Control de Errores' on the "
"server; the few root-level topic feeds that DO answer 200 "
"application/rss+xml (ayudas_y_subvenciones.rss, educacion.rss, "
"empleo_publico.rss, oposiciones_y_consursos.rss) are frozen at "
"'BOC 2012/201' — never use them; suscripcionesrss.html redirects "
"to an unrelated internal portal; round 5: the new sede."
"gobiernodecanarias.org/boc/ portal has no /rss/ (404), datos."
"canarias.es CKAN (catalogos/general/api/3) has no BOC dataset "
"(only municipal planning datasets), datos.gob.es lists none — "
"NO working feed exists today; round 7: HTML sumario wired instead "
"— boc_index.js HTTP 200, A(20260916186) = issue 186/2026 "
"(today); /boc/2026/186/index.html HTTP 200, 7 dated entries "
"outside 'Autoridades y personal'"},
},
"extremadura": {
"name": "DOE — Diario Oficial de Extremadura",
# v18 (2026-09-16, round 4): the homepage advertises 6
# <link rel=alternate> feeds (rss/rss.php?seccion=0..5), one per DOE
# section, plus an unlisted seccion=6 "SUMARIO COMPLETO" found on the
# RSS help page. seccion=6 answered HTTP 200 text/xml with 16 dated,
# per-disposition entries, all 2026-09-16 (today's issue), titles are
# real disposition text ("Resolución de 7 de septiembre de 2026,
# del Vicepresidente..."), links to the disposition PDF. seccion=3
# ("Otras resoluciones", 10 entries) and seccion=4 ("Administración de
# Justicia", 6 entries) are subsets of seccion=6; seccion=0,1,2,5
# answered 200 but with an EMPTY channel (0 items) on this date.
"rss_url": "https://doe.juntaex.es/rss/rss.php?seccion=6",
"rss_note": "'SUMARIO COMPLETO' — every section of the current issue in one feed; "
"per-disposition titles",
"web_url": "http://doe.juntaex.es",
"search_url": "http://doe.juntaex.es/busqueda/busqueda.php",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 text/xml, 16 dated "
"per-disposition entries, all 2026-09-16; seccion=0,1,2,5 are "
"empty channels on this date (not dead, just no items today); "
"/rss/rss.xml is 404 and /ultimosdoe/ is 403"},
},
"baleares": {
"name": "BOIB — Butlletí Oficial de les Illes Balears",
# v18 (2026-09-16, round 4): the homepage's <link rel=alternate>
# points to /root/rss.do?path=/eboibfront/indexrss.do..., which
# redirects to the general govern.caib.es portal (HTML, not the
# feed) — but the target path itself
# (/eboibfront/indexrss.do?lang=ca, same content under /eboibfront/
# ca/rss) answers HTTP 200 application/rss+xml directly. RSS 2.0, 13
# dated entries, newest 2026-09-15 (BOIB Núm 115/2026). Issue-level
# (like DOG/BOCM) — each entry is one day's whole issue, linking to
# an HTML page that lists that issue's individual dispositions
# (which in turn have per-disposition XML, but that is a second hop
# this monitor does not follow).
"rss_url": "https://www.caib.es/eboibfront/indexrss.do?lang=ca",
"rss_note": "issue-level feed: entries are the daily 'BOIB Núm N/YYYY' issue, no "
"per-disposition titles — manual search recommended for full coverage",
"web_url": "https://www.caib.es/eboibfront/",
"search_url": "https://www.caib.es/eboibfront/ca/2026",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 application/rss+xml RSS "
"2.0, 13 dated entries, newest 2026-09-15 (BOIB Núm 115/2026); the "
"advertised <link rel=alternate> (/root/rss.do?path=...) redirects "
"to the generic govern.caib.es HTML portal, not the feed itself — "
"use /eboibfront/indexrss.do?lang=ca directly"},
},
"murcia": {
"name": "BORM — Boletín Oficial de la Región de Murcia",
# v18 (2026-09-16, round 5): NO RSS/Atom (round 4 stands), but the
# SPA's own factories (scripts/boletines/factories/boletinFactory.js)
# call services/boletin/fecha/DD-MM-YYYY/sumario, which answers HTTP
# 200 JSON with the issue and its ``anunciosBoletin`` list — one record
# per announcement: sumario (title), anunciante, apartado ("I.
# Comunidad Autónoma", "IV. Administración Local"...), subApartado,
# numero, numeroBoletin, fechaPublicacion (dd-mm-yyyy). Verified live:
# 16-09-2026 -> 31 announcements, 15-09-2026 -> 17, Saturday 12-09 ->
# issue exists, Sunday 13-09 -> HTTP 404 JSON "errorBusqueda" (no
# issue). Announcement page (SPA route home.anuncio, app.js):
# /#/home/anuncio/<fecha>/<numero>; PDF: services/anuncio/<id>/pdf.
# The CKAN "Índices del BORM" datasets stop at 2015 (not used).
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_JSON_ROWS,
"label": "BORM sumario diario (servicio JSON del propio boletín, un día por petición)",
"url": "https://www.borm.es/services/boletin/fecha/{date:%d-%m-%Y}/sumario",
"per_day": True,
"no_issue_status": [404],
"rows_path": "anunciosBoletin",
"title_fields": ["sumario"],
"scan_fields": ["sumario"],
"date_field": "fechaPublicacion",
"date_format": "%d-%m-%Y",
"url_template": "https://www.borm.es/#/home/anuncio/{fechaPublicacion}/{numero}",
"description_template": "{apartado} · {subApartado} · {anunciante} · BORM nº {numeroBoletin}",
"exclude_values": {"subApartado": ["2. Autoridades y Personal"]},
}],
"rss_note": "per-announcement titles from the daily sumario service (one request per "
"day of the window; 'Autoridades y Personal' excluded as noise)",
"web_url": "https://www.borm.es",
"search_url": "https://www.borm.es/#/home/busqueda",
"rss_last_check": {"date": "2026-09-16", "result": "no RSS/Atom (SPA); services/boletin/"
"fecha/<dd-mm-yyyy>/sumario verified: HTTP 200 JSON, 31 announcements "
"on 16-09-2026 with titles/apartados, 404 on days without issue"},
},
"navarra": {
"name": "BON — Boletín Oficial de Navarra",
# v18 (2026-09-16, round 4): NO RSS/Atom found. bon.navarra.es is a
# Liferay portal; /es/rss, /es/rss.xml, /rss.xml, /es/boletin/rss and
# /es/ultimo-boletin all 404 (Liferay's own "Estado" error page); the
# "3. Alertas y anuncios" help page describes e-mail subscriptions
# only. Navarra's open-data portal (CKAN) has no BON dataset.
# v20 (2026-09-16, round 7): wired as a classic HTML sumario instead.
# bon.navarra.es/es/boletin (latest issue) and /es/boletin/-/sumario/
# {year}/{number} (any past issue) are plain server-rendered pages
# with real, per-disposition titles. Verified live: /es/boletin ->
# HTTP 200, "BOLETÍN Nº 184 - 16 de septiembre de 2026" header; issue
# 183 (15/09/2026) -> HTTP 200, 57 dated entries with real titles
# ("RESOLUCIÓN 6512E/2026, de 17 de agosto, del director general de
# Interior..."), sections "1. Comunidad Foral de Navarra", "2.
# Administración Local de Navarra", "6. Otros anuncios". Issue
# numbers run sequentially per calendar year (~1/business day), so
# the window is walked backwards by NUMBER from the latest issue,
# reading each page's own header to confirm its true date.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_BON_SUMARIO,
"label": "BON — sumario HTML por número (/es/boletin/-/sumario/{year}/{number})",
"url": "https://bon.navarra.es/es/boletin",
}],
"rss_note": "per-disposition titles walking backwards by issue number from the "
"latest issue (issue numbers run sequentially per calendar year)",
"web_url": "https://bon.navarra.es",
"search_url": "https://bon.navarra.es/es/buscador-bon",
"rss_last_check": {"date": "2026-09-16", "result": "Liferay portal; /es/rss, "
"/es/rss.xml, /rss.xml, /es/boletin/rss, /es/ultimo-boletin all 404 "
"(Liferay error page); 'Alertas y anuncios' help page describes "
"e-mail subscriptions only; datosabiertos.navarra.es CKAN "
"package_search for 'BON' returns 0 results; round 5: CKAN "
"'boletin' -> 1 unrelated dataset, 'BON disposiciones' -> 0, "
"/es/rss/boletin 404, datos.gob.es lists no BON dataset — NO "
"machine-readable feed exists today; round 7: HTML sumario wired "
"instead — /es/boletin HTTP 200 (Nº 184, 16/09/2026); "
"/es/boletin/-/sumario/2026/183 HTTP 200, 57 dated entries "
"(Nº 183, 15/09/2026)"},
},
"rioja": {
"name": "BOR — Boletín Oficial de La Rioja",
# v18 (2026-09-16, round 4): confirmed genuinely dead. The portal
# moved from ias1.larioja.org/bor/ (404) to web.larioja.org/
# bor-portada; that page and /suscripciones (a login-gated
# subscription form) carry no feed link; /bor-portada/rss.xml, /rss
# both resolve to the plain HTML portal, not a feed;
# ias1.larioja.org/boletin/rss and larioja.org/bor/rss are 404. The
# region's open-data host (datos.larioja.org) does not resolve in
# DNS at all.
"rss_url": None,
"web_url": "https://ias1.larioja.org/bor/",
"search_url": "https://ias1.larioja.org/bor/Bor",
"rss_last_check": {"date": "2026-09-16", "result": "ias1.larioja.org/bor/ 404; portal "
"moved to web.larioja.org/bor-portada, no feed link there or on "
"/suscripciones (login-gated form); /bor-portada/rss.xml and /rss "
"both resolve to the plain HTML portal; ias1.larioja.org/boletin/rss "
"and larioja.org/bor/rss 404; datos.larioja.org does not resolve in "
"DNS; round 5: bor-portada HTML carries no rss/api/json hint "
"(only /bor-portada/bor, /masbor, /bor-calendario links), "
"web.larioja.org/datos-abiertos is an HTML page, datos.gob.es "
"lists no BOR dataset — NO machine-readable feed exists today"},
},
"cantabria": {
"name": "BOC — Boletín Oficial de Cantabria",
# v18 (2026-09-16, round 4): boc.cantabria.es itself has no RSS
# (/boces/rss.do, /boces/rss, /boces/verRSS.do, /boces/rss/boc.xml
# all 404; /rss is a WAF 403 page). Its own page links "RSS
# Cantabria informa" to www.cantabria.es/web/gobierno/enlaces_rss,
# a Liferay page that lists 19 separate BOC feeds, one per BOC
# section, as .../o/BOC/feed/<assetId>. Feed 6802081 ("1
# Disposiciones Generales") answered HTTP 200 text/xml, 100 dated,
# PER-DISPOSITION entries (real titles, e.g. municipal ordinance
# approvals), newest 2026-09-16, 1 construction-keyword match within
# 30 days. Only section 1 is wired (BOE/BOJA precedent: procurement/
# administrative sections are noise for a legislation monitor); the
# other 18 section feeds are documented above but not wired.
"rss_url": "http://www.cantabria.es/o/BOC/feed/6802081",
"rss_note": "section 1 'Disposiciones Generales' only; 18 other BOC section feeds "
"exist at www.cantabria.es/web/gobierno/enlaces_rss but are not wired",
"web_url": "https://boc.cantabria.es",
"search_url": "https://boc.cantabria.es/boces/verBuscadorContenidos.do",
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 text/xml, 100 dated "
"per-disposition entries, newest 2026-09-16, 1 construction match "
"within 30 days; boc.cantabria.es itself has no working RSS "
"endpoint (all 404 or WAF 403) — the feed lives on the Liferay "
"www.cantabria.es host instead"},
},
"asturias": {
"name": "BOPA — Boletín Oficial del Principado de Asturias",
# v18 (2026-09-16, round 4): NO RSS/Atom found. sede.asturias.es/bopa
# redirects to a Liferay portal at miprincipado.asturias.es; /bopa/
# rss, /rss/bopa.xml (both hosts) all 404, and a Liferay
# "/o/<plugin>/feed" guess found nothing. round 5: datos.gob.es lists
# an official open-data dataset — but it is a YEARLY archive (the
# 2025 file, no 2026 file on 2026-09-16), useless for monitoring.
# v20 (2026-09-16, round 7): wired as a classic HTML sumario instead.
# The miprincipado.asturias.es portal's own "Consultar por fecha"
# widget calls /bopa-sumario?...&p_r_p_summaryDate=DD%2FMM%2FYYYY
# directly (no session needed). Verified live: 16/09/2026 -> HTTP
# 200, "Boletín Nº 179 del miércoles 16 de septiembre de 2026" header,
# 23 dated entries with real titles ("Resolución de 10 de septiembre
# de 2026, de la Consejería de Presidencia, Reto Demográfico,
# Igualdad y Turismo, por la que se somete a trámite de información
# pública el proyecto de Decreto por el que se regulan los
# apartamentos turísticos"), sections "I. Principado de Asturias",
# "IV. Administración Local", "VI. Otros Anuncios". A date with NO
# issue does not 404 — it silently serves the nearest available
# bulletin (verified: Sunday 13/09/2026 returned the 16/09 content
# unchanged); the client reads the page's own <h1> date and discards
# any day whose returned date does not match what was requested.
# "AUTORIDADES Y PERSONAL" subsections excluded as noise.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_BOPA_SUMARIO,
"label": "BOPA — sumario HTML diario (bopa-sumario, un GET por día)",
"url": "https://miprincipado.asturias.es/bopa-sumario",
"sections_exclude": ["AUTORIDADES Y PERSONAL"],
}],
"rss_note": "per-disposition titles from the daily HTML sumario (one GET per day of "
"the window, cross-checked against the page's own date to detect the "
"portal's silent fallback to the nearest bulletin); 'AUTORIDADES Y "
"PERSONAL' excluded as noise",
"web_url": "https://sede.asturias.es/bopa",
"search_url": "https://sede.asturias.es/bopa-disposiciones",
"rss_last_check": {"date": "2026-09-16", "result": "sede.asturias.es/bopa redirects "
"to the Liferay portal miprincipado.asturias.es; /bopa/rss, "
"/rss/bopa.xml on both hosts all 404; a Cantabria-style "
"'/o/<plugin>/feed' guess found nothing (404 or redirect to the "
"plain homepage, not a feed); round 5: datos.gob.es lists an "
"official open-data dataset 'Disposiciones publicadas en el BOPA' "
"(descargas.asturias.es/.../dataset-sum-bopa-<year>.csv|xml|json, "
"one file per YEAR: the 2025 file, 10,654 rows with titles/sections/"
"URLs, was last modified 2026-08-17; no 2026 file exists on "
"2026-09-16) — a yearly archive, not a monitoring feed; "
"datos.asturias.es does not resolve; round 7: HTML sumario wired "
"instead — bopa-sumario?...&p_r_p_summaryDate=16%2F09%2F2026 HTTP "
"200, 23 dated entries (Nº 179, 16/09/2026); Sunday "
"13/09/2026 silently falls back to the nearest bulletin instead "
"of 404ing — handled by verifying the page's own <h1> date"},
},
"ceuta": {
"name": "BOCCE — Boletín Oficial de la Ciudad de Ceuta",
# v18 (2026-09-16, round 4): confirmed genuinely dead FOR AN RSS/HTML
# FEED. ceuta.es/ceuta/ (the city portal) advertises <link
# rel=alternate> feeds (?format=feed&type=rss/atom) and they do
# answer HTTP 200 — but they are the city's GENERAL news feed
# (courses, library hours, grant calls), unrelated to BOCCE; the
# BOCCE page itself lists each issue only as a downloadable PDF via
# a jdownloads component (BOCCE_6652_15-09-2026, etc.), with no feed
# of its own and no <link rel=alternate> on that specific page.
# v20 (2026-09-16, round 7): wired as a PDF download + text
# extraction instead of a feed (there genuinely is no HTML sumario
# either — jdownloads is PDF-only). Discovery: /ceuta/documentos/
# secciones/bocces links one category per YEAR, the year category
# links one sub-category per MONTH, the month category lists items
# (BOCCE_NNNN_DD-MM-YYYY); the real PDF is served through .../
# jdownloads/finish/{month_slug}/{item_slug} (verified live: HTTP
# 200 application/pdf, 5.3 MB for BOCCE nº 6.652 of 15/09/2026).
# Extraction uses the ``pdftotext`` CLI (poppler, already installed
# on this host at /opt/homebrew/bin/pdftotext 26.07.0 — NOT a new
# Python dependency; the feed reports UNREACHABLE with an explicit
# reason if it is absent); ``pdftotext -layout`` on that PDF gives a
# clean SUMARIO page numbering each disposition ("630.OASTCE.
# Acuerdo del Pleno de la Asamblea de la Ciudad Autónoma de Ceuta...
# Pág.3411") — 8 real, dated, numbered entries extracted from that
# one issue.
"rss_url": None,
"feeds": [{
"kind": FEED_KIND_PDF_ISSUE,
"label": "BOCCE — PDF diario + extracción de texto (pdftotext)",
"url": "https://www.ceuta.es/ceuta/documentos/secciones/bocces",
}],
"rss_note": "no feed of any kind exists (not even HTML) — the daily PDF is downloaded "
"and its SUMARIO page is text-extracted with pdftotext (poppler CLI); "
"UNREACHABLE with an explicit reason if pdftotext is not installed",
"web_url": "https://www.ceuta.es/ceuta/bocce",
"search_url": None,
"rss_last_check": {"date": "2026-09-16", "result": "ceuta.es/ceuta/ has a working "
"site-wide RSS/Atom (?format=feed&type=rss|atom, HTTP 200) but its "
"content is general municipal news, not BOCCE; the BOCCE page "
"itself only lists PDF downloads (jdownloads component), no feed "
"link; round 5: Joomla per-page feed (bocce?format=feed&type=rss|"
"atom) redirects to the site-wide news feed, jdownloads feed view "
"times out, datos.gob.es lists no BOCCE dataset — NO "
"machine-readable feed of the bulletin exists today; round 7: PDF "
"download + pdftotext wired instead (no feed of any kind exists, "
"confirmed again) — /ceuta/documentos/secciones/bocces HTTP 200, "
"year category 1965-2026, month category 1980-septiembre, item "
"23263-bocce-6652-15-09-2026; finish/.../23263-... HTTP 200 "
"application/pdf 5.3 MB; pdftotext -layout -> 8 dated SUMARIO "
"entries with page numbers"},
},
"melilla": {
"name": "BOME — Boletín Oficial de la Ciudad de Melilla",
# v18 (2026-09-16, round 4): melilla.es/melilla/bome is 404 (moved
# off that host); the bulletin now lives at the dedicated
# bomemelilla.es, whose homepage links "SUBSCRIPCIÓN" and whose
# /rss answers HTTP 200 text/xml RSS 2.0 with 1,932 dated entries
# spanning 2014-01-03 to 2026-09-15 (yesterday at verification time)
# — one entry per issue ("BOME NÚMERO 6414"), issue-level like DOG.
"rss_url": "https://bomemelilla.es/rss",
"rss_note": "issue-level feed: entries are 'BOME NÚMERO NNNN', no per-disposition "
"titles — manual search recommended for full coverage",
"web_url": "https://www.melilla.es/melilla/bome",
"search_url": None,
"rss_last_check": {"date": "2026-09-16", "result": "HTTP 200 text/xml RSS 2.0, 1,932 "
"dated entries, 2014-01-03 through 2026-09-15; melilla.es/melilla/"
"bome (the old web_url) is 404 — the bulletin moved to the "
"dedicated bomemelilla.es host"},
},
}
# ═══════════════════════════════════════════════════════════
# RSS PARSER
# ═══════════════════════════════════════════════════════════
class _SafeRow(dict):
"""``str.format_map`` helper: a missing key renders as "" instead of raising.
v18: a present key whose value is ``None`` also renders as "" (the BORM
service sends ``"subApartado": null``, which ``str.format`` printed as
``None``).
"""
def __missing__(self, key):
return ""
def __getitem__(self, key):
value = super().__getitem__(key)
return "" if value is None else value
def _tidy_description(text: str) -> str:
"""Drop empty ``·``-separated segments left by blank template fields (pure)."""
parts = [p.strip() for p in (text or "").split(" · ")]
return " · ".join(p for p in parts if p)
def _dotted_get(row: Dict, path: str):
"""Resolve ``a.b.c`` inside nested dicts; ``None`` when any step is missing."""
value = row
for part in (path or "").split("."):
if not isinstance(value, dict):
return None
value = value.get(part)
return value
def feeds_for_source(source: Dict) -> List[Dict]:
"""Return the machine-readable feeds declared for a CCAA source (v17).
``feeds`` wins when present; otherwise a single RSS feed is derived from
``rss_url``; an empty list means the bulletin is not scanned automatically.
"""
feeds = source.get("feeds")
if feeds:
return [dict(f) for f in feeds if isinstance(f, dict)]
if source.get("rss_url"):
return [{"kind": FEED_KIND_RSS, "url": source["rss_url"],
"label": source.get("name", "").split("—")[0].strip()}]
return []
def parse_feed_date(value: str) -> Optional[datetime]:
"""Parse an RSS/Atom date (RFC 2822 or ISO-8601) into an aware UTC datetime."""
text = (value or "").strip()
if not text:
return None
try:
parsed = parsedate_to_datetime(text)
except (TypeError, ValueError, IndexError):
parsed = None
if parsed is None:
try:
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
class RSSParser:
"""Parse RSS feeds from CCAA bulletins."""
@staticmethod
def filter_entries(entries: List[Dict], keywords: List[str],
max_age_days: int, now: Optional[datetime] = None) -> List[Dict]:
"""Keyword-filter parsed feed entries and drop those older than the window.
Pure function (no network) so the age filter is unit-testable. Entries
whose date cannot be parsed are KEPT and flagged ``date_unparsed`` rather
than silently dropped or silently included as current.
"""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
kept = []
for entry in entries:
# v18: an entry may restrict what is scanned (``scan_text``): the
# DOGC summary, BOA and BORM feeds scan the disposition TITLE only,
# because their descriptions carry the issuing department name
# ("Departament de Territori, Habitatge...", "DEPARTAMENTO DE
# VIVIENDA...") which would tag every item of that department as
# housing law — the same trap the BOE scanner avoids since v16.0.1.
scan_text = entry.get("scan_text")
if scan_text is None:
scan_text = f"{entry.get('title', '')} {entry.get('description', '')}"
matched = keyword_matches(scan_text, keywords)
if not matched:
continue
published = parse_feed_date(entry.get("date", ""))
if published is not None and published < cutoff:
continue
kept.append({
"title": (entry.get("title") or "").strip(),
"url": (entry.get("url") or "").strip(),
"date": (entry.get("date") or "").strip(),
"description": (entry.get("description") or "")[:300],
"keywords_matched": matched,
"date_unparsed": published is None,
})
return kept
@staticmethod
def parse_feed(content: bytes) -> List[Dict]:
"""Extract raw entries (title/url/date/description) from RSS 2.0 or Atom XML."""
root = ET.fromstring(content)
entries = []
atom = "{http://www.w3.org/2005/Atom}"
items = list(root.iter("item")) or list(root.iter(f"{atom}entry"))
for item in items:
title_elem = item.find("title") if item.find("title") is not None else item.find(f"{atom}title")
if title_elem is None:
continue
link_elem = item.find("link")
link = ""
if link_elem is not None:
link = link_elem.text or ""
else:
atom_link = item.find(f"{atom}link")
if atom_link is not None:
link = atom_link.get("href", "") or ""
desc_elem = item.find("description")
if desc_elem is None:
desc_elem = item.find(f"{atom}summary")
date_elem = item.find("pubDate")
if date_elem is None:
date_elem = item.find(f"{atom}updated")
entries.append({
"title": title_elem.text or "",
"url": link,
"date": (date_elem.text if date_elem is not None else "") or "",
"description": (desc_elem.text if desc_elem is not None else "") or "",
})
return entries
@staticmethod
def fetch_feed(rss_url: str, keywords: List[str],
max_age_days: int = 30) -> Dict:
"""Fetch one feed and return a status record (v16.0.1).
``{"status": OK|EMPTY|UNREACHABLE|NOT_CONFIGURED, "entries_fetched": n,
"entries": [matched...], "error": str}``. ``EMPTY`` means the feed was
fetched and parsed but nothing matched the keywords inside the window;
``UNREACHABLE`` means we could not look (HTTP error, network, bad XML).
The two must never collapse into the same "0 entries" line.
"""
if not rss_url:
return {"status": SOURCE_NOT_CONFIGURED, "entries_fetched": 0, "entries": [], "error": ""}
try:
response = requests.get(rss_url, timeout=15, headers=HTTP_HEADERS)
except Exception as e:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"{type(e).__name__}: {e}"}
if response.status_code != 200:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"HTTP {response.status_code} from {rss_url}"}
try:
entries = RSSParser.parse_feed(response.content)
except ET.ParseError as e:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"feed is not parseable XML ({e}) from {rss_url}"}
matched = RSSParser.filter_entries(entries, keywords, max_age_days)
return {"status": SOURCE_OK if matched else SOURCE_EMPTY,
"entries_fetched": len(entries), "entries": matched, "error": ""}
@staticmethod
def rows_to_entries(rows: List[Dict], feed: Dict) -> List[Dict]:
"""Map JSON rows (Socrata or any JSON list service) to raw feed entries.
Pure function (v17 as ``socrata_rows_to_entries``, generalised in v18).
``feed`` declares ``title_fields`` (joined with a space), ``date_field``,
``url_field`` (dotted path into nested dicts, e.g. ``format_html.url``)
and ``description_template`` (``str.format`` with the row; missing keys
become ""). v18 additions:
- ``date_format``: ``strptime`` pattern of the source date (e.g.
``%Y%m%d`` for the BOA, ``%d-%m-%Y`` for the BORM); the entry date is
rendered ISO so :func:`parse_feed_date` accepts it. An unparseable
value is kept verbatim (it then surfaces as ``date_unparsed``).
- ``url_template``: ``str.format`` over the row, used when the row has
no ready URL field (the BOA exposes ``DOCN``, not a link).
- ``url_regex``: first match inside the ``url_field`` value (the BOA
wraps several URLs in backticks in one string).
- ``exclude_values``: ``{field: [values]}`` — rows whose field equals one
of the values are dropped (BORM "Autoridades y Personal").
- ``scan_fields``: row fields whose text is keyword-scanned (joined);
when absent the scanner uses title + description as before (the
Socrata feed relies on the Spanish title inside the description).
Rows without a title are skipped.
"""
entries: List[Dict] = []
title_fields = feed.get("title_fields") or ["title"]
template = feed.get("description_template") or ""
date_field = feed.get("date_field") or "date"
date_format = feed.get("date_format") or ""
url_template = feed.get("url_template") or ""
url_regex = feed.get("url_regex") or ""
exclude = feed.get("exclude_values") or {}
scan_fields = feed.get("scan_fields") or []
for row in rows or []:
if not isinstance(row, dict):
continue
if any(str(row.get(f, "")).strip() in [str(v) for v in vals]
for f, vals in exclude.items()):
continue
title = " ".join(str(row.get(f) or "") for f in title_fields).strip()
if not title:
continue
description = _tidy_description(template.format_map(_SafeRow(row))) if template else ""
raw_date = str(row.get(date_field) or "").strip()
entry_date = raw_date
if raw_date and date_format:
try:
entry_date = datetime.strptime(raw_date, date_format).strftime("%Y-%m-%dT00:00:00+00:00")
except ValueError:
entry_date = raw_date
if url_template:
url = url_template.format_map(_SafeRow(row))
else:
url = str(_dotted_get(row, feed.get("url_field") or "url") or "")
if url and url_regex:
match = re.search(url_regex, url)
url = match.group(0) if match else ""
entry = {
"title": title,
"url": url,
"date": entry_date,
"description": description,
}
if scan_fields:
entry["scan_text"] = " ".join(str(row.get(f) or "") for f in scan_fields)
entries.append(entry)
return entries
@staticmethod
def socrata_rows_to_entries(rows: List[Dict], feed: Dict) -> List[Dict]:
"""v17 name of :meth:`rows_to_entries` (kept for callers and tests)."""
return RSSParser.rows_to_entries(rows, feed)
@staticmethod
def render_feed_params(values: Dict, now: datetime, cutoff: datetime,
day: Optional[datetime] = None) -> Dict:
"""Expand ``{since:%Y%m%d}`` / ``{today:...}`` / ``{date:...}`` placeholders (pure).
``since`` is the window cutoff, ``today`` the run date and ``date`` the
day being scanned by a per-day feed. Non-string values pass through.
"""
def expand(text: str) -> str:
def sub(match):
name, fmt = match.group(1), match.group(2) or "%Y-%m-%d"
stamp = {"since": cutoff, "today": now, "date": day or now}.get(name)
return stamp.strftime(fmt) if stamp else match.group(0)
return re.sub(r"\{(since|today|date)(?::([^}]+))?\}", sub, text)
return {k: (expand(v) if isinstance(v, str) else v) for k, v in (values or {}).items()}
@staticmethod
def _load_json_rows(response, feed: Dict) -> Tuple[Optional[List], str]:
"""Decode a JSON-rows response; returns ``(rows, error)`` (pure over the response)."""
text = response.text
if feed.get("lenient_json"):
text = repair_json_escapes(text)
try:
payload = json.loads(text, strict=not feed.get("lenient_json"))
except ValueError as e:
return None, f"resource is not JSON ({e})"
rows_path = feed.get("rows_path") or ""
rows = _dotted_get(payload, rows_path) if rows_path and isinstance(payload, dict) else payload
if not isinstance(rows, list):
return None, f"unexpected JSON shape ({type(rows).__name__}) at {rows_path or 'root'}"
return rows, ""
@staticmethod
def fetch_json_rows(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None) -> Dict:
"""Fetch a generic JSON list service (v18) and return a status record.
Two shapes:
- one request: ``url`` (+ ``params``) with ``{since:...}`` placeholders,
the service filters by date itself (BOA);
- ``per_day: true``: ``url`` carries a ``{date:...}`` placeholder and is
fetched once per day of the window (BORM); ``no_issue_status`` codes
(default 404) mean "no issue that day", any other failure is a failed
day. Some days read and some failed -> ``PARTIAL`` (entries kept).
``rows_path`` selects the list inside a dict payload; ``lenient_json``
repairs invalid escapes and parses in non-strict mode.
"""
url = feed.get("url") or ""
if not url:
return {"status": SOURCE_NOT_CONFIGURED, "entries_fetched": 0, "entries": [], "error": ""}
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
headers = dict(HTTP_HEADERS)
headers["Accept"] = "application/json"
headers.update(feed.get("headers") or {})
timeout = int(feed.get("timeout") or 60)
no_issue = set(int(c) for c in (feed.get("no_issue_status") or [404]))
def fetch_once(target_url: str, params: Dict) -> Tuple[Optional[List], str, Optional[int]]:
try:
response = requests.get(target_url, params=params or None, timeout=timeout, headers=headers)
except Exception as e:
return None, f"{type(e).__name__}: {e}", None
if response.status_code != 200:
return None, f"HTTP {response.status_code} from {response.url}", response.status_code
if feed.get("encoding"):
response.encoding = feed["encoding"]
rows, error = RSSParser._load_json_rows(response, feed)
return rows, (f"{error} from {response.url}" if error else ""), 200
rows_all: List[Dict] = []
failed: List[str] = []
scanned = 0
if feed.get("per_day"):
for i in range(max_age_days):
day = now - timedelta(days=i)
day_url = RSSParser.render_feed_params({"u": url}, now, cutoff, day)["u"]
params = RSSParser.render_feed_params(feed.get("params") or {}, now, cutoff, day)
rows, error, code = fetch_once(day_url, params)
if rows is None and code in no_issue:
continue
if rows is None:
failed.append(f"{day.strftime('%d/%m/%Y')}: {error}")
continue
scanned += 1
rows_all.extend(r for r in rows if isinstance(r, dict))
if scanned == 0 and failed:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"{len(failed)}/{max_age_days} days failed: " + "; ".join(failed[:5])}
else:
params = RSSParser.render_feed_params(feed.get("params") or {}, now, cutoff)
rows, error, _ = fetch_once(RSSParser.render_feed_params({"u": url}, now, cutoff)["u"], params)
if rows is None:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [], "error": error}
scanned = 1
rows_all = [r for r in rows if isinstance(r, dict)]
entries = RSSParser.rows_to_entries(rows_all, feed)
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} day(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_days": failed}
@staticmethod
def fetch_socrata(feed: Dict, keywords: List[str], max_age_days: int = 30) -> Dict:
"""Fetch a Socrata open-data resource and return the same status record as
:meth:`fetch_feed` (v17).
The window is applied server-side (``$where date_field >= cutoff``) and
again client-side by :meth:`filter_entries`. Non-200, non-JSON or a
non-list body is ``UNREACHABLE`` — never silently ``EMPTY``.
"""
url = feed.get("url") or ""
if not url:
return {"status": SOURCE_NOT_CONFIGURED, "entries_fetched": 0, "entries": [], "error": ""}
date_field = feed.get("date_field") or "date"
cutoff = (datetime.now(timezone.utc) - timedelta(days=max_age_days)).strftime("%Y-%m-%dT00:00:00")
params = {"$where": f"{date_field} >= '{cutoff}'",
"$order": f"{date_field} DESC",
"$limit": str(feed.get("limit") or 1000)}
headers = dict(HTTP_HEADERS)
headers["Accept"] = "application/json"
try:
response = requests.get(url, params=params, timeout=20, headers=headers)
except Exception as e:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"{type(e).__name__}: {e}"}
if response.status_code != 200:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"HTTP {response.status_code} from {url}"}
try:
rows = response.json()
except ValueError as e:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"resource is not JSON ({e}) from {url}"}
if not isinstance(rows, list):
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"unexpected JSON shape ({type(rows).__name__}) from {url}"}
entries = RSSParser.socrata_rows_to_entries(rows, feed)
matched = RSSParser.filter_entries(entries, keywords, max_age_days)
return {"status": SOURCE_OK if matched else SOURCE_EMPTY,
"entries_fetched": len(entries), "entries": matched, "error": ""}
@staticmethod
def fetch_dogc_summary(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["DOGCSummaryClient"] = None) -> Dict:
"""Scan every DOGC issue of the window through the summary API (v18).
1. ``calendarDOGC`` for each month the window touches -> issue numbers
and dates; 2. ``summaryDOGC`` per issue (newest first, capped at
:data:`DOGC_MAX_ISSUES_PER_RUN`); 3. every document of every section
except those in ``feed["sections_exclude"]`` becomes an entry.
Calendar unreachable / no issue read -> ``UNREACHABLE``; some issues
failed -> ``PARTIAL`` (entries kept); else ``OK`` / ``EMPTY``.
"""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
client = client or DOGCSummaryClient(language=feed.get("language") or "ca")
excluded = set(feed.get("sections_exclude") or [])
months: List[Tuple[int, int]] = []
cursor = date(cutoff.year, cutoff.month, 1)
while (cursor.year, cursor.month) <= (now.year, now.month):
months.append((cursor.year, cursor.month))
cursor = date(cursor.year + (cursor.month == 12), (cursor.month % 12) + 1, 1)
issues: List[Tuple[str, str]] = []
calendar_errors: List[str] = []
for year, month in months:
result = client.calendar(year, month)
if result["status"] != "ok":
calendar_errors.append(f"{month:02d}/{year}: {result.get('message', '')}")
continue
issues.extend(client.calendar_issue_numbers(result["payload"]))
if not issues and calendar_errors:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": "calendarDOGC failed: " + "; ".join(calendar_errors)}
cutoff_iso, now_iso = cutoff.strftime("%Y-%m-%d"), now.strftime("%Y-%m-%d")
wanted = sorted({(d, n) for d, n in issues if cutoff_iso <= d <= now_iso}, reverse=True)
wanted = wanted[:DOGC_MAX_ISSUES_PER_RUN]
entries: List[Dict] = []
failed: List[str] = list(calendar_errors)
scanned = 0
for issue_date, number in wanted:
result = client.issue(number)
if result["status"] != "ok":
failed.append(f"DOGC {number} ({issue_date}): {result.get('message', '')}")
continue
scanned += 1
entries.extend(client.flatten_issue(result["payload"], excluded))
if scanned == 0:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": ("no DOGC issue in window" if not wanted else
f"0/{len(wanted)} issues read: " + "; ".join(failed[:5])),
"issues_scanned": 0, "failed_issues": failed}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} issue(s)/month(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_issues": failed}
@staticmethod
def fetch_bocm_xml(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["BOCMIssueClient"] = None) -> Dict:
"""Scan every BOCM issue of the window through its native per-issue XML (v19).
1. ``sumarios.rss`` (``feed["url"]``) -> the issues (date, number) it
lists — the RSS is the calendar; 2. one GET per issue XML (newest
first, capped at :data:`BOCM_MAX_ISSUES_PER_RUN`); 3. every unique
``<disposicion>`` outside ``feed["sections_exclude"]`` /
``feed["apartados_exclude"]`` becomes an entry scanned by TITLE.
RSS unreachable / no issue read -> ``UNREACHABLE``; some issues failed
-> ``PARTIAL`` (entries kept); else ``OK`` / ``EMPTY``. The RSS only
lists the 20 newest issues (~24 calendar days): ``issues_listed`` and
``oldest_issue`` in the record say how far back the scan really went.
"""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
client = client or BOCMIssueClient()
listing = client.list_issues(feed.get("url") or "")
if listing["status"] != "ok":
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"BOCM sumarios.rss: {listing.get('message', '')}"}
cutoff_iso, now_iso = cutoff.strftime("%Y-%m-%d"), now.strftime("%Y-%m-%d")
wanted = sorted({(d, n) for d, n in listing["issues"] if cutoff_iso <= d <= now_iso}, reverse=True)
wanted = wanted[:BOCM_MAX_ISSUES_PER_RUN]
entries: List[Dict] = []
failed: List[str] = []
scanned = 0
excluded_sections = set(feed.get("sections_exclude") or [])
excluded_apartados = set(feed.get("apartados_exclude") or [])
for issue_date, number in wanted:
result = client.issue(issue_date, number)
if result["status"] != "ok":
failed.append(f"BOCM {number} ({issue_date}): {result.get('message', '')}")
continue
scanned += 1
entries.extend(client.flatten_issue(result["root"], issue_date, number,
excluded_sections, excluded_apartados))
if scanned == 0:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": ("no BOCM issue in window" if not wanted else
f"0/{len(wanted)} issues read: " + "; ".join(failed[:5])),
"issues_scanned": 0, "issues_listed": len(listing["issues"]), "failed_issues": failed}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} issue(s) NOT read: " + "; ".join(failed[:5])
oldest = min((d for d, _ in listing["issues"]), default="")
if oldest and oldest > cutoff_iso:
note = f"RSS lists issues from {oldest} only (window asked from {cutoff_iso})"
error = f"{error}; {note}" if error else note
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "issues_listed": len(listing["issues"]),
"oldest_issue": oldest, "failed_issues": failed}
@staticmethod
def fetch_docm_sumario(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["DOCMClient"] = None) -> Dict:
"""Scan the DOCM's per-day HTML sumario, one GET per calendar day (v20)."""
now = now or datetime.now(timezone.utc)
client = client or DOCMClient()
excluded = set(feed.get("sections_exclude") or [])
entries: List[Dict] = []
failed: List[str] = []
scanned = 0
for i in range(max_age_days):
day = (now - timedelta(days=i)).date()
result = client.issue(day)
if result["status"] == "no_issue":
continue
if result["status"] != "ok":
failed.append(f"{day.isoformat()}: {result.get('message', '')}")
continue
scanned += 1
entries.extend(DOCMClient.flatten_issue(result["html"], day.isoformat(), excluded))
if scanned == 0 and failed:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"{len(failed)}/{max_age_days} days failed: " + "; ".join(failed[:5])}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} day(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_days": failed}
@staticmethod
def fetch_canarias_boc(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["CanariasBOCClient"] = None) -> Dict:
"""Scan every BOC (Canarias) issue of the window via the date->issue calendar (v20)."""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
client = client or CanariasBOCClient()
excluded = set(feed.get("sections_exclude") or [])
calendar = client.calendar()
if calendar["status"] != "ok":
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"boc_index.js: {calendar.get('message', '')}"}
cutoff_iso, now_iso = cutoff.strftime("%Y-%m-%d"), now.strftime("%Y-%m-%d")
wanted = sorted({(d, n) for d, numbers in calendar["by_date"].items()
if cutoff_iso <= d <= now_iso for n in numbers}, reverse=True)
wanted = wanted[:CANARIAS_MAX_ISSUES_PER_RUN]
entries: List[Dict] = []
failed: List[str] = []
scanned = 0
for date_iso, number in wanted:
year = date_iso[:4]
result = client.issue(year, number)
if result["status"] != "ok":
failed.append(f"BOC {number}/{year} ({date_iso}): {result.get('message', '')}")
continue
scanned += 1
entries.extend(CanariasBOCClient.flatten_issue(result["html"], date_iso, number, excluded))
if scanned == 0:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": ("no BOC issue in window" if not wanted else
f"0/{len(wanted)} issues read: " + "; ".join(failed[:5])),
"issues_scanned": 0, "failed_issues": failed}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} issue(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_issues": failed}
@staticmethod
def fetch_bon_sumario(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["BONClient"] = None) -> Dict:
"""Scan BON (Navarra) issues of the window, walking backwards by issue number (v20)."""
now = now or datetime.now(timezone.utc)
cutoff = now - timedelta(days=max_age_days)
cutoff_iso = cutoff.strftime("%Y-%m-%d")
client = client or BONClient()
excluded = set(feed.get("sections_exclude") or [])
latest = client.latest()
if latest["status"] != "ok":
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"BON latest issue: {latest.get('message', '')}"}
try:
latest_num = int(latest["number"])
except ValueError:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"BON latest issue number is not numeric: {latest['number']!r}"}
year = latest["date"][:4]
entries: List[Dict] = []
failed: List[str] = []
scanned = 0
hit_number_one = False
for offset in range(BON_MAX_ISSUES_PER_RUN):
number = latest_num - offset
if number < 1:
hit_number_one = True
break
if number == latest_num:
result = {"status": "ok", "html": latest["html"], "date": latest["date"]}
else:
result = client.issue(year, str(number))
if result["status"] != "ok":
failed.append(f"BON {number}/{year}: {result.get('message', '')}")
continue
if result["date"] < cutoff_iso:
break
scanned += 1
entries.extend(BONClient.flatten_issue(result["html"], result["date"], excluded))
if scanned == 0:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"0 issues read: " + "; ".join(failed[:5]),
"issues_scanned": 0, "failed_issues": failed}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} issue(s) NOT read: " + "; ".join(failed[:5])
if hit_number_one:
note = ("BON issue numbers reset at the calendar year — the window may extend "
"before issue 1 of the current year and was not scanned that far back")
error = f"{error}; {note}" if error else note
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_issues": failed}
@staticmethod
def fetch_bopa_sumario(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["BOPAClient"] = None) -> Dict:
"""Scan the BOPA's per-day HTML sumario, one GET per calendar day (v20)."""
now = now or datetime.now(timezone.utc)
client = client or BOPAClient()
excluded = set(feed.get("sections_exclude") or [])
entries: List[Dict] = []
failed: List[str] = []
scanned = 0
for i in range(max_age_days):
day = (now - timedelta(days=i)).date()
result = client.issue(day)
if result["status"] == "no_issue":
continue
if result["status"] != "ok":
failed.append(f"{day.isoformat()}: {result.get('message', '')}")
continue
scanned += 1
entries.extend(BOPAClient.flatten_issue(result["html"], day.isoformat(), excluded))
if scanned == 0 and failed:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"{len(failed)}/{max_age_days} days failed: " + "; ".join(failed[:5])}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} day(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_days": failed}
@staticmethod
def fetch_pdf_issue(feed: Dict, keywords: List[str], max_age_days: int = 30,
now: Optional[datetime] = None,
client: Optional["BOCCEClient"] = None) -> Dict:
"""Download+extract every BOCCE PDF of the window via ``pdftotext`` (v20).
Gated on the ``pdftotext`` CLI being installed (poppler) — no Python
PDF library is a project dependency, and this feed reports
``UNREACHABLE`` with an explicit reason rather than adding one.
"""
now = now or datetime.now(timezone.utc)
client = client or BOCCEClient()
if client.__class__ is BOCCEClient and shutil.which("pdftotext") is None:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": "pdftotext (poppler) is not installed on this host — "
"the daily BOCCE PDF cannot be text-extracted"}
listing = client.list_recent_issues(now, max_age_days)
if listing["status"] != "ok":
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": f"BOCCE discovery: {listing.get('message', '')}"}
entries: List[Dict] = []
failed: List[str] = list(listing.get("failed") or [])
scanned = 0
for date_iso, title, pdf_url in listing["items"]:
result = client.download_and_extract(pdf_url)
if result["status"] != "ok":
failed.append(f"{title}: {result.get('message', '')}")
continue
issue_entries = BOCCEClient.flatten_issue(result["text"], date_iso, title, pdf_url)
if not issue_entries:
failed.append(f"{title}: PDF downloaded but no SUMARIO entries were found in its text")
continue
scanned += 1
entries.extend(issue_entries)
if scanned == 0:
return {"status": SOURCE_UNREACHABLE, "entries_fetched": 0, "entries": [],
"error": ("no BOCCE issue in window" if not listing["items"] else
f"0/{len(listing['items'])} issues read: " + "; ".join(failed[:5])),
"issues_scanned": 0, "failed_issues": failed}
matched = RSSParser.filter_entries(entries, keywords, max_age_days, now)
status = SOURCE_OK if matched else SOURCE_EMPTY
error = ""
if failed:
status = SOURCE_PARTIAL
error = f"{len(failed)} issue(s) NOT read: " + "; ".join(failed[:5])
return {"status": status, "entries_fetched": len(entries), "entries": matched,
"error": error, "issues_scanned": scanned, "failed_issues": failed}
@staticmethod
def fetch_source_feed(feed: Dict, keywords: List[str], max_age_days: int = 30) -> Dict:
"""Dispatch one declared feed to the fetcher for its ``kind`` (v17/v18/v19/v20)."""
kind = str(feed.get("kind") or FEED_KIND_RSS).lower()
if kind == FEED_KIND_SOCRATA:
return RSSParser.fetch_socrata(feed, keywords, max_age_days)
if kind == FEED_KIND_JSON_ROWS:
return RSSParser.fetch_json_rows(feed, keywords, max_age_days)
if kind == FEED_KIND_DOGC_SUMMARY:
return RSSParser.fetch_dogc_summary(feed, keywords, max_age_days)
if kind == FEED_KIND_BOCM_XML:
return RSSParser.fetch_bocm_xml(feed, keywords, max_age_days)
if kind == FEED_KIND_DOCM_SUMARIO:
return RSSParser.fetch_docm_sumario(feed, keywords, max_age_days)
if kind == FEED_KIND_CANARIAS_BOC:
return RSSParser.fetch_canarias_boc(feed, keywords, max_age_days)
if kind == FEED_KIND_BON_SUMARIO:
return RSSParser.fetch_bon_sumario(feed, keywords, max_age_days)
if kind == FEED_KIND_BOPA_SUMARIO:
return RSSParser.fetch_bopa_sumario(feed, keywords, max_age_days)
if kind == FEED_KIND_PDF_ISSUE:
return RSSParser.fetch_pdf_issue(feed, keywords, max_age_days)
return RSSParser.fetch_feed(feed.get("url") or "", keywords, max_age_days)
class BOCMIssueClient:
"""Client for the BOCM's native per-issue XML (v19).
Live-verified 2026-09-16 (probe_log_2026-09-16_r6.txt):
- ``https://www.bocm.es/sumarios.rss`` lists the 20 newest issues; each
``<item>`` links ``https://www.bocm.es/boletin-completo/BOCM-YYYYMMDD/NNN``
(issue date + number) — that link is the only calendar the BOCM exposes.
- ``https://www.bocm.es/boletin/CM_Boletin_BOCM/YYYY/MM/DD/BOCM-YYYYMMDDNNN.xml``
(path = issue date) answers ``<sumario><metadatos>...</metadatos><diario>
<secciones><seccion nombre="I. COMUNIDAD DE MADRID"><apartado nombre="C)
Otras Disposiciones"><organismo nombre="CONSEJERÍA ..."><disposicion>
<identificador>BOCM-20260916-61</identificador><titulo>...</titulo>
<url_html>...</url_html><url_pdf>...</url_pdf>``. Sections seen: I.
COMUNIDAD DE MADRID (apartados A/B/C/D), III. ADMINISTRACIÓN LOCAL
AYUNTAMIENTOS (no apartado; titles like "– Madrid. Urbanismo. ... Plan
especial"), IV. ADMINISTRACIÓN DE JUSTICIA, V. OTROS ANUNCIOS. The same
``<disposicion>`` is repeated many times in the tree (3 570 nodes for 84
distinct identifiers on 16/09/2026): entries are de-duplicated by
``identificador``. A date with no issue answers HTTP 404 (Sundays).
"""
RSS_URL = "https://www.bocm.es/sumarios.rss"
XML_URL = "https://www.bocm.es/boletin/CM_Boletin_BOCM/{y}/{m}/{d}/BOCM-{y}{m}{d}{n}.xml"
LINK_RE = re.compile(r"/boletin-completo/BOCM-(\d{4})(\d{2})(\d{2})/(\d+)")
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 60):
self.session = session or requests.Session()
self.timeout = timeout
def _get(self, url: str):
headers = dict(HTTP_HEADERS)
try:
response = self.session.get(url, headers=headers, timeout=self.timeout)
except Exception as e:
return None, f"{type(e).__name__}: {e}"
if response.status_code != 200:
return None, f"HTTP {response.status_code}"
return response.content, ""
@classmethod
def issues_from_rss(cls, content: bytes) -> List[Tuple[str, str]]:
"""``(YYYY-MM-DD, number)`` for every issue linked from sumarios.rss (pure)."""
issues: List[Tuple[str, str]] = []
for entry in RSSParser.parse_feed(content):
match = cls.LINK_RE.search(entry.get("url") or "")
if match:
y, m, d, n = match.groups()
issues.append((f"{y}-{m}-{d}", n))
return issues
def list_issues(self, rss_url: str = "") -> Dict:
content, error = self._get(rss_url or self.RSS_URL)
if content is None:
return {"status": "error", "message": error}
try:
issues = self.issues_from_rss(content)
except ET.ParseError as e:
return {"status": "error", "message": f"RSS not parseable ({e})"}
if not issues:
return {"status": "error", "message": "RSS has no boletin-completo links (layout changed?)"}
return {"status": "ok", "issues": issues}
@classmethod
def issue_url(cls, issue_date: str, number: str) -> str:
y, m, d = issue_date.split("-")
return cls.XML_URL.format(y=y, m=m, d=d, n=number)
def issue(self, issue_date: str, number: str) -> Dict:
url = self.issue_url(issue_date, number)
content, error = self._get(url)
if content is None:
return {"status": "error", "message": f"{error} from {url}"}
try:
root = ET.fromstring(content)
except ET.ParseError as e:
return {"status": "error", "message": f"XML not parseable ({e}) from {url}"}
if root.tag != "sumario":
return {"status": "error", "message": f"unexpected root <{root.tag}> from {url}"}
return {"status": "ok", "root": root, "url": url}
@staticmethod
def flatten_issue(root, issue_date: str, number: str,
sections_exclude=None, apartados_exclude=None) -> List[Dict]:
"""One raw entry per DISTINCT disposicion of the issue, scanned by title (pure)."""
excluded_sections = set(sections_exclude or [])
excluded_apartados = set(apartados_exclude or [])
entries: List[Dict] = []
seen = set()
entry_date = f"{issue_date}T00:00:00+00:00"
for section in root.iter("seccion"):
sec_name = (section.get("nombre") or "").strip()
if sec_name in excluded_sections:
continue
for apartado in section.iter("apartado"):
ap_name = (apartado.get("nombre") or "").strip()
if ap_name in excluded_apartados:
continue
for organismo in apartado.iter("organismo"):
org_name = (organismo.get("nombre") or "").strip()
for disp in organismo.iter("disposicion"):
ident = (disp.findtext("identificador") or "").strip()
title = re.sub(r"\s+", " ", disp.findtext("titulo") or "").strip()
if not title:
continue
key = ident or title
if key in seen:
continue
seen.add(key)
url = (disp.findtext("url_html") or disp.findtext("url_pdf") or "").strip()
entries.append({
"title": title,
"url": url,
"date": entry_date,
"description": " · ".join(x for x in (f"BOCM núm. {number}", sec_name, ap_name, org_name) if x),
"section": sec_name,
"scan_text": title, # the organismo name is not scanned (v18 rule)
})
return entries
class DOGCSummaryClient:
"""Client for the DOGC summary API behind dogc.gencat.cat's "Sumari" page (v18).
Reverse-read from the page's own JavaScript (``fpca_sumari_DOGC.js`` posts
``numDOGC`` + ``language`` as a form to ``uriSumari``; ``constants.js``
names the production host ``portaldogc.gencat.cat``). Verified live
2026-09-16: ``summaryDOGC`` -> ``{"sumaris": [{"numDOGC", "dateDOGC"
(dd/mm/yyyy), "previousNumDOGC", "laterNumDOGC", "section": [{"title",
"header": [{"title", "document": [{"title", "linkDownloadDocumentPDF"}],
"subheader": [...same shape...]}]}]}]}``; ``calendarDOGC`` (``month``,
``year``, ``language``) -> ``{"calendar": [{"date", "hasDOGC",
"linkDOGC": "?...&numDOGC=9752&..."}]}``. ``language`` accepts ``ca`` and
``es``. Errors come back as HTTP 500 JSON ``{"errorCode", "errorDescription"}``.
"""
API_HOST = "https://portaldogc.gencat.cat"
SUMMARY_URL = API_HOST + "/eadop-rest/api/dogc/summaryDOGC"
CALENDAR_URL = API_HOST + "/eadop-rest/api/dogc/calendarDOGC"
DOCUMENT_URL = "https://dogc.gencat.cat/{lang}/document-del-dogc/?documentId={doc_id}"
def __init__(self, language: str = "ca", session: Optional[requests.Session] = None,
timeout: int = 45):
self.language = language if language in ("ca", "es") else "ca"
self.session = session or legacy_tls_session(self.API_HOST)
self.timeout = timeout
def _post(self, url: str, data: Dict) -> Dict:
headers = dict(HTTP_HEADERS)
headers["Accept"] = "application/json"
try:
response = self.session.post(url, data=data, headers=headers, timeout=self.timeout)
except Exception as e:
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
try:
payload = response.json()
except ValueError:
return {"status": "error", "message": f"HTTP {response.status_code} non-JSON body"}
if response.status_code != 200 or not isinstance(payload, dict):
desc = payload.get("errorDescription") if isinstance(payload, dict) else ""
return {"status": "error", "message": f"HTTP {response.status_code} {desc or ''}".strip()}
return {"status": "ok", "payload": payload}
def calendar(self, year: int, month: int) -> Dict:
return self._post(self.CALENDAR_URL, {"month": str(month), "year": str(year), "language": self.language})
def issue(self, number: str) -> Dict:
return self._post(self.SUMMARY_URL, {"numDOGC": str(number), "language": self.language})
@staticmethod
def calendar_issue_numbers(payload: Dict) -> List[Tuple[str, str]]:
"""``(YYYY-MM-DD, numDOGC)`` for every day of the calendar that has an issue (pure)."""
issues: List[Tuple[str, str]] = []
for day in (payload or {}).get("calendar") or []:
if not isinstance(day, dict) or not day.get("hasDOGC"):
continue
match = re.search(r"numDOGC=(\d+)", str(day.get("linkDOGC") or ""))
parsed = DOGCSummaryClient._iso_date(str(day.get("date") or ""))
if match and parsed:
issues.append((parsed, match.group(1)))
return issues
@staticmethod
def _iso_date(dd_mm_yyyy: str) -> str:
try:
return datetime.strptime(dd_mm_yyyy.strip(), "%d/%m/%Y").strftime("%Y-%m-%d")
except ValueError:
return ""
@staticmethod
def flatten_issue(payload: Dict, sections_exclude=None, language: str = "ca") -> List[Dict]:
"""One raw entry per document of the issue, with its section path (pure).
``url`` is the document page on dogc.gencat.cat (``documentId`` taken
from the PDF link); the PDF link itself is kept in the description.
"""
excluded = set(sections_exclude or [])
entries: List[Dict] = []
for issue in (payload or {}).get("sumaris") or []:
if not isinstance(issue, dict):
continue
number = str(issue.get("numDOGC") or "")
iso = DOGCSummaryClient._iso_date(str(issue.get("dateDOGC") or ""))
entry_date = f"{iso}T00:00:00+00:00" if iso else ""
for section in issue.get("section") or []:
if not isinstance(section, dict):
continue
sec_title = str(section.get("title") or "").strip()
if sec_title in excluded:
continue
def walk(node: Dict, path: List[str]):
title = str(node.get("title") or "").strip()
here = path + ([title] if title else [])
for doc in node.get("document") or []:
if not isinstance(doc, dict) or not str(doc.get("title") or "").strip():
continue
pdf = str(doc.get("linkDownloadDocumentPDF") or "")
doc_id = re.search(r"documentId=(\d+)", pdf)
url = (DOGCSummaryClient.DOCUMENT_URL.format(lang=language, doc_id=doc_id.group(1))
if doc_id else pdf)
entries.append({
"title": str(doc["title"]).strip(),
"url": url,
"date": entry_date,
"description": " · ".join([f"DOGC núm. {number}", sec_title] + here)
+ (f" · PDF: {pdf}" if pdf else ""),
"section": sec_title,
# scan the title only: the header path is the issuing
# department (e.g. "...Territori, Habitatge...")
"scan_text": str(doc["title"]).strip(),
})
for sub in node.get("subheader") or []:
if isinstance(sub, dict):
walk(sub, here)
for header in section.get("header") or []:
if isinstance(header, dict):
walk(header, [])
return entries
@staticmethod
def fetch_and_filter(rss_url: str, keywords: List[str],
max_age_days: int = 30) -> List[Dict]:
"""Compatibility wrapper over :meth:`fetch_feed`.
Returns the matched entries; a failure returns ``[{"error": ...}]`` so
older callers can still disclose it. New code should use ``fetch_feed``
because this shape cannot tell EMPTY from UNREACHABLE-with-no-error.
"""
result = RSSParser.fetch_feed(rss_url, keywords, max_age_days)
if result["status"] == SOURCE_UNREACHABLE:
return [{"error": result["error"]}]
return result["entries"]
class DOCMClient:
"""Client for the DOCM (Castilla-La Mancha) per-day HTML sumario (v20).
docm.jccm.es has no RSS/Atom (rounds 4-5 confirmed dead; see
``CCAA_SOURCES["castilla_mancha"]["rss_last_check"]``). Its own "Sumario"
page IS a classic server-rendered HTML listing, and the calendar widget on
that page links each day to ``/docm/cambiarBoletin.do?fecha=YYYYMMDD``
(no session/cookie needed — verified live 2026-09-16 with a fresh
``requests.get`` per date). A day with an issue answers HTTP 200 with a
``<td class="fechaDiario">`` header and one ``<div class="disp_...">`` per
disposition; a day without one (weekends/holidays — verified with Sunday
13/09/2026) answers HTTP 200 with NO ``fechaDiario`` text at all — that is
the "no issue" signal, not a different status code. Categories are
``<h3 class="cabeceraCategoria">`` (e.g. "II.- AUTORIDADES Y PERSONAL");
each disposition is ``<div class="disp_ID"><p class="sumario"><a
href="...pdf">START OF TITLE</a>REST OF TITLE</p>`` — anchor text + the
text that follows is the real, full disposition title (verified: "Régimen
Local. Resolución de 08/09/2026, de la Viceconsejería..."). "II.-
AUTORIDADES Y PERSONAL" is excluded as noise by default (oposiciones,
nombramientos — same criterion as BOCM/BORM's staff-section exclusion).
"""
BASE = "https://docm.jccm.es"
ISSUE_URL = BASE + "/docm/cambiarBoletin.do?fecha={ymd}"
ENTRY_RE = re.compile(
r'<div\s+class\s*=\s*"disp_[^"]*">\s*<p\s+class\s*=\s*"sumario">\s*'
r'<a\s+href="([^"]+)"[^>]*>(.*?)</a>(.*?)</p>', re.S)
CATEGORY_SPLIT_RE = re.compile(r'(<h3\s+class\s*=\s*"cabeceraCategoria">.*?</h3>)', re.S)
CATEGORY_TEXT_RE = re.compile(r'cabeceraCategoria">\s*([^<]+?)\s*</h3>')
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 30):
self.session = session or requests.Session()
self.timeout = timeout
def issue(self, day: date) -> Dict:
url = self.ISSUE_URL.format(ymd=day.strftime("%Y%m%d"))
try:
response = self.session.get(url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
if response.status_code != 200:
return {"status": "error", "message": f"HTTP {response.status_code} from {url}"}
if "fechaDiario" not in response.text:
return {"status": "no_issue"}
return {"status": "ok", "html": response.text}
@classmethod
def flatten_issue(cls, html: str, day_iso: str, categories_exclude=None) -> List[Dict]:
"""One raw entry per disposition of the day, tagged with its category (pure)."""
excluded = set(categories_exclude or [])
entries: List[Dict] = []
current_category = ""
for chunk in cls.CATEGORY_SPLIT_RE.split(html):
cat_match = cls.CATEGORY_TEXT_RE.search(chunk)
if cat_match:
current_category = re.sub(r"\s+", " ", cat_match.group(1)).strip()
continue
if current_category in excluded:
continue
for href, anchor_text, rest in cls.ENTRY_RE.findall(chunk):
title = re.sub(r"<[^>]+>", "", anchor_text + rest)
title = html_unescape(re.sub(r"\s+", " ", title)).strip()
if not title:
continue
url = html_unescape(href)
if not url.startswith("http"):
url = cls.BASE + "/docm/" + url.lstrip("./")
entries.append({
"title": title, "url": url, "date": f"{day_iso}T00:00:00+00:00",
"description": f"DOCM · {current_category}", "section": current_category,
})
return entries
class CanariasBOCClient:
"""Client for the BOC (Canarias) per-issue HTML sumario (v20).
The site's own ``/boc/rss/`` scheme is dead (round 4/5 — every ``./
capitulo|cabildo|ayuntamiento/*.rss`` link is 404, a handful of root
feeds that DO answer 200 are frozen at "BOC 2012/201"). But the "Sede
electrónica" search widget (``www.gobiernodecanarias.org/boc/menu.html``,
``boc.js``/``boc_index.js``) is driven by a plain calendar lookup: every
``A(YYYYMMDDNNN)`` call in ``boc_index.js`` maps one calendar date to that
day's issue number (verified live 2026-09-16: newest entry
``A(20260916186)`` = issue 186 published today). The issue itself is a
static page, ``/boc/{year}/{number:03d}/index.html``, with real,
per-disposition titles: ``<h4>I. Disposiciones generales</h4> ...
<li class="justificado_boc"><a...><b>3261</b></a>
<a href="...pdf">ORDEN de 4 de septiembre de 2026, por la que...</a>``.
The server declares no charset and ``requests`` defaults to ISO-8859-1 for
a bare ``text/html``, garbling accents — the response encoding is forced
to UTF-8 (the actual byte content), same fix as the BOA in v18.
"II. Autoridades y personal" is excluded as noise (staff appointments/
oposiciones — same criterion as the other three new HTML sources).
"""
ISSUE_HOST = "https://www.gobiernodecanarias.org"
INDEX_JS_URL = ISSUE_HOST + "/boc/boc_index.js"
ISSUE_URL = ISSUE_HOST + "/boc/{year}/{number:03d}/index.html"
CALENDAR_RE = re.compile(r"A\((\d{4})(\d{2})(\d{2})(\d{3})\)")
SECTION_SPLIT_RE = re.compile(r"(<h4>.*?</h4>)", re.S)
SECTION_TEXT_RE = re.compile(r"<h4>\s*([^<]+?)\s*</h4>")
ENTRY_RE = re.compile(
r'<li class="justificado_boc">\s*<a[^>]*><b>(\d+)</b></a>\s*<a href="([^"]+)">(.*?)</a>', re.S)
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 30):
self.session = session or requests.Session()
self.timeout = timeout
def _get(self, url: str):
try:
response = self.session.get(url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return None, f"{type(e).__name__}: {e}"
if response.status_code != 200:
return None, f"HTTP {response.status_code} from {url}"
response.encoding = "utf-8"
return response.text, ""
def calendar(self) -> Dict:
"""``{date_iso: [issue_number, ...]}`` for every entry in boc_index.js."""
text, error = self._get(self.INDEX_JS_URL)
if text is None:
return {"status": "error", "message": error}
by_date: Dict[str, List[str]] = {}
for y, m, d, n in self.CALENDAR_RE.findall(text):
by_date.setdefault(f"{y}-{m}-{d}", []).append(n)
if not by_date:
return {"status": "error", "message": "boc_index.js has no A(...) entries (layout changed?)"}
return {"status": "ok", "by_date": by_date}
def issue(self, year: str, number: str) -> Dict:
url = self.ISSUE_URL.format(year=int(year), number=int(number))
text, error = self._get(url)
if text is None:
return {"status": "error", "message": error}
return {"status": "ok", "html": text}
@classmethod
def flatten_issue(cls, html: str, date_iso: str, number: str, sections_exclude=None) -> List[Dict]:
"""One raw entry per disposition of the issue (pure)."""
excluded = set(sections_exclude or [])
entries: List[Dict] = []
current_section = ""
for chunk in cls.SECTION_SPLIT_RE.split(html):
sec_match = cls.SECTION_TEXT_RE.match(chunk)
if sec_match:
current_section = re.sub(r"\s+", " ", sec_match.group(1)).strip()
continue
if current_section in excluded:
continue
for doc_num, href, raw_title in cls.ENTRY_RE.findall(chunk):
title = html_unescape(re.sub(r"\s+", " ", raw_title)).strip()
if not title:
continue
entries.append({
"title": title, "url": href, "date": f"{date_iso}T00:00:00+00:00",
"description": f"BOC núm. {number} · {current_section} · doc. {doc_num}",
"section": current_section,
})
return entries
class BONClient:
"""Client for the BON (Navarra) per-issue HTML sumario (v20).
bon.navarra.es is a Liferay portal with no RSS/Atom (round 4/5 confirmed
dead). Its own "Sumario" page IS a real, per-disposition listing:
``/es/boletin`` (no params) renders the latest issue, and
``/es/boletin/-/sumario/{year}/{number}`` renders any past issue by
number — both carry a self-describing header, ``<p id="numero_boletin">
BOLETÍN Nº 184 - 16 de septiembre de 2026</p>``, used to read the TRUE
date of whatever issue was returned rather than trusting the requested
number (defensive, same principle as BOPA's own-date check below).
Sections: ``<p class="hd r-hn3 b-ambito">1. Comunidad Foral de
Navarra</p>`` etc.; each disposition is ``<a href=".../anuncio/-/texto/
YYYY/NUM/SEQ" title="FULL TITLE">``. Issue numbers run sequentially within
a calendar year (~1 per business day: number 184 on 16/09/2026), so the
window is walked backwards by NUMBER from the latest issue rather than by
calendar day.
"""
BASE = "https://bon.navarra.es"
LATEST_URL = BASE + "/es/boletin"
ISSUE_URL = BASE + "/es/boletin/-/sumario/{year}/{number}"
NUMERO_RE = re.compile(
r'numero_boletin"[^>]*>\s*BOLET[IÍ]N\s*N[ºo]\s*(\d+)\s*-\s*'
r'(\d{1,2})\s*de\s*(\w+)\s*de\s*(\d{4})', re.I)
AMBITO_SPLIT_RE = re.compile(r'(<p class="hd r-hn3 b-ambito">.*?</p>)', re.S)
AMBITO_TEXT_RE = re.compile(r'b-ambito">\s*([^<]+?)\s*</p>')
ENTRY_RE = re.compile(r'<a href="(https://bon\.navarra\.es/es/anuncio/-/texto/[^"]+)" title="([^"]*)">', re.S)
MONTHS = {"enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6,
"julio": 7, "agosto": 8, "septiembre": 9, "octubre": 10, "noviembre": 11,
"diciembre": 12}
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 30):
self.session = session or requests.Session()
self.timeout = timeout
def _get(self, url: str):
try:
response = self.session.get(url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return None, f"{type(e).__name__}: {e}"
if response.status_code != 200:
return None, f"HTTP {response.status_code} from {url}"
return response.text, ""
@classmethod
def parse_numero(cls, html: str) -> Optional[Tuple[str, str]]:
"""``(number, YYYY-MM-DD)`` read from the page's own header (pure)."""
match = cls.NUMERO_RE.search(html)
if not match:
return None
number, day, month_name, year = match.groups()
month = cls.MONTHS.get(month_name.lower())
if not month:
return None
return number, f"{int(year):04d}-{month:02d}-{int(day):02d}"
def latest(self) -> Dict:
html, error = self._get(self.LATEST_URL)
if html is None:
return {"status": "error", "message": error}
parsed = self.parse_numero(html)
if not parsed:
return {"status": "error", "message": "no numero_boletin header found (layout changed?)"}
number, date_iso = parsed
return {"status": "ok", "number": number, "date": date_iso, "html": html}
def issue(self, year: str, number: str) -> Dict:
html, error = self._get(self.ISSUE_URL.format(year=year, number=number))
if html is None:
return {"status": "error", "message": error}
parsed = self.parse_numero(html)
if not parsed:
return {"status": "error", "message": "no numero_boletin header found (layout changed?)"}
true_number, date_iso = parsed
return {"status": "ok", "html": html, "date": date_iso, "number": true_number}
@classmethod
def flatten_issue(cls, html: str, date_iso: str, sections_exclude=None) -> List[Dict]:
"""One raw entry per disposition of the issue, tagged with its ambito (pure)."""
excluded = set(sections_exclude or [])
entries: List[Dict] = []
current = ""
for chunk in cls.AMBITO_SPLIT_RE.split(html):
match = cls.AMBITO_TEXT_RE.search(chunk)
if match:
current = re.sub(r"\s+", " ", match.group(1)).strip()
continue
if current in excluded:
continue
for href, raw_title in cls.ENTRY_RE.findall(chunk):
title = re.sub(r"<br\s*/?>", " ", raw_title)
title = html_unescape(re.sub(r"\s+", " ", title)).strip()
if not title:
continue
entries.append({
"title": title, "url": href, "date": f"{date_iso}T00:00:00+00:00",
"description": f"BON · {current}", "section": current,
})
return entries
class BOPAClient:
"""Client for the BOPA (Asturias) per-day HTML sumario (v20).
Round 4/5 confirmed no RSS/Atom on either ``sede.asturias.es/bopa`` or the
Liferay portal it redirects to (``miprincipado.asturias.es/bopa``), and
the official open-data dataset is a yearly archive, not a monitoring feed.
But the portal's own "Consultar por fecha" widget calls
``/bopa-sumario?p_p_id=pa_sede_bopa_web_portlet_SedeBopaSummaryWeb&
p_r_p_summaryDate=DD%2FMM%2FYYYY&p_r_p_summaryIsSearch=false`` directly —
no session/cookie needed — and returns real, per-disposition titles:
``<h4>I. Principado de Asturias</h4><h5>AUTORIDADES Y PERSONAL</h5>
<h6>...</h6><dl><dt>Decreto 62/2026, de 14 de septiembre...
<strong>[Cód. 2026-07611]</strong></dt><dd><a href=".../2026-07611.pdf">
PDF de la disposición</a></dd></dl>``. A date with NO issue (verified
Sunday 13/09/2026) does not answer empty or 404 — it silently FALLS BACK
to the nearest available bulletin, so every fetch reads the page's own
``<h1>Boletín Nº NNN del DIA de MES de YYYY</h1>`` and only keeps the
result when that date matches what was requested (otherwise: no issue that
day, same effect as BORM's 404). "AUTORIDADES Y PERSONAL" subsections are
excluded as noise (nombramientos, ceses — same criterion as the other
three new HTML sources).
"""
BASE = "https://miprincipado.asturias.es"
ISSUE_URL = (BASE + "/bopa-sumario?p_p_id=pa_sede_bopa_web_portlet_SedeBopaSummaryWeb"
"&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view"
"&p_r_p_summaryDate={dd}%2F{mm}%2F{yyyy}&p_r_p_summaryIsSearch=false")
H1_RE = re.compile(
r'<h1[^>]*>\s*Bolet[ií]n\s*N[ºo]\s*\d+\s*del\s*\w+\s*(\d{1,2})\s*de\s*(\w+)\s*de\s*(\d{4})',
re.I | re.S)
BLOCK_SPLIT_RE = re.compile(r'(<h4[^>]*>.*?</h4>|<h5>.*?</h5>)', re.S)
H4_RE = re.compile(r'^<h4[^>]*>\s*([^<]*?)\s*</h4>', re.I)
H5_RE = re.compile(r'^<h5>\s*([^<]*?)\s*</h5>', re.I)
DL_RE = re.compile(r'<dl>\s*<dt>\s*(.*?)\s*</dt>\s*<dd>\s*(.*?)\s*</dd>\s*</dl>', re.S)
PDF_RE = re.compile(r'href="(/bopa/[^"]+\.pdf)"')
MONTHS = BONClient.MONTHS
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 30):
self.session = session or requests.Session()
self.timeout = timeout
def issue(self, day: date) -> Dict:
url = self.ISSUE_URL.format(dd=f"{day.day:02d}", mm=f"{day.month:02d}", yyyy=day.year)
try:
response = self.session.get(url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
if response.status_code != 200:
return {"status": "error", "message": f"HTTP {response.status_code} from {url}"}
true_date = self.parse_h1_date(response.text)
if true_date is None:
return {"status": "no_issue"}
if true_date != day.strftime("%Y-%m-%d"):
# the portal silently served the nearest available bulletin instead
# of the requested day — that day genuinely has no issue.
return {"status": "no_issue"}
return {"status": "ok", "html": response.text}
@classmethod
def parse_h1_date(cls, html: str) -> Optional[str]:
match = cls.H1_RE.search(html)
if not match:
return None
day, month_name, year = match.groups()
month = cls.MONTHS.get(month_name.lower())
if not month:
return None
return f"{int(year):04d}-{month:02d}-{int(day):02d}"
@classmethod
def flatten_issue(cls, html: str, day_iso: str, sections_exclude=None) -> List[Dict]:
"""One raw entry per disposition of the day (pure).
``sections_exclude`` matches the ``<h5>`` SUBSECTION text (e.g.
"AUTORIDADES Y PERSONAL"), not the ``<h4>`` top-level section — BOPA
nests staff appointments one level deeper than DOCM/Canarias/BON.
"""
excluded = set(sections_exclude or [])
start = html.find('id="bopa-boletin"')
block = html[start:] if start >= 0 else html
entries: List[Dict] = []
cur_h4, cur_h5 = "", ""
for chunk in cls.BLOCK_SPLIT_RE.split(block):
m4 = cls.H4_RE.match(chunk)
if m4:
cur_h4, cur_h5 = re.sub(r"\s+", " ", m4.group(1)).strip(), ""
continue
m5 = cls.H5_RE.match(chunk)
if m5:
cur_h5 = re.sub(r"\s+", " ", m5.group(1)).strip()
continue
if cur_h5 in excluded:
continue
for raw_title, dd in cls.DL_RE.findall(chunk):
title = html_unescape(re.sub(r"<[^>]+>", "", raw_title)).replace("\xa0", " ")
title = re.sub(r"\s+", " ", title).strip()
if not title:
continue
pdf = cls.PDF_RE.search(dd)
entries.append({
"title": title,
"url": (cls.BASE + pdf.group(1)) if pdf else "",
"date": f"{day_iso}T00:00:00+00:00",
"description": " · ".join(x for x in ("BOPA", cur_h4, cur_h5) if x),
"section": cur_h4,
})
return entries
class BOCCEClient:
"""Client for the BOCCE (Ceuta) daily PDF, downloaded and text-extracted (v20).
Round 4/5 confirmed BOCCE has NO feed of any kind — not RSS/Atom (the
site's own feed is the generic municipal news feed, unrelated), not even
a plain HTML sumario page: every issue is published ONLY as a PDF behind a
jdownloads component (``BOCCE_NNNN_DD-MM-YYYY``). This client downloads
that PDF and extracts its text with the ``pdftotext`` CLI (poppler; no
Python PDF library is a project dependency, and none is added here —
``shutil.which("pdftotext")`` gates the whole feed, live-verified present
at ``/opt/homebrew/bin/pdftotext`` 26.07.0). Discovery: the section page
(``/ceuta/documentos/secciones/bocces``) links one category per YEAR
(``viewcategory/{id}-{year}``); the year category links one sub-category
per MONTH (``viewcategory/{id}-{month_name_es}``); the month category
lists items (``viewdownload/{month_slug}/{id}-bocce-...-DD-MM-YYYY``)
whose real PDF is fetched through ``finish/{month_slug}/{item_slug}``
(HTTP 200 ``application/pdf`` — verified live, 5.3 MB for one issue).
The extracted text's own SUMARIO page numbers each disposition
(``630.OASTCE.Acuerdo...Pág.3411``); those are the entries returned —
at minimum a real, numbered, dated disposition title per issue.
"""
BASE = "https://www.ceuta.es"
SECTIONS_URL = BASE + "/ceuta/documentos/secciones/bocces"
CATEGORY_URL = BASE + "/ceuta/component/jdownloads/viewcategory/{slug}?Itemid=534"
FINISH_URL = BASE + "/ceuta/component/jdownloads/finish/{month_slug}/{item_slug}?Itemid=0"
YEAR_RE = re.compile(r"viewcategory/(\d+-(\d{4}))\?Itemid")
MONTH_RE = re.compile(r"viewcategory/(\d+-(\w+))\?Itemid")
ITEM_RE = re.compile(r'viewdownload/([\w-]+)/(\d+-[\w-]+)(?:\?[^"]*)?"[^>]*>\s*([^<]+?)\s*<')
ITEM_DATE_RE = re.compile(r"(\d{2})-(\d{2})-(\d{4})\s*$")
SUMARIO_ENTRY_RE = re.compile(r"(\d{2,5})\.[\-‐-―]\s*(.+?)\s*P[aá]g\.(\d+)", re.S)
MONTH_NAMES = {v: k for k, v in BONClient.MONTHS.items()} # 9 -> "septiembre"
def __init__(self, session: Optional[requests.Session] = None, timeout: int = 45):
self.session = session or requests.Session()
self.timeout = timeout
def _get_text(self, url: str):
try:
response = self.session.get(url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return None, f"{type(e).__name__}: {e}"
if response.status_code != 200:
return None, f"HTTP {response.status_code} from {url}"
return response.text, ""
def list_recent_issues(self, now: datetime, max_age_days: int) -> Dict:
"""``[(date_iso, title, finish_url), ...]`` for BOCCE PDFs inside the window."""
cutoff_date = (now - timedelta(days=max_age_days)).date()
months_needed = set()
d = now.date()
while d >= cutoff_date:
months_needed.add((d.year, d.month))
d -= timedelta(days=1)
html, error = self._get_text(self.SECTIONS_URL)
if html is None:
return {"status": "error", "message": f"{self.SECTIONS_URL}: {error}"}
year_slugs = {int(y): slug for slug, y in self.YEAR_RE.findall(html)}
items = []
failed = []
for year, month in sorted(months_needed):
year_slug = year_slugs.get(year)
if not year_slug:
failed.append(f"no category for year {year}")
continue
year_html, error = self._get_text(self.CATEGORY_URL.format(slug=year_slug))
if year_html is None:
failed.append(f"{year_slug}: {error}")
continue
month_name = self.MONTH_NAMES.get(month, "")
month_slugs = {name.lower(): slug for slug, name in self.MONTH_RE.findall(year_html)}
month_slug = month_slugs.get(month_name)
if not month_slug:
continue # no issues published that month yet (e.g. current month, day 1)
month_html, error = self._get_text(self.CATEGORY_URL.format(slug=month_slug))
if month_html is None:
failed.append(f"{month_slug}: {error}")
continue
for href_month_slug, item_slug, title in self.ITEM_RE.findall(month_html):
title = html_unescape(title).strip()
if not title.upper().startswith("BOCCE"):
continue
date_match = self.ITEM_DATE_RE.search(title)
if not date_match:
continue
dd, mm, yyyy = date_match.groups()
date_iso = f"{yyyy}-{mm}-{dd}"
if not (cutoff_date.isoformat() <= date_iso <= now.date().isoformat()):
continue
finish_url = self.FINISH_URL.format(month_slug=href_month_slug, item_slug=item_slug)
items.append((date_iso, title, finish_url))
items = sorted(set(items), reverse=True)[:BOCCE_MAX_ISSUES_PER_RUN]
return {"status": "ok", "items": items, "failed": failed}
def download_and_extract(self, pdf_url: str) -> Dict:
"""Download one PDF and return its text via ``pdftotext -layout`` (impure)."""
try:
response = self.session.get(pdf_url, headers=HTTP_HEADERS, timeout=self.timeout)
except Exception as e:
return {"status": "error", "message": f"{type(e).__name__}: {e}"}
if response.status_code != 200:
return {"status": "error", "message": f"HTTP {response.status_code} from {pdf_url}"}
if not response.content[:4] == b"%PDF":
return {"status": "error", "message": f"response from {pdf_url} is not a PDF"}
with tempfile.NamedTemporaryFile(suffix=".pdf") as tmp:
tmp.write(response.content)
tmp.flush()
try:
proc = subprocess.run(["pdftotext", "-layout", tmp.name, "-"],
capture_output=True, timeout=60)
except Exception as e:
return {"status": "error", "message": f"pdftotext failed: {type(e).__name__}: {e}"}
if proc.returncode != 0:
return {"status": "error", "message": f"pdftotext exit {proc.returncode}: "
f"{proc.stderr.decode('utf-8', 'replace')[:200]}"}
return {"status": "ok", "text": proc.stdout.decode("utf-8", "replace")}
@classmethod
def flatten_issue(cls, text: str, date_iso: str, title: str, pdf_url: str) -> List[Dict]:
"""Numbered disposition entries from the PDF's own SUMARIO page (pure)."""
start = text.find("SUMARIO")
if start < 0:
return []
end_match = re.search(r"BOCCE\s*[nN][ºo]", text[start + 7:])
block = text[start:start + 7 + end_match.start()] if end_match else text[start:]
entries: List[Dict] = []
for number, raw_title, page in cls.SUMARIO_ENTRY_RE.findall(block):
entry_title = re.sub(r"\s+", " ", raw_title.replace("\xad", "")).strip()
if not entry_title:
continue
entries.append({
"title": entry_title, "url": pdf_url, "date": f"{date_iso}T00:00:00+00:00",
"description": f"{title.strip()} · pág. {page}",
})
return entries
# ═══════════════════════════════════════════════════════════
# LEGAL CHANGE CLASSIFIER
# ═══════════════════════════════════════════════════════════
class LegalClassifier:
"""Classify legal changes by impact and category."""
@staticmethod
def classify(title: str, description: str,
keywords_matched: List[str]) -> Dict:
"""
Classify a legal change.
Returns: category, impact_level, affects_visado
"""
text = f"{title} {description}"
def has(*kws):
# v16: whole-word, case-insensitive matching. v15 lowercased the
# text but compared against upper-case tokens ("CTE", "PGOU", "VPO",
# "ITE", "RITE", "RSCIEI", "DB-SI", "nZEB"), so those categories
# never matched; and substring matching let "ITE" hit "límite".
return bool(keyword_matches(text, list(kws)))
# Category detection (RITE checked before ITE: distinct regulations)
category = "general"
if has("CTE", "código técnico", "documento básico"):
category = "CTE"
elif has("urbanismo", "urbanística", "plan general", "PGOU", "POUM", "suelo"):
category = "urbanismo"
elif has("vivienda", "VPO", "alquiler"):
category = "vivienda"
elif has("eficiencia energética", "certificación", "emisiones", "nZEB"):
category = "eficiencia_energetica"
elif has("RITE", "instalaciones térmicas"):
category = "instalaciones"
elif has("ITE", "inspección técnica"):
category = "inspeccion"
elif has("accesibilidad", "barreras"):
category = "accesibilidad"
elif has("incendio", "RSCIEI", "DB-SI"):
category = "seguridad_incendios"
# Impact level
impact = "BAJO"
if keyword_matches(text, HIGH_IMPACT_KEYWORDS):
impact = "ALTO"
elif len(keywords_matched) >= 2:
impact = "MEDIO"
# Visado impact
affects_visado = bool(keyword_matches(text, VISADO_KEYWORDS))
return {
"category": category,
"impact_level": impact,
"affects_visado": affects_visado,
}
# ═══════════════════════════════════════════════════════════
# DIGEST GENERATOR
# ═══════════════════════════════════════════════════════════
class DigestGenerator:
"""Generate monthly digest of legal changes."""
@staticmethod
def generate(changes: List[LegalChange],
period: str = "monthly",
language: str = "ca",
source_status: Optional[List[Dict]] = None) -> str:
"""
Generate a formatted digest.
language: "ca" (català), "es" (español), "en" (English)
source_status (v16.0.1): rows from ``LegalMonitor.source_status_records``;
any source that is not OK/EMPTY is listed in a "not scanned" block so the
text digest cannot present an unreachable bulletin as "no changes".
"""
now = datetime.now()
# Headers by language. v16 adds "en" (v15 silently fell back to Spanish
# for --lang en) and localises the summary block and per-item labels
# that v15 printed in Catalan regardless of language.
headers = {
"ca": {
"title": "BUTLLETÍ DE NOVETATS LEGISLATIVES — CONSTRUCCIÓ I URBANISME",
"period_label": "Període",
"high": "IMPACTE ALT",
"medium": "IMPACTE MITJÀ",
"low": "IMPACTE BAIX",
"visado_warning": "⚠ Afecta requisits de visat",
"no_changes": "No s'han detectat canvis legislatius rellevants en aquest període.",
"footer": "Generat automàticament per RailNexus Value",
"sources": "Fonts",
"category": "Categoria",
"keywords": "Paraules clau",
"date_unparsed": "(data no interpretable a la font)",
"summary": "RESUM: {n} canvis detectats",
"counts": "🔴 Alt: {h} | 🟡 Mitjà: {m} | 🟢 Baix: {l}",
"visado_count": "⚠ {n} canvis afecten requisits de visat",
"not_scanned": "⚠ FONTS NO ESCANEJADES O INCOMPLETES ({n}) — aquest butlletí NO cobreix:",
"scanned_ok": "Fonts escanejades: {ok}/{total}",
"st_UNREACHABLE": "NO ACCESSIBLE", "st_NOT_CONFIGURED": "SENSE FEED",
"st_PARTIAL": "PARCIAL", "st_EMPTY": "SENSE NOVETATS", "st_OK": "OK",
},
"es": {
"title": "BOLETÍN DE NOVEDADES LEGISLATIVAS — CONSTRUCCIÓN Y URBANISMO",
"period_label": "Período",
"high": "IMPACTO ALTO",
"medium": "IMPACTO MEDIO",
"low": "IMPACTO BAJO",
"visado_warning": "⚠ Afecta requisitos de visado",
"no_changes": "No se han detectado cambios legislativos relevantes en este período.",
"footer": "Generado automáticamente por RailNexus Value",
"sources": "Fuentes",
"category": "Categoría",
"keywords": "Palabras clave",
"date_unparsed": "(fecha no interpretable en la fuente)",
"summary": "RESUMEN: {n} cambios detectados",
"counts": "🔴 Alto: {h} | 🟡 Medio: {m} | 🟢 Bajo: {l}",
"visado_count": "⚠ {n} cambios afectan a requisitos de visado",
"not_scanned": "⚠ FUENTES NO ESCANEADAS O INCOMPLETAS ({n}) — este boletín NO cubre:",
"scanned_ok": "Fuentes escaneadas: {ok}/{total}",
"st_UNREACHABLE": "NO ACCESIBLE", "st_NOT_CONFIGURED": "SIN FEED",
"st_PARTIAL": "PARCIAL", "st_EMPTY": "SIN NOVEDADES", "st_OK": "OK",
},
"en": {
"title": "LEGISLATIVE UPDATE BULLETIN — CONSTRUCTION AND URBAN PLANNING",
"period_label": "Period",
"high": "HIGH IMPACT",
"medium": "MEDIUM IMPACT",
"low": "LOW IMPACT",
"visado_warning": "⚠ Affects visado (college stamp) requirements",
"no_changes": "No relevant legislative changes were detected in this period.",
"footer": "Generated automatically by RailNexus Value",
"sources": "Sources",
"category": "Category",
"keywords": "Keywords",
"date_unparsed": "(source date could not be parsed)",
"summary": "SUMMARY: {n} changes detected",
"counts": "🔴 High: {h} | 🟡 Medium: {m} | 🟢 Low: {l}",
"visado_count": "⚠ {n} changes affect visado requirements",
"not_scanned": "⚠ SOURCES NOT SCANNED OR INCOMPLETE ({n}) — this bulletin does NOT cover:",
"scanned_ok": "Sources scanned: {ok}/{total}",
"st_UNREACHABLE": "UNREACHABLE", "st_NOT_CONFIGURED": "NO FEED",
"st_PARTIAL": "PARTIAL", "st_EMPTY": "NO CHANGES", "st_OK": "OK",
},
}
h = headers.get(language, headers["es"])
lines = []
lines.append("=" * 70)
lines.append(f" {h['title']}")
lines.append("=" * 70)
lines.append(f" {h['period_label']}: {now.strftime('%B %Y')}")
lines.append(f" {h['footer']} v{AGENT_VERSION}")
lines.append("=" * 70)
# v16.0.1: source coverage block — printed BEFORE the changes so that an
# empty digest cannot read as "nothing happened" when a feed was down.
if source_status:
problems = [s for s in source_status
if s.get("status") not in (SOURCE_OK, SOURCE_EMPTY)]
ok_count = len(source_status) - len(problems)
lines.append(f" {h['scanned_ok'].format(ok=ok_count, total=len(source_status))}")
if problems:
lines.append(f"\n {h['not_scanned'].format(n=len(problems))}")
for s in problems:
label = h.get(f"st_{s.get('status', '')}", s.get("status", ""))
detail = f" — {s['detail']}" if s.get("detail") else ""
lines.append(f" • {s.get('source') or s.get('ccaa')} ({s.get('ccaa')}): {label}{detail}")
if not changes:
lines.append(f"\n {h['no_changes']}")
return "\n".join(lines)
# Group by impact level
high = [c for c in changes if c.impact_level == "ALTO"]
medium = [c for c in changes if c.impact_level == "MEDIO"]
low = [c for c in changes if c.impact_level == "BAJO"]
for group, label, icon in [
(high, h["high"], "🔴"),
(medium, h["medium"], "🟡"),
(low, h["low"], "🟢"),
]:
if group:
lines.append(f"\n{'─' * 70}")
lines.append(f" {icon} {label} ({len(group)})")
lines.append(f"{'─' * 70}")
for change in group:
visado_flag = f" {h['visado_warning']}" if change.affects_visado else ""
unparsed = f" {h['date_unparsed']}" if change.date_unparsed else ""
lines.append(f"\n [{change.source}] {change.date}{unparsed}")
lines.append(f" {change.title}")
lines.append(f" {h['category']}: {change.category}{visado_flag}")
if change.keywords_matched:
lines.append(f" {h['keywords']}: {', '.join(change.keywords_matched[:5])}")
if change.summary:
lines.append(f" {change.summary}")
if change.url:
lines.append(f" 🔗 {change.url}")
# Statistics
lines.append(f"\n{'═' * 70}")
lines.append(" " + h["summary"].format(n=len(changes)))
lines.append(" " + h["counts"].format(h=len(high), m=len(medium), l=len(low)))
visado_count = sum(1 for c in changes if c.affects_visado)
if visado_count:
lines.append(" " + h["visado_count"].format(n=visado_count))
# Sources
sources_used = set(c.source for c in changes)
lines.append(f"\n {h['sources']}: {', '.join(sorted(sources_used))}")
lines.append(f"\n{'═' * 70}")
return "\n".join(lines)
# ═══════════════════════════════════════════════════════════
# MAIN MONITOR ORCHESTRATOR
# ═══════════════════════════════════════════════════════════
class LegalMonitor:
"""
Main orchestrator: runs the full monitoring pipeline.
Pipeline:
1. Query BOE API for national changes
2. Query CCAA RSS feeds for regional changes
3. Classify all changes
4. Generate digest
5. (Future) Send via email to subscribers
"""
def __init__(self, target_ccaa: List[str] = None,
boe_sections: Optional[List[str]] = None):
"""
Initialize monitor.
target_ccaa: List of CCAA to monitor.
None = monitor all.
Example: ["cataluña", "valencia"]
boe_sections (v16.0.1): BOE section codes to scan; ``None`` = the
default legislation sections; ``["all"]`` = every section.
"""
self.target_ccaa = target_ccaa if target_ccaa is not None else list(CCAA_SOURCES.keys())
if boe_sections is None:
self.boe_sections: Optional[List[str]] = list(BOE_DEFAULT_SECTIONS)
elif any(str(s).lower() == "all" for s in boe_sections):
self.boe_sections = None
else:
self.boe_sections = [str(s).upper() for s in boe_sections]
self.changes: List[LegalChange] = []
self.source_errors: List[Dict] = []
# v16.0.1: per-source outcome, always populated by run()
self.ccaa_status: List[Dict] = []
self.boe_scan: Dict = {}
@staticmethod
def boe_changes_from_records(records: List[Dict], date_label: str) -> List[LegalChange]:
"""Keyword-scan flattened sumario records (pure; used by scan_boe and tests).
Only the disposition title and its epígrafe are scanned — never the
page template, never the departamento name (a "Ministerio de Vivienda"
header would otherwise tag every item of that ministry as housing law).
"""
changes: List[LegalChange] = []
for rec in records:
scan_text = f"{rec.get('titulo', '')} {rec.get('epigrafe', '')}"
matched = keyword_matches(scan_text, CONSTRUCTION_KEYWORDS)
if not matched:
continue
classification = LegalClassifier.classify(
rec.get("titulo", ""), rec.get("epigrafe", ""), matched)
context = " · ".join(part for part in (
rec.get("seccion_nombre", ""), rec.get("departamento", ""),
rec.get("epigrafe", "")) if part)
changes.append(LegalChange(
source="BOE",
date=date_label,
title=rec.get("titulo") or rec.get("identificador") or "Sin título",
category=classification["category"],
impact_level=classification["impact_level"],
summary=context,
url=rec.get("url_html") or rec.get("url_pdf") or "",
affects_visado=classification["affects_visado"],
ccaa="nacional",
keywords_matched=matched,
identifier=rec.get("identificador", ""),
section=rec.get("seccion_codigo", ""),
))
return changes
def scan_boe(self, days_back: int = 30) -> List[LegalChange]:
"""Scan the BOE OpenData sumario, one disposition at a time (v16.0.1).
Fills ``self.boe_scan`` with day-level accounting so a run that could
not fetch some days is never confused with a run that found nothing.
"""
changes: List[LegalChange] = []
scan = {"days_requested": days_back, "issues_scanned": 0, "no_issue_days": 0,
"failed_days": [], "items_scanned": 0, "items_matched": 0,
"sections_scanned": self.boe_sections or "all"}
for i in range(days_back):
date = datetime.now() - timedelta(days=i)
date_str = date.strftime("%Y%m%d")
date_label = date.strftime("%d/%m/%Y")
result = BOEClient.get_sumario(date_str)
if result["status"] == "no_issue":
scan["no_issue_days"] += 1
continue
if result["status"] != "ok":
detail = str(result.get("message") or result.get("code") or "unknown")
scan["failed_days"].append({"date": date_label, "error": detail})
self.source_errors.append({"ccaa": "nacional", "source": "BOE",
"error": f"BOE sumario {date_label}: {detail}"})
continue
records = BOEClient.parse_sumario(result["payload"])
if self.boe_sections is not None:
records = [r for r in records
if str(r.get("seccion_codigo", "")).upper() in self.boe_sections]
scan["issues_scanned"] += 1
scan["items_scanned"] += len(records)
day_changes = self.boe_changes_from_records(records, date_label)
scan["items_matched"] += len(day_changes)
changes.extend(day_changes)
scan["status"] = (SOURCE_UNREACHABLE if scan["issues_scanned"] == 0 and scan["failed_days"]
else "PARTIAL" if scan["failed_days"]
else SOURCE_OK if changes else SOURCE_EMPTY)
self.boe_scan = scan
return changes
def scan_ccaa(self, days_back: int = 30) -> List[LegalChange]:
"""Scan the declared feeds of each requested CCAA; record a status per CCAA.
v17: a CCAA may declare several feeds (see :func:`feeds_for_source`).
Each feed's outcome is kept in ``feeds`` of the status record and the
CCAA status is the honest aggregate: ``UNREACHABLE`` when no feed could
be read, ``PARTIAL`` when some could and some could not, ``OK`` /
``EMPTY`` only when every feed was read.
"""
changes: List[LegalChange] = []
self.ccaa_status = []
for ccaa_key in self.target_ccaa:
if ccaa_key not in CCAA_SOURCES:
self.ccaa_status.append({"ccaa": ccaa_key, "source": "", "rss_url": "",
"status": SOURCE_NOT_CONFIGURED, "entries_fetched": 0,
"entries_matched": 0, "detail": "unknown CCAA key"})
self.source_errors.append({"ccaa": ccaa_key, "source": "",
"error": "unknown CCAA key — not scanned"})
continue
source = CCAA_SOURCES[ccaa_key]
short_name = source["name"].split("—")[0].strip()
feeds = feeds_for_source(source)
status_rec = {"ccaa": ccaa_key, "source": short_name,
"rss_url": source.get("rss_url") or "",
"feeds": [],
"status": SOURCE_NOT_CONFIGURED, "entries_fetched": 0,
"entries_matched": 0, "detail": "",
"rss_last_check": source.get("rss_last_check")}
if source.get("rss_note"):
status_rec["note"] = source["rss_note"]
if not feeds:
manual = source.get("search_url") or source["web_url"]
status_rec["detail"] = f"no machine-readable feed configured — search manually at {manual}"
self.ccaa_status.append(status_rec)
self.source_errors.append({
"ccaa": ccaa_key, "source": short_name,
"error": "no machine-readable feed configured — bulletin NOT scanned "
f"automatically; search manually at {manual}",
})
continue
fetched: List[Dict] = []
failed: List[str] = []
for feed in feeds:
result = RSSParser.fetch_source_feed(feed, CONSTRUCTION_KEYWORDS,
max_age_days=days_back)
label = feed.get("label") or feed.get("url") or ""
feed_rec = {
"label": label, "kind": feed.get("kind") or FEED_KIND_RSS,
"url": feed.get("url") or "", "status": result["status"],
"entries_fetched": result["entries_fetched"],
"entries_matched": len(result["entries"]), "error": result["error"],
}
if "issues_scanned" in result:
feed_rec["issues_scanned"] = result["issues_scanned"]
status_rec["feeds"].append(feed_rec)
if result["status"] in (SOURCE_OK, SOURCE_EMPTY):
fetched.append(result)
elif result["status"] == SOURCE_PARTIAL:
# v18: part of the window was read — keep it AND flag the gap
fetched.append(result)
failed.append(f"{label}: {result['error'] or result['status']}")
else:
failed.append(f"{label}: {result['error'] or result['status']}")
# v18: the same act can appear in two feeds of one CCAA (DOGC
# summary + Socrata dataset); keep the first occurrence by title.
seen_titles = set()
deduplicated = 0
for r in fetched:
kept = []
for entry in r["entries"]:
key = normalise_title(entry.get("title", ""))
if key and key in seen_titles:
deduplicated += 1
continue
seen_titles.add(key)
kept.append(entry)
r["entries"] = kept
status_rec["entries_deduplicated"] = deduplicated
status_rec["entries_fetched"] = sum(r["entries_fetched"] for r in fetched)
status_rec["entries_matched"] = sum(len(r["entries"]) for r in fetched)
if not fetched:
status_rec["status"] = SOURCE_UNREACHABLE
status_rec["detail"] = "; ".join(failed)
self.source_errors.append({"ccaa": ccaa_key, "source": short_name,
"error": status_rec["detail"]})
elif failed:
status_rec["status"] = SOURCE_PARTIAL
status_rec["detail"] = (f"{len(fetched)}/{len(feeds)} feeds read; NOT read: "
+ "; ".join(failed))
self.source_errors.append({"ccaa": ccaa_key, "source": short_name,
"error": status_rec["detail"]})
elif status_rec["entries_matched"]:
status_rec["status"] = SOURCE_OK
else:
status_rec["status"] = SOURCE_EMPTY
status_rec["detail"] = (f"{len(feeds)} feed(s) fetched ({status_rec['entries_fetched']} "
f"entries); none matched construction keywords within "
f"{days_back} days")
self.ccaa_status.append(status_rec)
for entry in (e for r in fetched for e in r["entries"]):
classification = LegalClassifier.classify(
entry.get("title", ""), entry.get("description", ""),
entry.get("keywords_matched", []))
changes.append(LegalChange(
source=short_name,
date=entry.get("date", ""),
title=entry.get("title", "Sin título"),
category=classification["category"],
impact_level=classification["impact_level"],
summary=entry.get("description", "")[:200],
url=entry.get("url", source["web_url"]),
affects_visado=classification["affects_visado"],
ccaa=ccaa_key,
keywords_matched=entry.get("keywords_matched", []),
date_unparsed=bool(entry.get("date_unparsed", False)),
))
return changes
def coverage(self) -> Dict:
"""Summarise whether every requested source was actually scanned.
v17: a CCAA whose feeds were only partly read (``PARTIAL``) is listed in
``ccaa_partial`` and keeps the overall status below ``COMPLETE``.
"""
boe_status = self.boe_scan.get("status", SOURCE_UNREACHABLE) if self.boe_scan else "NOT_RUN"
scanned = [s for s in self.ccaa_status if s["status"] in (SOURCE_OK, SOURCE_EMPTY)]
partial = [s["ccaa"] for s in self.ccaa_status if s["status"] == SOURCE_PARTIAL]
unreachable = [s["ccaa"] for s in self.ccaa_status if s["status"] == SOURCE_UNREACHABLE]
not_configured = [s["ccaa"] for s in self.ccaa_status if s["status"] == SOURCE_NOT_CONFIGURED]
boe_ok = boe_status in (SOURCE_OK, SOURCE_EMPTY)
if boe_ok and not unreachable and not not_configured and not partial:
status = "COMPLETE"
elif boe_ok or scanned or partial:
status = "PARTIAL"
else:
status = "FAILED"
return {
"status": status,
"boe": boe_status,
"ccaa_requested": len(self.ccaa_status),
"ccaa_scanned": len(scanned),
"ccaa_partial": partial,
"ccaa_unreachable": unreachable,
"ccaa_not_configured": not_configured,
}
def run(self, language: str = "ca", days_back: int = 30) -> str:
"""
Run full monitoring pipeline.
Returns formatted digest string. Progress goes to stderr (v16) so that
stdout can carry clean JSON.
"""
self.source_errors = []
self.ccaa_status = []
self.boe_scan = {}
print("🔍 Scanning BOE (national, OpenData sumario API)...", file=sys.stderr)
boe_changes = self.scan_boe(days_back=days_back)
b = self.boe_scan
print(f" BOE: {len(boe_changes)} matching dispositions in {b.get('issues_scanned', 0)} issues "
f"({b.get('items_scanned', 0)} items scanned, {b.get('no_issue_days', 0)} days without issue, "
f"{len(b.get('failed_days', []))} days FAILED) -> {b.get('status')}", file=sys.stderr)
print(f"🔍 Scanning {len(self.target_ccaa)} CCAA bulletins...", file=sys.stderr)
ccaa_changes = self.scan_ccaa(days_back=days_back)
for rec in self.ccaa_status:
detail = f" — {rec['detail']}" if rec.get("detail") else ""
print(f" {rec['ccaa']}: {rec['status']} ({rec['entries_matched']} matched / "
f"{rec['entries_fetched']} fetched){detail}", file=sys.stderr)
cov = self.coverage()
print(f" Coverage: {cov['status']} — CCAA scanned {cov['ccaa_scanned']}/{cov['ccaa_requested']}",
file=sys.stderr)
self.changes = boe_changes + ccaa_changes
# Sort by impact (HIGH first) then date
impact_order = {"ALTO": 0, "MEDIO": 1, "BAJO": 2}
self.changes.sort(key=lambda c: (impact_order.get(c.impact_level, 9), c.date))
digest = DigestGenerator.generate(self.changes, language=language,
source_status=self.source_status_records())
return digest
def source_status_records(self) -> List[Dict]:
"""BOE + CCAA status rows for the digest (v16.0.1)."""
rows: List[Dict] = []
if self.boe_scan:
b = self.boe_scan
failed = b.get("failed_days", [])
detail = ""
if failed:
detail = f"{len(failed)}/{b.get('days_requested', 0)} days failed: " + \
"; ".join(f"{f['date']} ({f['error']})" for f in failed[:5])
rows.append({"ccaa": "nacional", "source": "BOE", "status": b.get("status", ""),
"entries_matched": b.get("items_matched", 0),
"entries_fetched": b.get("items_scanned", 0), "detail": detail})
rows.extend(self.ccaa_status)
return rows
def to_dict(self, days_back: int = 30, language: str = "ca") -> Dict:
"""Structured result: changes, per-source status, coverage and disclosed errors."""
return {
"agent_version": AGENT_VERSION,
"generated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"window_days": days_back,
"language": language,
"ccaa_requested": self.target_ccaa,
"coverage": self.coverage(),
"boe_scan": self.boe_scan,
"ccaa_sources": self.ccaa_status,
"change_count": len(self.changes),
"changes": [asdict(c) for c in self.changes],
"source_errors": self.source_errors,
}
def to_json(self, days_back: int = 30, language: str = "ca") -> str:
"""Export the structured result as JSON (for API integration)."""
return json.dumps(self.to_dict(days_back, language), ensure_ascii=False, indent=2)
# ═══════════════════════════════════════════════════════════
# EMAIL PREVIEW (no sending capability exists in this package)
# ═══════════════════════════════════════════════════════════
class EmailPreviewWriter:
"""
Write an email-shaped preview of the digest to an EXPLICIT path.
There is no SMTP/SendGrid/Mailgun integration in this package. v15 exposed
``--email ADDR`` which looked like sending but only saved
``digest_YYYYMM.txt`` in the current directory. v16 names the behaviour
honestly (``--save-email-preview PATH``); sending, if ever needed, belongs to
the web layer (see commands/monitor-legal.md, EXECUTION MODEL).
"""
@staticmethod
def write_preview(digest: str, path: str, recipients: Optional[List[str]] = None,
subject: Optional[str] = None) -> Dict:
"""Write the preview file and return a status record. Never sends anything."""
recipients = recipients or []
if not subject:
subject = (f"RailNexus — Novedades legislativas construcción "
f"{datetime.now().strftime('%B %Y')}")
with open(path, "w", encoding="utf-8") as f:
f.write(f"TO: {', '.join(recipients) if recipients else '(recipients not supplied)'}\n")
f.write(f"SUBJECT: {subject}\n")
f.write(f"DATE: {datetime.now().isoformat()}\n")
f.write(f"{'=' * 70}\n\n")
f.write(digest)
return {
"status": "preview_written_not_sent",
"path": path,
"recipients": len(recipients),
"note": "No email was sent. This package has no mail transport; the web layer owns delivery.",
}
# ═══════════════════════════════════════════════════════════
# CLI ENTRY POINT
# ═══════════════════════════════════════════════════════════
def build_parser():
"""Build the side-effect-free CLI parser (importable for tests)."""
import argparse
parser = argparse.ArgumentParser(
description=f"RailNexus Legal Monitor v{AGENT_VERSION} — Construction law changes. "
"Writes nothing to disk unless --output / --save-email-preview is given.")
parser.add_argument("--ccaa", nargs="+", default=["cataluña", "valencia"],
help="CCAA to monitor (default: cataluña valencia)")
parser.add_argument("--lang", default="ca", choices=["ca", "es", "en"],
help="Output language (default: ca)")
parser.add_argument("--days", type=int, default=30,
help="Days to look back — applied to BOE pages AND RSS entry dates (default: 30)")
parser.add_argument("--format", default="text", choices=["text", "json"],
help="What to print on stdout (default: text digest)")
parser.add_argument("--boe-sections", nargs="+", default=None, metavar="CODE",
help="BOE sumario sections to scan (default: 1 3 = Disposiciones "
"generales + Otras disposiciones; 'all' scans every section, "
"including V. Anuncios procurement notices)")
parser.add_argument("--output", default=None,
help="Explicit path to ALSO write the selected format to (optional)")
parser.add_argument("--save-email-preview", default=None, metavar="PATH",
help="Explicit path to write an email-shaped preview of the digest. "
"Nothing is sent.")
parser.add_argument("--recipients", nargs="+", default=None,
help="Recipient list shown in the preview header (informational only)")
return parser
def main() -> int:
"""Run the monitor; return process exit code."""
parser = build_parser()
args = parser.parse_args()
if args.days <= 0:
parser.error("--days must be a positive integer")
print(f"🏗️ RailNexus Legal Monitor v{AGENT_VERSION}", file=sys.stderr)
print(f" Monitoring: BOE + {', '.join(args.ccaa)}", file=sys.stderr)
print(f" Period: last {args.days} days", file=sys.stderr)
print(f" Language: {args.lang}\n", file=sys.stderr)
monitor = LegalMonitor(target_ccaa=args.ccaa, boe_sections=args.boe_sections)
digest = monitor.run(language=args.lang, days_back=args.days)
rendered = digest if args.format == "text" else monitor.to_json(args.days, args.lang)
print(rendered)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(rendered + ("\n" if not rendered.endswith("\n") else ""))
print(f"📄 written: {args.output}", file=sys.stderr)
if args.save_email_preview:
result = EmailPreviewWriter.write_preview(digest, args.save_email_preview, args.recipients)
print(f"📧 {result}", file=sys.stderr)
# v16.0.1: exit 0 only when every requested source was really scanned.
coverage = monitor.coverage()
if coverage["status"] != "COMPLETE":
print(f"⚠ coverage {coverage['status']}: BOE={coverage['boe']}, "
f"CCAA unreachable={coverage['ccaa_unreachable']}, "
f"partial={coverage['ccaa_partial']}, "
f"not configured={coverage['ccaa_not_configured']}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
"""
legal_monitor.py — Spanish Construction Law Monitor (v18)
Queries the BOE OpenData sumario API + CCAA bulletin feeds (RSS/Atom, open-data
JSON datasets, JSON row services and the DOGC summary API) for
construction-related legal changes.
v18 (2026-09-16, rounds 4-5 — every URL below was fetched and parsed live):
- Round 4 (sonnet): six bulletins wired with real RSS (BOCM, BOCYL, DOE, BOIB,
BOC Cantabria, BOME); eight investigated and left without feed.
- Round 5 (fable): three of those eight are now scanned through their own
JSON services, and Catalunya is scanned through the DOGC's own summary API:
* **DOGC (Catalunya), ALL sections** — the "Sumari del DOGC" page is fed by
``POST https://portaldogc.gencat.cat/eadop-rest/api/dogc/summaryDOGC``
(form fields ``numDOGC`` + ``language``; ``calendarDOGC`` with ``month`` /
``year`` lists the issue numbers of a month). Sections returned live on
2026-09-16: Disposicions generals, Altres disposicions, Càrrecs i personal,
Anuncis, Administració local, Altres subjectes emissors — i.e. the edictes
of the Comissions Territorials d'Urbanisme and the municipal planning
approvals that the Section-1-only Socrata dataset (kept as a second feed)
never carried. The host only completes a TLS handshake at OpenSSL security
level 1 (``SSLV3_ALERT_HANDSHAKE_FAILURE`` at the default level 2), so a
session with a scoped, still certificate-verifying context is used for that
host only (:func:`legacy_tls_session`).
* **BOA (Aragón)** — the SPA's open-data JSON service
``cgi-bin/EBOA/BRSCGI?...&SEC=OPENDATABOAJSON&@PUBL-GE=YYYYMMDD`` (the URL
the region's own CKAN catalogue publishes for the "Decretos y Leyes"
dataset) returns one record per disposition with title, section, rank,
issuer, publication date, ELI URI and text. The producer emits invalid JSON
escapes (``\\_`` inside ``Texto``) and ISO-8859-1; both are repaired before
parsing (``lenient_json``). Sections I + III are requested (same default as
the BOE); V. Anuncios is available by changing ``SECC-C``.
* **BORM (Murcia)** — the SPA's ``services/boletin/fecha/DD-MM-YYYY/sumario``
returns the day's issue with every announcement (``anunciosBoletin``:
``sumario`` = title, ``apartado`` / ``subApartado``, ``numero``). Scanned
one day at a time like the BOE (HTTP 404 = no issue that day); the
"Autoridades y Personal" sub-section is excluded as noise.
* Asturias, Canarias, Castilla-La Mancha, Navarra, La Rioja and Ceuta stay
without a machine-readable feed after a second, different set of attempts
(regional CKAN/open-data APIs, datos.gob.es, Joomla/Liferay conventions);
what was tried is in each ``rss_last_check``. Asturias publishes a yearly
open-data archive of BOPA dispositions (the 2025 file appeared in
August 2026) — an archive, not a monitoring feed.
- Feed kinds: ``rss`` | ``socrata_json`` | ``json_rows`` (generic JSON list,
optional per-day URL template) | ``dogc_summary`` | ``bocm_xml`` (v19: the
BOCM's per-issue native XML, issue calendar from sumarios.rss). A feed that could read
only part of its window reports ``PARTIAL`` and keeps what it read; the
CCAA aggregate is then ``PARTIAL`` (coverage != COMPLETE, exit 1).
- Entries of one CCAA are de-duplicated by normalised title across its feeds
(the DOGC summary and the Socrata dataset both list a new Decret).
- Catalan keyword equivalents were added to the keyword lists so Catalan
titles (DOGC, BOIB) match without a second language fetch.
v17 (2026-09-16, third correction round — the four CCAA feeds left BLOCKED in
v16.0.1 were re-investigated with live autodiscovery on each bulletin's own site
and on the official open-data portals; every URL below was fetched and parsed):
- País Vasco (BOPV): ``https://www.euskadi.eus/bopv2/datos/Ultimo.xml`` — the
"RSS" link on the official "Último boletín" page. RSS 2.0, one entry per
disposition of the LATEST issue only (nº 176 of 15/09/2026: 16 dated entries,
2 construction matches). The old ``/contenidos/informacion/ehaa_rss/...`` is 404.
- Andalucía (BOJA): ``/boja/distribucion/s51.xml`` (1. Disposiciones generales)
and ``s54.xml`` (3. Otras disposiciones) — Atom feeds advertised with
``<link rel="alternate">`` on every issue page and documented in the BOJA FAQ
"Distribución de RSS". Current issue only (nº 180 of 16/09/2026). WARNING: the
legacy ``/boja/distribucion/s0..s5.2.xml`` still answer 200 but are frozen at
issue 2021/217 (lastBuildDate 2021-11-11) with undated entries — never use them.
The old ``/eboja/rss/rss.html`` is 404.
- Catalunya (DOGC): no RSS/Atom exists (e-mail "Alertes DOGC" only; portaldogc
403). The DOGC "Dades obertes" page points to the official Socrata dataset
``n6hn-rmy7`` "Normativa del DOGC i del Portal Jurídic de Catalunya"
(attribution EADOP, refreshed daily — newest row DOGC nº 9751 of 2026-09-15).
Scanned through the JSON API with a server-side date filter. Scope: Section 1
normative acts (laws, decrets, ordres) — not Section 3 nor announcements.
- Valencia (DOGV): genuinely no machine-readable feed. ``/datos/rss/*`` answers
403 for every file name and for the folder, with default and browser
User-Agent; ``/es/rss`` and ``/rss/dogv_es.xml`` redirect to the HTML home;
"Alertas y subscripciones" redirects to the personal-area login; the GVA
open-data portal has no DOGV dataset (package_list, 1309 packages) and its
search API answers 500; datos.gob.es lists no DOGV bulletin dataset. Kept as a
dead URL that is retried and reported ``UNREACHABLE`` on every run.
- A CCAA may now declare several feeds (``feeds``); per-feed outcomes are
reported and a source whose feeds partly failed is ``PARTIAL`` (never
collapsed into OK/EMPTY), which keeps ``coverage.status != COMPLETE``.
Sources:
- BOE OpenData sumario API (https://www.boe.es/datosabiertos/api/boe/sumario/YYYYMMDD,
``Accept: application/json``) — one disposition per item, keyword scan on the
disposition title. Live-verified 2026-09-15 (HTTP 200 JSON; 404 + API code 404
on days without an issue, e.g. Sundays).
v16.0.0 scanned the HTML page ``/boe/dias/YYYY/MM/DD/`` as one blob; its footer
carries a site-wide "Accesibilidad" link, so every day matched the keyword
"accesibilidad", every entry was a synthetic "BOE dd/mm — disposiciones…" line
with an empty summary, and a failed fetch was silently skipped.
- CCAA RSS feeds where they exist (see CCAA_SOURCES); others are listed with
search URLs only and are NOT scanned automatically. Every requested source
reports a status (OK / EMPTY / UNREACHABLE / NOT_CONFIGURED) in the JSON, in
the text digest and through the exit code — an unreachable feed is never
reported the same way as a feed with nothing relevant.
CLI contract (v16 — v14 audit F-09):