#!/usr/bin/env python3 """Refresh Flounder's local MotionEye preview images.""" import os from pathlib import Path import sys import time from urllib.error import URLError from urllib.request import urlopen OUTPUTS = ( "front-door.jpg", "driveway.jpg", "garage.jpg", "bike-shed.jpg", "caravan.jpg", ) OUTPUT_DIR = Path(os.environ.get("HASS_CONFIG", "/config")) / "www/flounder" HASS_URL = os.environ.get("HASS_URL", "http://127.0.0.1:8123") def download(url_path: str, destination: Path) -> bool: url = f"{HASS_URL}{url_path}" for attempt in range(2): try: with urlopen(url, timeout=4) as response: image = response.read() if image.startswith(b"\xff\xd8") and image.endswith(b"\xff\xd9"): temporary = destination.with_suffix(".tmp") temporary.write_bytes(image) os.replace(temporary, destination) return True except (OSError, TimeoutError, URLError): pass if attempt == 0: time.sleep(2) return False def main() -> int: arguments = sys.argv[1:] outputs = OUTPUTS if arguments and arguments[0] == "--primary": arguments = arguments[1:] outputs = OUTPUTS[:3] if len(arguments) != len(outputs): return 2 OUTPUT_DIR.mkdir(parents=True, exist_ok=True) failures = 0 for url_path, filename in zip(arguments, outputs, strict=True): if not download(url_path, OUTPUT_DIR / filename): failures += 1 time.sleep(2) return 1 if failures else 0 if __name__ == "__main__": raise SystemExit(main())