diff --git a/tools/mock/mock_peertube.py b/tools/mock/mock_peertube.py index 142c7a1..6f2235e 100644 --- a/tools/mock/mock_peertube.py +++ b/tools/mock/mock_peertube.py @@ -34,8 +34,22 @@ import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer UPSTREAM = "https://peertube2.cpy.re" +UP_HOST = "peertube2.cpy.re" AVATAR = UPSTREAM + "/lazy-static/avatars/73e78544-cbae-439e-8c84-98b0756fbde7.jpg" PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080 +# How the emulator addresses this proxy. The app decides a video/channel is +# "local" by matching its host against the instance host, so we relabel the +# upstream host to ours in the JSON (only the `host` fields, never URLs, so +# thumbnails/media keep pointing at peertube2). +MOCK_HOST = f"10.0.2.2:{PORT}" + + +def relabel_hosts(obj): + if isinstance(obj, dict): + return {k: (MOCK_HOST if k == "host" and v == UP_HOST else relabel_hosts(v)) for k, v in obj.items()} + if isinstance(obj, list): + return [relabel_hosts(x) for x in obj] + return obj def fetch(path_with_query): @@ -54,7 +68,7 @@ class Handler(BaseHTTPRequestHandler): pass def _json(self, obj, code=200): - data = json.dumps(obj).encode() + data = json.dumps(relabel_hosts(obj)).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) @@ -127,9 +141,16 @@ class Handler(BaseHTTPRequestHandler): return self._json(detail) # Everything else (video lists, detail, channels, thumbnails) is proxied. + # A handle the app built with our host (name@10.0.2.2:PORT) is mapped back + # to the upstream host before we ask peertube2. + upstream = self.path.replace(MOCK_HOST, UP_HOST).replace( + MOCK_HOST.replace(":", "%3A"), UP_HOST) try: - code, ctype, body = fetch(self.path) - self._raw(code, ctype, body) + code, ctype, body = fetch(upstream) + if "json" in ctype: + self._json(json.loads(body), code) # relabel hosts in proxied JSON too + else: + self._raw(code, ctype, body) except urllib.error.HTTPError as e: self._raw(e.code, "application/json", e.read()) except Exception as e: # noqa: BLE001