`` 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
```` header and one ```` 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
`` |