76 lines
3.0 KiB
Python
76 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import socket
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from datetime import datetime
|
|
from typing import Optional
|
|
|
|
from .model import Snapshot
|
|
from .parser import parse_forecast, parse_observation
|
|
|
|
URL_RE = re.compile(r"https://(www\.)?meteoinfo\.ru/(pogoda|forecasts)/[A-Za-z0-9_\-/]+")
|
|
URL_HINT = "Адрес должен вести на страницу станции вида https://meteoinfo.ru/pogoda/russia/…"
|
|
|
|
|
|
def is_valid_url(url: str) -> bool:
|
|
return URL_RE.fullmatch(url) is not None
|
|
|
|
|
|
def page_url(url: str, section: str) -> str:
|
|
return re.sub(r"/(pogoda|forecasts)/", f"/{section}/", url, count=1)
|
|
|
|
|
|
def _get(url: str) -> str:
|
|
req = urllib.request.Request(url, headers={
|
|
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) RuWeather/0.1",
|
|
"Accept-Language": "ru",
|
|
})
|
|
with urllib.request.urlopen(req, timeout=20) as resp:
|
|
return resp.read().decode("utf-8", errors="replace")
|
|
|
|
|
|
def _describe(e: Exception) -> str:
|
|
if isinstance(e, urllib.error.HTTPError):
|
|
return f"Сервер ответил: HTTP {e.code}"
|
|
if isinstance(e, (socket.timeout, TimeoutError)):
|
|
return "Превышено время ожидания ответа"
|
|
if isinstance(e, urllib.error.URLError):
|
|
if isinstance(e.reason, (socket.timeout, TimeoutError)):
|
|
return "Превышено время ожидания ответа"
|
|
return "Нет соединения с интернетом"
|
|
return str(e) or e.__class__.__name__
|
|
|
|
|
|
def _fetch_fresh(station_url: str) -> Snapshot:
|
|
now = time.time()
|
|
if not is_valid_url(station_url):
|
|
return Snapshot(station_url, obs_error=URL_HINT, fetched_at=now)
|
|
snap = Snapshot(station_url, fetched_at=now)
|
|
try:
|
|
snap.obs = parse_observation(_get(page_url(station_url, "pogoda")))
|
|
except Exception as e: # noqa: BLE001 - показываем причину пользователю
|
|
snap.obs_error = _describe(e)
|
|
try:
|
|
snap.forecast = parse_forecast(_get(page_url(station_url, "forecasts")), datetime.now())
|
|
except Exception as e: # noqa: BLE001
|
|
snap.forecast_error = _describe(e)
|
|
return snap
|
|
|
|
|
|
def refresh(old: Optional[Snapshot], station_url: str) -> Snapshot:
|
|
"""Свежие данные; при сбое для той же станции остаётся последнее удачное значение."""
|
|
fresh = _fetch_fresh(station_url)
|
|
reuse = old if old is not None and old.station_url == station_url else None
|
|
got_something = fresh.obs is not None or fresh.forecast is not None
|
|
return Snapshot(
|
|
station_url=station_url,
|
|
obs=fresh.obs or (reuse.obs if reuse else None),
|
|
forecast=fresh.forecast or (reuse.forecast if reuse else None),
|
|
obs_error=fresh.obs_error,
|
|
forecast_error=fresh.forecast_error,
|
|
fetched_at=fresh.fetched_at if got_something else (reuse.fetched_at if reuse else fresh.fetched_at),
|
|
)
|