"""Daily Saint Petersburg snow depth from the owner's selected public source.
The source's 'fresh snow' selector changes density calculations, not depth.
Use total depth for the latest dated day, as explicitly selected by the owner.
"""
from __future__ import annotations
import re
import threading
import time
from datetime import date, datetime, timedelta
from html.parser import HTMLParser
from http.client import HTTPException
from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo
SNOW_COVER_URL = "https://climate-energy.ru/weather/spravochnik/sndp/climate_sprav-sndp_260630687.php"
UNAVAILABLE = {"available": False, "depth_cm": None, "observed_on": None}
_MONTHS = {name: index for index, name in enumerate(
("янв", "фев", "мар", "апр", "мая", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"), 1)}
_MOSCOW = ZoneInfo("Europe/Moscow")
_MAX_BYTES = 3 * 1024 * 1024
class _SnowCells(HTMLParser):
"""Read only the named table's data cells; never run upstream scripts."""
def __init__(self):
super().__init__()
self.cells: dict[str, str] = {}
self.cell = None
def handle_starttag(self, tag, attrs):
if tag in {"td", "th"}:
name = dict(attrs).get("id", "")
self.cell = name if re.fullmatch(r"(?:tek_klim_znachen|data_)\d+", name) else None
if self.cell:
self.cells[self.cell] = ""
def handle_endtag(self, tag):
if tag in {"td", "th"}:
self.cell = None
def handle_data(self, data):
if self.cell:
self.cells[self.cell] += data
def parse_snow_cover(html: str, *, today: date | None = None) -> dict:
"""Extract the newest column, including explicit zero; reject missing/stale data."""
today = today or datetime.now(_MOSCOW).date()
table = re.search(r"
]*\bid\s*=\s*['\"]tek_parametry['\"][^>]*>(.*?)
", html, re.S | re.I)
if not table:
return dict(UNAVAILABLE)
parser = _SnowCells()
parser.feed(table[1])
# Dates on this page are assigned as literal HTML by inline JavaScript.
# Parse only that known assignment; eval/JS execution is intentionally absent.
for index, label in re.findall(
r"getElementById\(\s*['\"]data_(\d+)['\"]\s*\)\s*\.innerHTML\s*=\s*['\"]([^<]+)['\"]",
table[1],
):
parser.cells[f"data_{index}"] = label.replace(" ", " ")
columns = []
for key, label in parser.cells.items():
match = re.fullmatch(r"data_(\d+)", key)
stamp = re.fullmatch(r"\s*(\d{1,2})\.([а-я]{3})\.?\s*", label.lower())
if not match or not stamp or stamp[2] not in _MONTHS:
continue
candidates = []
for year in (today.year - 1, today.year, today.year + 1):
try:
candidates.append(date(year, _MONTHS[stamp[2]], int(stamp[1])))
except ValueError:
continue
if candidates:
observed = min(candidates, key=lambda day: abs((today - day).days))
columns.append((observed, match[1]))
if not columns:
return dict(UNAVAILABLE)
observed, index = max(columns)
depth = re.fullmatch(r"\s*(\d{1,3}(?:[.,]\d+)?)\s*см\s*", parser.cells.get(f"tek_klim_znachen{index}", ""))
if not 0 <= (today - observed).days <= 2 or not depth:
return dict(UNAVAILABLE)
depth_cm = float(depth[1].replace(",", "."))
if depth_cm > 500:
return dict(UNAVAILABLE)
return {"available": True, "depth_cm": depth_cm, "observed_on": observed.isoformat()}
class SnowCoverCache:
"""Independent of METAR: cache 30 min, retry failure after 5 min, no DB."""
def __init__(self):
self._lock = threading.Lock()
self._expires = 0.0
self._value = dict(UNAVAILABLE)
def get(self) -> dict:
if time.monotonic() < self._expires:
return dict(self._value)
if not self._lock.acquire(blocking=False):
return dict(UNAVAILABLE)
try:
if time.monotonic() < self._expires:
return dict(self._value)
value = dict(UNAVAILABLE)
try:
request = Request(SNOW_COVER_URL, headers={"Accept": "text/html", "User-Agent": "BelkiWeather/1.0"})
with urlopen(request, timeout=4) as response:
body = response.read(_MAX_BYTES + 1)
if len(body) <= _MAX_BYTES:
value = parse_snow_cover(body.decode("utf-8"))
except (OSError, HTTPException, ValueError):
pass
ttl = 1800 if value["available"] else 300
if value["available"]:
cutoff = datetime.combine(date.fromisoformat(value["observed_on"]) + timedelta(days=3), datetime.min.time(), _MOSCOW)
ttl = min(ttl, max(0, (cutoff - datetime.now(_MOSCOW)).total_seconds()))
self._value = value
self._expires = time.monotonic() + ttl
return dict(value)
finally:
self._lock.release()
snow_cover_cache = SnowCoverCache()