"""Fetch helper for the kewpie external-proxy collection. Kept in the owned directory so every download is reproducible from the manifest's source_page. Not part of the product code. """ import gzip import json import re import ssl import sys import urllib.parse import urllib.request try: import certifi _CTX = ssl.create_default_context(cafile=certifi.where()) except ImportError: # pragma: no cover - certifi ships with this repo's venv _CTX = ssl.create_default_context() UA = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" ) def get(url, referer=None, lang="ja,en-US;q=0.9,en;q=0.8"): req = urllib.request.Request(url) req.add_header("User-Agent", UA) req.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8") req.add_header("Accept-Language", lang) req.add_header("Accept-Encoding", "gzip, deflate") if referer: req.add_header("Referer", referer) with urllib.request.urlopen(req, timeout=40, context=_CTX) as r: raw = r.read() if r.headers.get("Content-Encoding") == "gzip": raw = gzip.decompress(raw) return raw, r.headers.get("Content-Type", "") def text(url, **kw): raw, ctype = get(url, **kw) for enc in ("utf-8", "shift_jis", "euc-jp"): try: return raw.decode(enc) except UnicodeDecodeError: continue return raw.decode("utf-8", "replace") def download(url, path, referer=None): raw, ctype = get(url, referer=referer) with open(path, "wb") as f: f.write(raw) return len(raw), ctype def amazon_search(query, limit=20): """Return [(asin, title)] from an amazon.co.jp search.""" h = text("https://www.amazon.co.jp/s?k=" + urllib.parse.quote(query)) out = [] for block in re.split(r'(?=