# coding=utf-8 """ Recuperation de la photo sur une machine distante (serveur HTTP de capture). Le serveur (par exemple un petit serveur Flask sur la machine qui porte la camera) expose : - /capture : prend une nouvelle photo et la renvoie (image/jpeg) ; - /old : renvoie la derniere photo prise, sans en prendre de nouvelle. Bibliotheque standard seulement (urllib), sans dependance a inkex. """ import http.client import socket from urllib.error import HTTPError, URLError from urllib.parse import urlsplit, urlunsplit from urllib.request import ProxyHandler, Request, build_opener DEFAULT_PORT = 5000 ENDPOINTS = {"capture": "/capture", "old": "/old"} MAX_BYTES = 64 * 1024 * 1024 # garde-fou : une photo ne depasse pas 64 Mo class RemoteError(Exception): """Echec de la recuperation ; `reason` est un code court, `detail` le message.""" def __init__(self, reason, detail=""): Exception.__init__(self, reason) self.reason = reason self.detail = detail def remote_url(host, port=DEFAULT_PORT, endpoint="capture"): """URL de la photo : accepte « 192.168.1.20 », « 192.168.1.20:5000 » ou une URL. Un port ecrit dans l'adresse l'emporte sur `port` ; le chemin eventuel de l'adresse est remplace par celui du point d'acces choisi. """ text = (host or "").strip() if not text: raise RemoteError("no_host") if endpoint not in ENDPOINTS: raise RemoteError("bad_endpoint", endpoint) if "://" not in text: if text.count(":") > 1 and not text.startswith("["): text = "[{}]".format(text) # IPv6 nue : « fe80::1 » text = "http://" + text parts = urlsplit(text) try: explicit_port = parts.port except ValueError: raise RemoteError("bad_host", host) hostname = parts.hostname if not hostname or parts.scheme not in ("http", "https"): raise RemoteError("bad_host", host) if ":" in hostname: # IPv6 : crochets obligatoires hostname = "[{}]".format(hostname) netloc = "{}:{}".format(hostname, explicit_port or int(port)) return urlunsplit((parts.scheme, netloc, ENDPOINTS[endpoint], "", "")) def _read_limited(response, chunk=256 * 1024): """Lit la reponse par blocs, jusqu'a MAX_BYTES + 1 octets au plus. Un read(MAX_BYTES + 1) allouerait d'emblee un tampon de 64 Mo : la lecture par blocs borne la memoire a la taille reelle de la photo. """ parts, total = [], 0 while total <= MAX_BYTES: block = response.read(chunk) if not block: break parts.append(block) total += len(block) return b"".join(parts) def _fetch_once(url, timeout): """Une tentative : ouverture (erreurs de connexion) puis lecture (coupures).""" opener = build_opener(ProxyHandler({})) request = Request(url, headers={"User-Agent": "Inkscape board_photo"}) try: response = opener.open(request, timeout=timeout) except HTTPError as error: # Le serveur explique l'echec dans le corps (« Error: Could not access # the camera ») : on le fait suivre a l'utilisateur. body = error.read(500).decode("utf-8", "replace").strip() raise RemoteError("http", "{} {}".format(error.code, body).strip()) except (socket.timeout, TimeoutError): raise RemoteError("timeout", url) except URLError as error: if isinstance(error.reason, (socket.timeout, TimeoutError)): raise RemoteError("timeout", url) raise RemoteError("unreachable", str(error.reason)) except OSError as error: raise RemoteError("unreachable", str(error)) # Connexion etablie : une erreur a partir d'ici est une transmission # interrompue (reseau instable, coupure), pas une machine injoignable. with response: content_type = response.headers.get_content_type() expected = response.headers.get("Content-Length") try: data = _read_limited(response) except (OSError, http.client.HTTPException) as error: raise RemoteError("interrupted", str(error) or type(error).__name__) if len(data) > MAX_BYTES: raise RemoteError("too_large", url) if expected and expected.isdigit() and len(data) < int(expected): raise RemoteError("interrupted", "{} / {}".format(len(data), expected)) if not content_type.startswith("image/"): text = data[:200].decode("utf-8", "replace").strip() raise RemoteError("not_image", text) return data def fetch_photo(url, timeout=20.0, retries=1): """Telecharge la photo ; renvoie ses octets ou leve RemoteError. Les proxys du systeme sont ignores : la camera est sur le reseau local, un proxy d'entreprise ne saurait pas la joindre. Une transmission interrompue est retentee `retries` fois ; les autres erreurs (machine injoignable, erreur du serveur) sont remontees tout de suite. """ for attempt in range(retries + 1): try: return _fetch_once(url, timeout) except RemoteError as error: if error.reason != "interrupted" or attempt == retries: raise