Files
zenai-apc-ngoro/motioneye_client.py
2026-10-21 10:01:25 +07:00

123 lines
4.0 KiB
Python

"""HTTP client for MotionEye batch video ingest."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Optional
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
try:
import requests
except ImportError: # pragma: no cover
requests = None
def _ingest_url() -> str:
return os.getenv("MOTIONEYE_INGEST_URL", "http://192.168.192.251:8090").rstrip("/")
def _token() -> str:
return os.getenv("MOTIONEYE_INGEST_TOKEN", "change-me-ingest-token")
def batch_video_filename(batch_id: str) -> str:
return f"batch_{batch_id}.mp4"
def resolve_video_url(batch_id: str) -> str:
"""Canonical download URL served by the ingest service."""
return f"{_ingest_url()}/files/{batch_id}"
def upload_batch_video(local_path: str | Path, batch_id: str, timeout: float = 120.0) -> dict:
"""
Upload a finalized batch mp4 to MotionEye ingest.
Returns JSON dict with video_url on success. Raises on failure.
"""
path = Path(local_path)
if not path.is_file():
raise FileNotFoundError(str(path))
url = f"{_ingest_url()}/upload"
headers = {"X-Ingest-Token": _token()}
if requests is not None:
with path.open("rb") as fh:
resp = requests.post(
url,
headers=headers,
data={"batch_id": batch_id},
files={"file": (batch_video_filename(batch_id), fh, "video/mp4")},
timeout=timeout,
)
if resp.status_code >= 400:
raise RuntimeError(f"ingest HTTP {resp.status_code}: {resp.text[:300]}")
data = resp.json()
if not data.get("success"):
raise RuntimeError(data.get("error") or "upload failed")
return data
# Minimal fallback without requests (multipart is awkward; require requests)
raise RuntimeError("requests package required for motioneye upload")
def health_check(timeout: float = 5.0) -> bool:
url = f"{_ingest_url()}/health"
try:
if requests is not None:
r = requests.get(url, timeout=timeout)
return r.status_code == 200 and r.json().get("ok") is True
with urlopen(Request(url), timeout=timeout) as resp:
return resp.status == 200
except (URLError, HTTPError, OSError, ValueError):
return False
def file_exists(batch_id: str, timeout: float = 5.0) -> Optional[dict]:
url = f"{_ingest_url()}/files/{batch_id}?meta=1"
try:
if requests is not None:
r = requests.get(url, timeout=timeout)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json()
with urlopen(Request(url), timeout=timeout) as resp:
import json
return json.loads(resp.read().decode("utf-8"))
except Exception:
return None
def delete_batch_video(batch_id: str, timeout: float = 30.0) -> dict:
"""Delete a finalized batch mp4 from MotionEye ingest."""
url = f"{_ingest_url()}/files/{batch_id}"
headers = {"X-Ingest-Token": _token()}
if requests is not None:
resp = requests.delete(url, headers=headers, timeout=timeout)
if resp.status_code >= 400:
raise RuntimeError(f"ingest HTTP {resp.status_code}: {resp.text[:300]}")
data = resp.json()
if not data.get("success"):
raise RuntimeError(data.get("error") or "delete failed")
return data
req = Request(url, method="DELETE", headers=headers)
try:
with urlopen(req, timeout=timeout) as resp:
import json
data = json.loads(resp.read().decode("utf-8"))
if not data.get("success"):
raise RuntimeError(data.get("error") or "delete failed")
return data
except HTTPError as exc:
body = exc.read().decode("utf-8", errors="ignore")
raise RuntimeError(f"ingest HTTP {exc.code}: {body[:300]}") from exc
except URLError as exc:
raise RuntimeError(f"ingest URL error: {exc}") from exc