PulseCanvas / app · pulsecanvas.ai / scripts / upload-radio-r2.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Upload a prepared radio library via the R2 S3 API. Requires no Python packages. |
| 3 | |
| 4 | Credentials are read only from environment variables, never written into the catalog: |
| 5 | R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET. |
| 6 | Use a token scoped to Object Read & Write on the radio bucket. |
| 7 | Uploads immutable audio first, then catalogs, and publishes stations.json last. |
| 8 | """ |
| 9 | import argparse |
| 10 | from datetime import datetime, timezone |
| 11 | import hashlib |
| 12 | import hmac |
| 13 | import json |
| 14 | import os |
| 15 | from pathlib import Path |
| 16 | import re |
| 17 | from urllib.parse import quote |
| 18 | from urllib.request import Request, urlopen |
| 19 | |
| 20 | |
| 21 | def upload(directory, prefix): |
| 22 | names = ["R2_ACCOUNT_ID", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY", "R2_BUCKET"] |
| 23 | missing = [key for key in names if not os.environ.get(key)] |
| 24 | if missing: |
| 25 | raise SystemExit("Missing environment variables: " + ", ".join(missing)) |
| 26 | account, access, secret, bucket = (os.environ[key] for key in names) |
| 27 | if not re.fullmatch(r"[a-fA-F0-9]{32}", account) or not re.fullmatch(r"[a-z0-9][a-z0-9.-]+", bucket): |
| 28 | raise SystemExit("Invalid R2 account ID or bucket name") |
| 29 | host = account + ".r2.cloudflarestorage.com" |
| 30 | catalog = json.loads((directory / "catalog.json").read_text()) |
| 31 | files = [] |
| 32 | for track in catalog["tracks"]: |
| 33 | path = (directory / track["audio"]).resolve() |
| 34 | if not path.is_relative_to(directory.resolve()): |
| 35 | raise SystemExit("Audio path escapes library") |
| 36 | data = path.read_bytes() |
| 37 | if len(data) != track["byteCount"] or hashlib.sha256(data).hexdigest() != track["sha256"]: |
| 38 | raise SystemExit("Audio integrity mismatch: " + track["title"]) |
| 39 | files.append((track["audio"], data, "audio/mp4", "public, max-age=31536000, immutable")) |
| 40 | if (directory / "stations.json").exists(): |
| 41 | station_index = json.loads((directory / "stations.json").read_text()) |
| 42 | for name in dict.fromkeys(station["catalog"] for station in station_index["stations"]): |
| 43 | if name == "catalog.json": |
| 44 | continue |
| 45 | if not re.fullmatch(r"station-[a-z0-9-]+\.json", name): |
| 46 | raise SystemExit("Invalid station catalog path") |
| 47 | path = directory / name |
| 48 | files.append((name, path.read_bytes(), "application/json; charset=utf-8", "public, max-age=60")) |
| 49 | files.append(("catalog.json", (directory / "catalog.json").read_bytes(), "application/json; charset=utf-8", "public, max-age=60")) |
| 50 | if (directory / "stations.json").exists(): |
| 51 | files.append(("stations.json", (directory / "stations.json").read_bytes(), "application/json; charset=utf-8", "public, max-age=60")) |
| 52 | for name, data, content_type, cache in files: |
| 53 | stamp = datetime.now(timezone.utc) |
| 54 | date, moment = stamp.strftime("%Y%m%d"), stamp.strftime("%Y%m%dT%H%M%SZ") |
| 55 | path = "/" + quote(bucket + "/" + "/".join(filter(None, [prefix.strip("/"), name])), safe="/~") |
| 56 | digest = hashlib.sha256(data).hexdigest() |
| 57 | headers = {"cache-control": cache, "content-type": content_type, "host": host, |
| 58 | "x-amz-content-sha256": digest, "x-amz-date": moment} |
| 59 | signed = ";".join(sorted(headers)) |
| 60 | canonical_headers = "".join(key + ":" + headers[key] + "\n" for key in sorted(headers)) |
| 61 | request = "\n".join(["PUT", path, "", canonical_headers, signed, digest]) |
| 62 | scope = date + "/auto/s3/aws4_request" |
| 63 | message = "AWS4-HMAC-SHA256\n" + moment + "\n" + scope + "\n" + hashlib.sha256(request.encode()).hexdigest() |
| 64 | signing = ("AWS4" + secret).encode() |
| 65 | for part in [date, "auto", "s3", "aws4_request"]: |
| 66 | signing = hmac.new(signing, part.encode(), hashlib.sha256).digest() |
| 67 | signature = hmac.new(signing, message.encode(), hashlib.sha256).hexdigest() |
| 68 | headers["Authorization"] = f"AWS4-HMAC-SHA256 Credential={access}/{scope}, SignedHeaders={signed}, Signature={signature}" |
| 69 | with urlopen(Request("https://" + host + path, data=data, headers=headers, method="PUT"), timeout=120) as response: |
| 70 | if response.status not in [200, 201]: |
| 71 | raise SystemExit(f"Upload failed: HTTP {response.status}") |
| 72 | print("Uploaded " + name, flush=True) |
| 73 | print("Published catalog after all audio uploads completed.") |
| 74 | |
| 75 | |
| 76 | if __name__ == "__main__": |
| 77 | parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 78 | parser.add_argument("--library", default=Path("build/radio"), type=Path) |
| 79 | parser.add_argument("--prefix", default="") |
| 80 | args = parser.parse_args() |
| 81 | upload(args.library, args.prefix) |