#!/usr/bin/env python3 """ClearReadout from the command line. Needs Python 3.9 or later and nothing else. export CLEARREADOUT_KEY=YOUR_API_KEY python3 clearreadout.py me python3 clearreadout.py sites each site with its newest report_id python3 clearreadout.py check YOUR_SITE start a check, wait, print how it ended python3 clearreadout.py report REPORT_ID python3 clearreadout.py fixes REPORT_ID Exit code 0 when the check is done; 1 when it failed, expired or was turned down, with the reason on stderr. """ import json import os import sys import time import urllib.error import urllib.request BASE = os.environ.get("CLEARREADOUT_URL", "https://app.clearreadout.com").rstrip("/") class NoRedirects(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None # a redirect would carry the key to wherever it points def call(path, body=None): key = os.environ.get("CLEARREADOUT_KEY", "") if not key: sys.exit("Set CLEARREADOUT_KEY to your API key first.") if not BASE.startswith(("https://", "http://127.0.0.1")): sys.exit("CLEARREADOUT_URL must be https, so your key is not sent in the clear.") req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}) try: with urllib.request.build_opener(NoRedirects).open(req, timeout=60) as r: return r.read().decode() except urllib.error.HTTPError as e: sys.exit(f"{e.code}: {e.read().decode()[:500]}") except urllib.error.URLError as e: sys.exit(f"Could not reach ClearReadout: {e.reason}") def check(site): started = json.loads(call("/api/v1/checks", {"site": site})) while True: now = json.loads(call("/api/v1/checks/" + started["id"])) if now["state"] in ("done", "failed", "expired"): print(json.dumps(now, indent=2)) if now["state"] != "done": sys.exit("Check " + now["state"] + ": " + str(now.get("reason") or "it is too old to follow.")) sys.exit(0) time.sleep(5) def main(): a = sys.argv[1:] if not a or a[0] in ("-h", "--help"): print(__doc__) elif a == ["me"] or a == ["sites"]: print(call("/api/v1/" + a[0])) elif len(a) == 2 and a[0] == "check": check(a[1]) elif len(a) == 2 and a[0] == "report": print(call("/api/v1/reports/" + a[1])) elif len(a) == 2 and a[0] == "fixes": print(call(f"/api/v1/reports/{a[1]}/fixes.txt")) else: sys.exit(__doc__) if __name__ == "__main__": main()