| 1 | |
| 2 | |
| 3 | import json |
| 4 | import re |
| 5 | import urllib.error |
| 6 | import urllib.parse |
| 7 | import urllib.request |
| 8 | |
| 9 | |
| 10 | class _NoRedirect(urllib.request.HTTPRedirectHandler): |
| 11 | def redirect_request(self, *args, **kwargs): |
| 12 | return None |
| 13 | |
| 14 | |
| 15 | _OPENER = urllib.request.build_opener(_NoRedirect) |
| 16 | |
| 17 | |
| 18 | class Resp: |
| 19 | def __init__(self, status, headers, body): |
| 20 | self.status = status |
| 21 | self.headers = headers |
| 22 | self.body = body |
| 23 | |
| 24 | @property |
| 25 | def text(self): |
| 26 | return self.body.decode("utf-8", "replace") |
| 27 | |
| 28 | @property |
| 29 | def location(self): |
| 30 | return self.headers.get("Location", "") |
| 31 | |
| 32 | def json(self): |
| 33 | return json.loads(self.body or b"null") |
| 34 | |
| 35 | |
| 36 | def raw_request(url, method="GET", data=None, headers=None, timeout=60): |
| 37 | req = urllib.request.Request(url, data=data, method=method, headers=headers or {}) |
| 38 | try: |
| 39 | with _OPENER.open(req, timeout=timeout) as r: |
| 40 | return Resp(r.status, r.headers, r.read()) |
| 41 | except urllib.error.HTTPError as e: |
| 42 | return Resp(e.code, e.headers, e.read()) |
| 43 | |
| 44 | |
| 45 | class Client: |
| 46 | def __init__(self, base): |
| 47 | self.base = base.rstrip("/") |
| 48 | self.cookies = {} |
| 49 | self.csrf = None |
| 50 | |
| 51 | def cookie_header(self): |
| 52 | return "; ".join(f"{k}={v}" for k, v in self.cookies.items()) |
| 53 | |
| 54 | def _absorb(self, resp): |
| 55 | for sc in resp.headers.get_all("Set-Cookie") or []: |
| 56 | pair = sc.split(";", 1)[0] |
| 57 | if "=" not in pair: |
| 58 | continue |
| 59 | k, v = pair.split("=", 1) |
| 60 | low = sc.lower() |
| 61 | if v == "" or "max-age=0" in low: |
| 62 | self.cookies.pop(k.strip(), None) |
| 63 | else: |
| 64 | self.cookies[k.strip()] = v |
| 65 | |
| 66 | def request(self, path, method="GET", data=None, headers=None, follow=True): |
| 67 | url = path if path.startswith("http") else self.base + path |
| 68 | for _ in range(8): |
| 69 | h = {"Origin": self.base, "Referer": url} |
| 70 | h.update(headers or {}) |
| 71 | if self.cookies: |
| 72 | h["Cookie"] = self.cookie_header() |
| 73 | resp = raw_request(url, method, data, h) |
| 74 | self._absorb(resp) |
| 75 | if follow and resp.status in (301, 302, 303, 307, 308) and resp.location: |
| 76 | url = urllib.parse.urljoin(url, resp.location) |
| 77 | if resp.status in (301, 302, 303): |
| 78 | method, data = "GET", None |
| 79 | continue |
| 80 | resp.url = url |
| 81 | return resp |
| 82 | resp.url = url |
| 83 | return resp |
| 84 | |
| 85 | def get(self, path, **kw): |
| 86 | return self.request(path, **kw) |
| 87 | |
| 88 | def post(self, path, fields, follow=True): |
| 89 | if isinstance(fields, dict): |
| 90 | fields = list(fields.items()) |
| 91 | if self.csrf and not any(k in ("csrf", "precsrf") for k, _ in fields): |
| 92 | fields = [("csrf", self.csrf)] + list(fields) |
| 93 | body = urllib.parse.urlencode(fields).encode() |
| 94 | return self.request( |
| 95 | path, "POST", body, |
| 96 | {"Content-Type": "application/x-www-form-urlencoded"}, follow=follow, |
| 97 | ) |
| 98 | |
| 99 | |
| 100 | def field(html, name): |
| 101 | m = re.search(r'name="%s"[^>]*?value="([^"]*)"' % re.escape(name), html) |
| 102 | if not m: |
| 103 | m = re.search(r'value="([^"]*)"[^>]*?name="%s"' % re.escape(name), html) |
| 104 | return m.group(1) if m else None |