markedet's picture
Add license files and NOTICE, update license fields
98ee81b verified
Raw History Blame Contribute Delete
12.3 kB
"""Polite reader for lightweight read routes a site offers itself:
RSS/Atom/JSON Feed, sitemaps, oEmbed (via its discovery link), JSON-LD and Open Graph.
Standard library only. Low rate, caching, ETag / If-None-Match, honest User-Agent,
robots.txt check (urllib.robotparser), same-host redirects and links only.
It does NOT read the site's terms for you. Read them first (guide 14, step 1).
License: Apache-2.0.
"""
from __future__ import annotations
import json
import time
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from html.parser import HTMLParser
from urllib.robotparser import RobotFileParser
FEED_TYPES = {
"application/rss+xml": "rss",
"application/atom+xml": "atom",
"application/feed+json": "jsonfeed",
"application/json": "jsonfeed", # only accepted together with rel="alternate"
}
OEMBED_TYPES = {"application/json+oembed", "text/xml+oembed"}
class Blocked(Exception):
"""Raised instead of fetching: robots.txt disallows it, or the host is not allowed."""
@dataclass
class Response:
url: str
status: int
body: bytes
headers: dict
from_cache: bool = False # True when answered from cache (fresh, or a 304)
revalidated: bool = False # True when the server answered 304 Not Modified
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **kw): # we follow redirects ourselves, with checks
return None
class ReadRoutes:
def __init__(self, user_agent: str, min_interval: float = 2.0, timeout: float = 15.0,
max_bytes: int = 2_000_000, cache_ttl: float = 300.0,
sleep=time.sleep, clock=time.monotonic):
if "/" not in user_agent or len(user_agent) < 8:
raise ValueError("use an honest User-Agent like 'my-agent/0.1 (+https://example.com/about-my-agent)'")
self.ua, self.min_interval, self.timeout = user_agent, min_interval, timeout
self.max_bytes, self.cache_ttl, self._sleep, self._clock = max_bytes, cache_ttl, sleep, clock
self._opener = urllib.request.build_opener(_NoRedirect)
self._cache: dict[str, tuple[float, str | None, str | None, Response]] = {}
self._robots: dict[str, RobotFileParser] = {}
self._last_request: dict[str, float] = {}
# ---- robots.txt -------------------------------------------------
def _robots_for(self, url: str) -> RobotFileParser:
p = urllib.parse.urlsplit(url)
origin = f"{p.scheme}://{p.netloc}"
if origin not in self._robots:
rp = RobotFileParser()
try:
r = self._raw(origin + "/robots.txt", {})
if r.status == 200:
rp.parse(r.body.decode("utf-8", "replace").splitlines())
elif r.status in (401, 403) or r.status >= 500:
rp.disallow_all = True # RFC 9309: unreachable or forbidden means do not crawl
else:
rp.allow_all = True # 404 and other 4xx: no robots rules
except (urllib.error.URLError, OSError):
rp.disallow_all = True
self._robots[origin] = rp
return self._robots[origin]
def allowed(self, url: str) -> bool:
rp = self._robots_for(url)
if rp.disallow_all:
return False
if rp.allow_all:
return True
return rp.can_fetch(self.ua, url)
def sitemaps_from_robots(self, origin_url: str) -> list[str]:
return list(self._robots_for(origin_url).site_maps() or [])
# ---- HTTP -------------------------------------------------------
def _wait(self, host: str, crawl_delay: float | None):
gap = max(self.min_interval, crawl_delay or 0.0)
last = self._last_request.get(host)
if last is not None:
remaining = gap - (self._clock() - last)
if remaining > 0:
self._sleep(remaining)
self._last_request[host] = self._clock()
def _raw(self, url: str, extra: dict) -> Response:
host = urllib.parse.urlsplit(url).netloc
self._wait(host, None)
headers = {"User-Agent": self.ua, "Accept": "*/*", "Accept-Encoding": "identity", **extra}
req = urllib.request.Request(url, headers=headers)
try:
with self._opener.open(req, timeout=self.timeout) as resp:
body = resp.read(self.max_bytes + 1)
if len(body) > self.max_bytes:
raise ValueError(f"response larger than {self.max_bytes} bytes: not read")
return Response(url, resp.status, body, dict(resp.headers))
except urllib.error.HTTPError as err:
headers = dict(err.headers)
err.close()
return Response(url, err.code, b"", headers)
def get(self, url: str, max_redirects: int = 3) -> Response:
"""GET one URL politely. Raises Blocked if robots.txt disallows it."""
origin = urllib.parse.urlsplit(url).netloc
for _ in range(max_redirects + 1):
if not self.allowed(url):
raise Blocked(f"robots.txt disallows {url} for {self.ua!r} (or robots.txt was unreachable)")
now = self._clock()
cached = self._cache.get(url)
if cached and now - cached[0] < self.cache_ttl:
r = cached[3]
return Response(r.url, r.status, r.body, r.headers, from_cache=True)
extra = {}
if cached and cached[1]:
extra["If-None-Match"] = cached[1]
if cached and cached[2]:
extra["If-Modified-Since"] = cached[2]
rp = self._robots_for(url)
self._wait_extra(url, rp)
r = self._raw(url, extra)
if r.status in (301, 302, 303, 307, 308):
target = urllib.parse.urljoin(url, r.headers.get("Location", ""))
if urllib.parse.urlsplit(target).netloc != origin:
raise Blocked(f"redirect to another host refused: {target}")
url = target
continue
if r.status == 304 and cached:
self._cache[url] = (now, cached[1], cached[2], cached[3])
c = cached[3]
return Response(c.url, c.status, c.body, c.headers, from_cache=True, revalidated=True)
if r.status == 200 and (r.headers.get("ETag") or r.headers.get("Last-Modified")):
self._cache[url] = (now, r.headers.get("ETag"), r.headers.get("Last-Modified"), r)
return r
raise Blocked("too many redirects")
def _wait_extra(self, url, rp):
delay = rp.crawl_delay(self.ua) if not (rp.allow_all or rp.disallow_all) else None
if delay:
host = urllib.parse.urlsplit(url).netloc
last = self._last_request.get(host)
if last is not None:
remaining = float(delay) - (self._clock() - last)
if remaining > 0:
self._sleep(remaining)
# ---- discovery --------------------------------------------------
def discover(self, page_url: str) -> dict:
"""Fetch a page and list the routes it announces. Same-host links only."""
r = self.get(page_url)
return extract_routes(r.body.decode("utf-8", "replace"), page_url)
class _Head(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.links, self.meta, self.jsonld = [], [], []
self._in_ld, self._buf = False, []
def handle_starttag(self, tag, attrs):
a = {k.lower(): (v or "") for k, v in attrs}
if tag == "link":
self.links.append(a)
elif tag == "meta":
self.meta.append(a)
elif tag == "script" and a.get("type", "").lower() == "application/ld+json":
self._in_ld, self._buf = True, []
def handle_data(self, data):
if self._in_ld:
self._buf.append(data)
def handle_endtag(self, tag):
if tag == "script" and self._in_ld:
self._in_ld = False
self.jsonld.append("".join(self._buf))
def extract_routes(html: str, base_url: str) -> dict:
"""Pure function: list feeds, oEmbed link, JSON-LD and Open Graph from an HTML page."""
p = _Head()
p.feed(html)
host = urllib.parse.urlsplit(base_url).netloc
out = {"feeds": [], "oembed": [], "jsonld": [], "opengraph": {}, "ignored_other_host": []}
for a in p.links:
rel = a.get("rel", "").lower().split()
typ = a.get("type", "").lower().split(";")[0].strip()
href = a.get("href")
if not href or "alternate" not in rel:
continue
url = urllib.parse.urljoin(base_url, href)
if urllib.parse.urlsplit(url).netloc != host:
out["ignored_other_host"].append(url)
continue
if typ in OEMBED_TYPES:
out["oembed"].append({"url": url, "type": typ})
elif typ in FEED_TYPES:
out["feeds"].append({"url": url, "type": typ, "title": a.get("title", "")})
for m in p.meta:
prop = m.get("property", "")
if prop.startswith("og:") and "content" in m:
out["opengraph"].setdefault(prop, m["content"])
for raw in p.jsonld:
try:
data = json.loads(raw)
except ValueError:
continue # broken JSON-LD is common: skip it, do not guess
items = data if isinstance(data, list) else data.get("@graph", [data]) if isinstance(data, dict) else []
out["jsonld"].extend(i for i in items if isinstance(i, dict))
return out
# ---- parsers (no network) --------------------------------------------
def _safe_xml(body: bytes) -> ET.Element:
head = body[:4096].upper()
if b"<!DOCTYPE" in head or b"<!ENTITY" in body.upper():
raise ValueError("XML with DOCTYPE/ENTITY declarations is refused (entity expansion risk)")
return ET.fromstring(body)
def _local(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def parse_feed(body: bytes) -> list[dict]:
"""RSS 2.0, Atom 1.0 or JSON Feed -> [{id, title, link, published}]. Authors are not extracted on purpose."""
text = body.lstrip()
if text[:1] == b"{":
data = json.loads(body)
return [{"id": i.get("id"), "title": i.get("title"), "link": i.get("url"),
"published": i.get("date_published")} for i in data.get("items", [])]
root = _safe_xml(body)
items = []
if _local(root.tag) == "rss":
for it in root.iter("item"):
g = lambda n: (it.findtext(n) or "").strip() or None # noqa: E731
items.append({"id": g("guid"), "title": g("title"), "link": g("link"), "published": g("pubDate")})
elif _local(root.tag) == "feed":
for it in root:
if _local(it.tag) != "entry":
continue
d = {_local(c.tag): c for c in it}
link = next((c.get("href") for c in it if _local(c.tag) == "link"
and c.get("rel", "alternate") == "alternate"), None)
t = lambda k: (d[k].text or "").strip() if k in d else None # noqa: E731
items.append({"id": t("id"), "title": t("title"), "link": link,
"published": t("published") or t("updated")})
else:
raise ValueError(f"not a feed: root element {root.tag!r}")
return items
def parse_sitemap(body: bytes, max_urls: int = 5000) -> dict:
"""Sitemap or sitemap index -> {'urls': [...], 'sitemaps': [...]}, capped."""
root = _safe_xml(body)
kind = _local(root.tag)
locs = [(e.findtext("{*}loc") or "").strip() for e in root if _local(e.tag) in ("url", "sitemap")]
locs = [x for x in locs if x][:max_urls]
if kind == "urlset":
return {"urls": locs, "sitemaps": []}
if kind == "sitemapindex":
return {"urls": [], "sitemaps": locs}
raise ValueError(f"not a sitemap: root element {root.tag!r}")
def oembed_summary(body: bytes) -> dict:
"""Keep only non-personal basics from an oEmbed JSON response (no author fields, no html)."""
d = json.loads(body)
return {k: d.get(k) for k in ("type", "version", "title", "provider_name", "provider_url", "width", "height")}