|
| 1 | +"""Pure storage/validation helpers for chore images (#750). |
| 2 | +
|
| 3 | +Deliberately mirrors ``photos.py`` in shape but NOT in lifecycle. Evidence |
| 4 | +photos are transient artefacts of a completion and are orphan-swept at midnight |
| 5 | +by ``coordinator._async_sweep_orphan_photos``, whose referenced set is built |
| 6 | +only from completions. Chore images are configuration referenced by a chore, so |
| 7 | +they live in their own directory and are never swept — they are deleted |
| 8 | +explicitly when the chore is deleted or its image replaced. |
| 9 | +
|
| 10 | +Like ``photos.py`` this module has NO Home Assistant HTTP / aiohttp imports at |
| 11 | +module scope, so it can be imported from coordinator modules and unit-tested |
| 12 | +without a real HA install. The aiohttp views live in ``http_images.py``. |
| 13 | +
|
| 14 | +Images are stored as ``<32 hex>.<ext>`` under ``<config>/taskmate_images`` and |
| 15 | +served (auth-gated) at ``/api/taskmate/image/<name>``. |
| 16 | +""" |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import logging |
| 20 | +import re |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +from .photos import content_type_for, detect_image_ext |
| 24 | + |
| 25 | +_LOGGER = logging.getLogger(__name__) |
| 26 | + |
| 27 | +# Directory under the HA config dir (survives integration upgrades). |
| 28 | +IMAGES_DIR = "taskmate_images" |
| 29 | + |
| 30 | +# Public URL prefix for upload (POST) and serve (GET /<name>). |
| 31 | +URL_PREFIX = "/api/taskmate/image" |
| 32 | + |
| 33 | +# The panel downscales to 512px and re-encodes as JPEG before upload, so a real |
| 34 | +# chore image is a few tens of KB. This cap only catches abuse/bugs. |
| 35 | +MAX_UPLOAD_BYTES = 2 * 1024 * 1024 # 2 MB |
| 36 | + |
| 37 | +# Total disk budget for all stored chore images. |
| 38 | +MAX_TOTAL_BYTES = 64 * 1024 * 1024 # 64 MB |
| 39 | + |
| 40 | +# HEIC is deliberately absent: photos.py accepts it because a phone may upload |
| 41 | +# one directly, but a chore image is only ever *displayed*, and most browsers |
| 42 | +# cannot render HEIC — storing one produces a silently broken image. |
| 43 | +ALLOWED_EXTS = ("jpg", "png", "webp") |
| 44 | + |
| 45 | +FILENAME_RE = re.compile(r"^[0-9a-f]{32}\.(jpg|png|webp)$") |
| 46 | + |
| 47 | +# Re-exported so http_images.py has a single import site for its serve view. |
| 48 | +__all__ = [ |
| 49 | + "ALLOWED_EXTS", "FILENAME_RE", "IMAGES_DIR", "MAX_TOTAL_BYTES", |
| 50 | + "MAX_UPLOAD_BYTES", "URL_PREFIX", "async_delete_image", "content_type_for", |
| 51 | + "detect_allowed_ext", "image_file_for_url", "images_path", |
| 52 | + "is_taskmate_image_url", "sign_image_url", "total_images_bytes", |
| 53 | +] |
| 54 | + |
| 55 | + |
| 56 | +def detect_allowed_ext(data: bytes) -> str | None: |
| 57 | + """Sniff image magic bytes, narrowed to the browser-renderable formats.""" |
| 58 | + ext = detect_image_ext(data) |
| 59 | + return ext if ext in ALLOWED_EXTS else None |
| 60 | + |
| 61 | + |
| 62 | +def images_path(hass) -> Path: |
| 63 | + """Absolute path to the chore-images directory.""" |
| 64 | + return Path(hass.config.path(IMAGES_DIR)) |
| 65 | + |
| 66 | + |
| 67 | +def is_taskmate_image_url(image_url: str) -> bool: |
| 68 | + """True only for a well-formed ``/api/taskmate/image/<name>`` URL of ours. |
| 69 | +
|
| 70 | + Pure (no hass / no filesystem) so it can guard untrusted input at the |
| 71 | + websocket boundary. Rejects blanks, the evidence-photo prefix, foreign |
| 72 | + URLs, dangerous schemes and anything failing the strict filename pattern. |
| 73 | + """ |
| 74 | + if not image_url: |
| 75 | + return False |
| 76 | + prefix = URL_PREFIX + "/" |
| 77 | + if not image_url.startswith(prefix): |
| 78 | + return False |
| 79 | + return bool(FILENAME_RE.match(image_url[len(prefix):])) |
| 80 | + |
| 81 | + |
| 82 | +def image_file_for_url(hass, image_url: str) -> Path | None: |
| 83 | + """Map a ``/api/taskmate/image/<name>`` URL to its path, or None.""" |
| 84 | + if not is_taskmate_image_url(image_url): |
| 85 | + return None |
| 86 | + return images_path(hass) / image_url[len(URL_PREFIX) + 1:] |
| 87 | + |
| 88 | + |
| 89 | +def sign_image_url(hass, image_url: str, expiration_hours: int = 24) -> str: |
| 90 | + """Return a self-authenticating signed URL for one of our image URLs. |
| 91 | +
|
| 92 | + Browsers don't send the HA bearer token on plain ``<img>`` requests, so the |
| 93 | + auth-gated serve view 401s on a bare URL. Foreign/blank URLs pass through. |
| 94 | + The HA import is local so this module stays importable without a real HA. |
| 95 | + """ |
| 96 | + if not image_url or not image_url.startswith(URL_PREFIX + "/"): |
| 97 | + return image_url |
| 98 | + from datetime import timedelta |
| 99 | + |
| 100 | + try: |
| 101 | + from homeassistant.components.http.auth import async_sign_path |
| 102 | + |
| 103 | + return async_sign_path(hass, image_url, timedelta(hours=expiration_hours)) |
| 104 | + except Exception: # noqa: BLE001 - never break state delivery over a signing hiccup |
| 105 | + _LOGGER.debug("Could not sign image URL %s", image_url, exc_info=True) |
| 106 | + return image_url |
| 107 | + |
| 108 | + |
| 109 | +async def async_delete_image(hass, image_url: str) -> None: |
| 110 | + """Best-effort delete of the file backing an image URL. |
| 111 | +
|
| 112 | + No-op for foreign URLs (including evidence photos) or a missing file. |
| 113 | + """ |
| 114 | + path = image_file_for_url(hass, image_url) |
| 115 | + if path is None: |
| 116 | + return |
| 117 | + |
| 118 | + def _unlink() -> None: |
| 119 | + try: |
| 120 | + path.unlink() |
| 121 | + except FileNotFoundError: |
| 122 | + pass |
| 123 | + except OSError as err: # pragma: no cover - defensive |
| 124 | + _LOGGER.debug("Could not delete chore image %s: %s", path, err) |
| 125 | + |
| 126 | + await hass.async_add_executor_job(_unlink) |
| 127 | + |
| 128 | + |
| 129 | +def total_images_bytes(hass) -> int: |
| 130 | + """Sum of all stored chore-image file sizes (0 if the dir is absent).""" |
| 131 | + directory = images_path(hass) |
| 132 | + if not directory.is_dir(): |
| 133 | + return 0 |
| 134 | + total = 0 |
| 135 | + for p in directory.iterdir(): |
| 136 | + if p.is_file() and FILENAME_RE.match(p.name): |
| 137 | + try: |
| 138 | + total += p.stat().st_size |
| 139 | + except OSError: # pragma: no cover - defensive |
| 140 | + pass |
| 141 | + return total |
0 commit comments