361 files
This commit is contained in:
@@ -516,16 +516,26 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
|
||||
_register_photo_services(hass)
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
# Reload when the options flow changes the entry (e.g. a new Immich
|
||||
# selection or the reverse-geocode toggle) so it takes effect at once.
|
||||
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
|
||||
|
||||
store.notify()
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
await hass.config_entries.async_reload(entry.entry_id)
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
if unload_ok:
|
||||
domain_data = hass.data.get(DOMAIN, {})
|
||||
coordinator = domain_data.get(entry.entry_id, {}).get("coordinator")
|
||||
if coordinator is not None:
|
||||
await coordinator._cancel_enrichment()
|
||||
domain_data.pop(entry.entry_id, None)
|
||||
# Drop the shared semaphore once the last album is gone so it's
|
||||
# re-created if the integration is re-added later.
|
||||
|
||||
@@ -5,6 +5,7 @@ from collections import OrderedDict, deque
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime, timezone
|
||||
import logging
|
||||
import math
|
||||
import random
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -20,6 +21,10 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
CAMERA_METADATA_FIELDS,
|
||||
DEFAULT_CUSTOM_LOOKBACK_DAYS,
|
||||
DEFAULT_SHUFFLE_AGE_BIAS,
|
||||
DEFAULT_MISSING_DATE_MODE,
|
||||
MAX_RESOLUTION_SHORT_EDGE,
|
||||
ORIENTATION_MISMATCH_PAIR,
|
||||
ORIENTATION_MISMATCH_AVOID,
|
||||
@@ -111,6 +116,41 @@ def _utc_now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _camera_metadata_attributes(item: MediaItem | None) -> dict[str, Any]:
|
||||
metadata = getattr(item, "camera_metadata", None)
|
||||
return {
|
||||
field: metadata.get(field) if isinstance(metadata, dict) else None
|
||||
for field in CAMERA_METADATA_FIELDS
|
||||
}
|
||||
|
||||
|
||||
def _item_faces(item: MediaItem | None) -> tuple[ip.FaceBox, ...] | None:
|
||||
"""Return the validated face boxes stored on a media item.
|
||||
|
||||
None means no face data; an empty tuple means the photo has no faces.
|
||||
"""
|
||||
faces = getattr(item, "faces", None) if item is not None else None
|
||||
if not isinstance(faces, (list, tuple)):
|
||||
return None
|
||||
valid: list[ip.FaceBox] = []
|
||||
for face in faces:
|
||||
if (
|
||||
not isinstance(face, (list, tuple))
|
||||
or len(face) not in (5, 6)
|
||||
or not all(
|
||||
not isinstance(value, bool) and isinstance(value, (int, float))
|
||||
and math.isfinite(value) for value in face[:5]
|
||||
)
|
||||
or (len(face) == 6 and not isinstance(face[5], bool))
|
||||
):
|
||||
continue
|
||||
left, top, right, bottom, weight = (float(value) for value in face[:5])
|
||||
if 0 <= left < right <= 1 and 0 <= top < bottom <= 1 and weight > 0:
|
||||
selected = face[5] if len(face) == 6 else False
|
||||
valid.append(ip.FaceBox(left, top, right, bottom, weight, selected))
|
||||
return tuple(valid)
|
||||
|
||||
|
||||
class _DownloadCache:
|
||||
"""Byte-budget LRU cache for downloaded image data, O(1) per operation."""
|
||||
|
||||
@@ -208,6 +248,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
self._frame_id: int = 0
|
||||
|
||||
self._interrupt_event: asyncio.Event = asyncio.Event()
|
||||
self._slide_deadline: float | None = None
|
||||
# Navigation runs directly in the button/service coroutine. The lock
|
||||
# serialises rapid presses while buffered swaps remain independent of
|
||||
# the background timer loop.
|
||||
@@ -244,6 +285,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
def _on_store_change() -> None:
|
||||
self._download_cache.resize(self.store.image_cache_mb * 1024 * 1024)
|
||||
self._effective_cache = None
|
||||
self._slide_deadline = None
|
||||
self._invalidate_timeline()
|
||||
|
||||
store.add_listener(_on_store_change)
|
||||
@@ -333,12 +375,14 @@ class AlbumSlideshowCamera(Camera):
|
||||
"captured_at_primary": captured_at,
|
||||
"uploaded_at": _ts_to_iso(getattr(cur, "uploaded_at", None)),
|
||||
"byte_size": getattr(cur, "byte_size", None),
|
||||
# GPS + reverse-geocoded label come from EXIF for local-folder
|
||||
# entries; Google albums leave these as ``None``.
|
||||
"latitude": getattr(cur, "latitude", None),
|
||||
"longitude": getattr(cur, "longitude", None),
|
||||
"location": getattr(cur, "location", None),
|
||||
"description": getattr(cur, "description", None),
|
||||
**_camera_metadata_attributes(cur),
|
||||
"google_metadata_enabled": bool(getattr(self.coordinator, "google_metadata_enabled", False)),
|
||||
"google_location_enabled": bool(getattr(self.coordinator, "google_location_enabled", False)),
|
||||
"google_reverse_geocode_enabled": bool(getattr(self.coordinator, "google_reverse_geocode_enabled", False)),
|
||||
# Structured per-image caption metadata. A single-element list for
|
||||
# normal slides; two elements (top/left first) for paired slides,
|
||||
# so the card can overlay an accurate date/location on each half.
|
||||
@@ -351,6 +395,8 @@ class AlbumSlideshowCamera(Camera):
|
||||
"portrait_mode": self.store.portrait_mode,
|
||||
"order_mode": self.store.order_mode,
|
||||
"date_filter": self.store.date_filter,
|
||||
"custom_lookback_days": int(self.store.custom_lookback_days),
|
||||
"shuffle_age_bias": int(self.store.shuffle_age_bias),
|
||||
"missing_date_mode": self.store.missing_date_mode,
|
||||
"paused": bool(self.store.paused),
|
||||
"refresh_hours": int(self.store.refresh_hours),
|
||||
@@ -393,6 +439,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
"latitude": getattr(cur, "latitude", None),
|
||||
"longitude": getattr(cur, "longitude", None),
|
||||
"description": getattr(cur, "description", None),
|
||||
**_camera_metadata_attributes(cur),
|
||||
}
|
||||
]
|
||||
|
||||
@@ -429,6 +476,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
cache_key = (
|
||||
id(raw),
|
||||
self.store.date_filter,
|
||||
getattr(self.store, "custom_lookback_days", DEFAULT_CUSTOM_LOOKBACK_DAYS),
|
||||
self.store.missing_date_mode,
|
||||
self.store.order_mode,
|
||||
self.store.hidden_revision,
|
||||
@@ -440,6 +488,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
[item for item in raw if item.photo_id and item.photo_id not in self.store.hidden_photo_ids]
|
||||
if self.store.hidden_photo_ids else raw,
|
||||
mode=self.store.date_filter,
|
||||
lookback_days=getattr(self.store, "custom_lookback_days", DEFAULT_CUSTOM_LOOKBACK_DAYS),
|
||||
missing_date=self.store.missing_date_mode,
|
||||
)
|
||||
ordered = playlist.order_items(filtered, self.store.order_mode)
|
||||
@@ -463,6 +512,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
self._last_nav_outcome = "pending"
|
||||
self._last_nav_error = None
|
||||
# Wake the timer loop so the manual frame starts a fresh interval.
|
||||
self._slide_deadline = None
|
||||
self._interrupt_event.set()
|
||||
self.async_write_ha_state()
|
||||
|
||||
@@ -492,6 +542,8 @@ class AlbumSlideshowCamera(Camera):
|
||||
)
|
||||
finally:
|
||||
self._navigation_pending -= 1
|
||||
self._slide_deadline = None
|
||||
self._interrupt_event.set()
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_force_refresh(self) -> None:
|
||||
@@ -1015,6 +1067,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
|
||||
async def _render_loop(self, initial_delay: float = 0.0) -> None:
|
||||
"""Display buffered frames on command/timer and refill them in the background."""
|
||||
loop = asyncio.get_running_loop()
|
||||
if initial_delay > 0:
|
||||
await asyncio.sleep(initial_delay)
|
||||
|
||||
@@ -1045,6 +1098,8 @@ class AlbumSlideshowCamera(Camera):
|
||||
|
||||
while True:
|
||||
try:
|
||||
if self._slide_deadline is None:
|
||||
self._slide_deadline = loop.time() + float(int(self.store.slide_interval))
|
||||
if self._timeline_dirty:
|
||||
async with self._navigation_lock:
|
||||
if self._timeline_dirty:
|
||||
@@ -1052,16 +1107,22 @@ class AlbumSlideshowCamera(Camera):
|
||||
continue
|
||||
|
||||
interrupted = await self._wait_or_interrupt(
|
||||
float(int(self.store.slide_interval))
|
||||
max(0.0, self._slide_deadline - loop.time())
|
||||
)
|
||||
if not interrupted and not self.store.paused:
|
||||
async with self._navigation_lock:
|
||||
if not self._timeline_dirty:
|
||||
if (
|
||||
not self._timeline_dirty
|
||||
and self._slide_deadline is not None
|
||||
and loop.time() >= self._slide_deadline
|
||||
):
|
||||
await self._show_next_frame()
|
||||
self._slide_deadline = loop.time() + float(int(self.store.slide_interval))
|
||||
self._consecutive_failures = 0
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as err:
|
||||
self._slide_deadline = None
|
||||
self._consecutive_failures += 1
|
||||
_LOGGER.warning(
|
||||
"Album Slideshow: buffered navigation/render failed (attempt %d): %s",
|
||||
@@ -1104,7 +1165,8 @@ class AlbumSlideshowCamera(Camera):
|
||||
self._index = (self._index + 1) % count
|
||||
return
|
||||
|
||||
self._index = self._next_random_index(count)
|
||||
bias = getattr(self.store, "shuffle_age_bias", DEFAULT_SHUFFLE_AGE_BIAS)
|
||||
self._index = self._next_age_weighted_index(items, bias) if bias else self._next_random_index(count)
|
||||
cur_url = items[self._index].url
|
||||
self._recent_urls.append(cur_url)
|
||||
keep = min(20, max(1, count - 1))
|
||||
@@ -1122,6 +1184,13 @@ class AlbumSlideshowCamera(Camera):
|
||||
return
|
||||
self._index = (self._index + 1) % count
|
||||
|
||||
def _crop_hints(self, item: MediaItem | None) -> ip.CropHints:
|
||||
return ip.CropHints(
|
||||
faces=_item_faces(item),
|
||||
debug=bool(getattr(getattr(self, "store", None), "face_debug", False)),
|
||||
name=getattr(item, "filename", None),
|
||||
)
|
||||
|
||||
async def _compose_for_index(
|
||||
self, items: list[MediaItem]
|
||||
) -> tuple[Image.Image | None, dict | None]:
|
||||
@@ -1183,6 +1252,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
composed = await self._async_image_job(
|
||||
ip.pair_images, img, other_img, width, height, fill_mode,
|
||||
is_portrait_canvas, divider, divider_fill, transparent_divider,
|
||||
self._crop_hints(cur), self._crop_hints(other_item),
|
||||
)
|
||||
pair_frames = [
|
||||
{
|
||||
@@ -1191,6 +1261,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
"latitude": getattr(cur, "latitude", None),
|
||||
"longitude": getattr(cur, "longitude", None),
|
||||
"description": getattr(cur, "description", None),
|
||||
**_camera_metadata_attributes(cur),
|
||||
},
|
||||
{
|
||||
"captured_at": _ts_to_iso(getattr(other_item, "captured_at", None)),
|
||||
@@ -1198,12 +1269,13 @@ class AlbumSlideshowCamera(Camera):
|
||||
"latitude": getattr(other_item, "latitude", None),
|
||||
"longitude": getattr(other_item, "longitude", None),
|
||||
"description": getattr(other_item, "description", None),
|
||||
**_camera_metadata_attributes(other_item),
|
||||
},
|
||||
]
|
||||
pair_meta = [f["captured_at"] for f in pair_frames]
|
||||
else:
|
||||
composed = await self._async_image_job(
|
||||
ip.render_image, img, fill_mode, width, height,
|
||||
ip.render_image, img, fill_mode, width, height, self._crop_hints(cur),
|
||||
)
|
||||
finally:
|
||||
ip.safe_close(other_img)
|
||||
@@ -1226,7 +1298,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
return composed, meta
|
||||
|
||||
composed = await self._async_image_job(
|
||||
ip.render_image, img, fill_mode, width, height
|
||||
ip.render_image, img, fill_mode, width, height, self._crop_hints(cur)
|
||||
)
|
||||
return composed, {
|
||||
"is_portrait": cur_is_portrait,
|
||||
@@ -1278,7 +1350,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
if self._index != start:
|
||||
self._do_advance(count, items)
|
||||
composed = await self._async_image_job(
|
||||
ip.render_image, img, fill_mode, width, height
|
||||
ip.render_image, img, fill_mode, width, height, self._crop_hints(cur)
|
||||
)
|
||||
return composed, {
|
||||
"is_portrait": is_portrait_canvas,
|
||||
@@ -1304,7 +1376,7 @@ class AlbumSlideshowCamera(Camera):
|
||||
try:
|
||||
cur_is_portrait = ip.is_portrait_item(item, img)
|
||||
composed = await self._async_image_job(
|
||||
ip.render_image, img, fill_mode, width, height
|
||||
ip.render_image, img, fill_mode, width, height, self._crop_hints(item)
|
||||
)
|
||||
return composed, {
|
||||
"is_portrait": cur_is_portrait,
|
||||
@@ -1407,6 +1479,23 @@ class AlbumSlideshowCamera(Camera):
|
||||
|
||||
return None
|
||||
|
||||
def _next_age_weighted_index(self, items: list[MediaItem], bias: int) -> int:
|
||||
weights = playlist.age_weights(
|
||||
items, bias, missing_date=getattr(self.store, "missing_date_mode", DEFAULT_MISSING_DATE_MODE),
|
||||
)
|
||||
count = len(items)
|
||||
if count <= 1 or min(weights) == max(weights):
|
||||
return self._next_random_index(count)
|
||||
cooldown = min(5, max(1, count // 10))
|
||||
recent = set(self._recent_urls[-cooldown:])
|
||||
candidates = [
|
||||
index for index, item in enumerate(items)
|
||||
if index != self._index and item.url not in recent
|
||||
]
|
||||
if not candidates:
|
||||
candidates = [index for index in range(count) if index != self._index]
|
||||
return self._rng.choices(candidates, weights=[weights[index] for index in candidates], k=1)[0]
|
||||
|
||||
def _next_random_index(self, count: int) -> int:
|
||||
if count <= 1:
|
||||
self._random_order = [0]
|
||||
|
||||
@@ -20,6 +20,11 @@ from .const import (
|
||||
CONF_PROVIDER,
|
||||
CONF_ALBUM_NAME,
|
||||
CONF_ALBUM_URL,
|
||||
CONF_GOOGLE_METADATA,
|
||||
DEFAULT_GOOGLE_METADATA,
|
||||
CONF_GOOGLE_LOCATION,
|
||||
DEFAULT_GOOGLE_LOCATION,
|
||||
DEFAULT_GOOGLE_REVERSE_GEOCODE,
|
||||
CONF_LOCAL_PATH,
|
||||
CONF_MEDIA_CONTENT_ID,
|
||||
CONF_RECURSIVE,
|
||||
@@ -149,6 +154,193 @@ def _redact_token(token: str | None) -> str:
|
||||
return f"{token[:3]}...({len(token)} chars, shape {shape})"
|
||||
|
||||
|
||||
async def _fetch_immich_choices(
|
||||
client: Any,
|
||||
) -> tuple[dict[str, str], dict[str, str]]:
|
||||
"""Return id -> name maps of the albums and named people a key can see.
|
||||
|
||||
A key with limited permissions can read the server but not albums or
|
||||
people; keep going with whatever it can see.
|
||||
"""
|
||||
albums: list[dict[str, Any]] = []
|
||||
people: list[dict[str, Any]] = []
|
||||
for label, call in (
|
||||
("albums", client.async_list_albums),
|
||||
("people", client.async_list_people),
|
||||
):
|
||||
try:
|
||||
result = await call()
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
"Immich %s listing failed for %s: %s",
|
||||
label,
|
||||
client.base_url,
|
||||
_describe_error(err),
|
||||
)
|
||||
else:
|
||||
if label == "albums":
|
||||
albums = result
|
||||
else:
|
||||
people = result
|
||||
album_map = {
|
||||
a["id"]: (a.get("albumName") or a["id"]) for a in albums if a.get("id")
|
||||
}
|
||||
people_map = {
|
||||
p["id"]: p["name"]
|
||||
for p in people
|
||||
if p.get("id") and (p.get("name") or "").strip()
|
||||
}
|
||||
return album_map, people_map
|
||||
|
||||
|
||||
def _immich_validation_error(err: BaseException) -> str:
|
||||
return (
|
||||
"immich_invalid_auth"
|
||||
if getattr(err, "status", None) in (401, 403)
|
||||
else "immich_cannot_connect"
|
||||
)
|
||||
|
||||
|
||||
def _immich_select_schema(
|
||||
albums: dict[str, str],
|
||||
people: dict[str, str],
|
||||
defaults: dict[str, Any] | None = None,
|
||||
) -> vol.Schema:
|
||||
"""Build the albums/people/favorites picker, optionally pre-filled."""
|
||||
defaults = defaults or {}
|
||||
|
||||
def _default(key: str, fallback: Any = vol.UNDEFINED) -> Any:
|
||||
return defaults.get(key, fallback)
|
||||
|
||||
fields: dict[Any, Any] = {
|
||||
vol.Required(CONF_ALBUM_NAME, default=_default(CONF_ALBUM_NAME)): str
|
||||
}
|
||||
if albums:
|
||||
album_options = [
|
||||
selector.SelectOptionDict(value=_ALL_ALBUMS, label="Select all albums")
|
||||
] + [
|
||||
selector.SelectOptionDict(value=aid, label=name)
|
||||
for aid, name in albums.items()
|
||||
]
|
||||
fields[vol.Optional("albums", default=_default("albums"))] = (
|
||||
selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=album_options,
|
||||
multiple=True,
|
||||
mode=selector.SelectSelectorMode.DROPDOWN,
|
||||
custom_value=False,
|
||||
)
|
||||
)
|
||||
)
|
||||
if people:
|
||||
people_options = [
|
||||
selector.SelectOptionDict(value=_ALL_PEOPLE, label="Select all people")
|
||||
] + [
|
||||
selector.SelectOptionDict(value=pid, label=name)
|
||||
for pid, name in people.items()
|
||||
]
|
||||
fields[vol.Optional("people", default=_default("people"))] = (
|
||||
selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=people_options,
|
||||
multiple=True,
|
||||
mode=selector.SelectSelectorMode.DROPDOWN,
|
||||
custom_value=False,
|
||||
)
|
||||
)
|
||||
)
|
||||
fields[vol.Optional("favorites", default=_default("favorites", False))] = (
|
||||
selector.BooleanSelector()
|
||||
)
|
||||
filter_default = _default(CONF_IMMICH_FILTER)
|
||||
fields[
|
||||
vol.Optional(
|
||||
CONF_IMMICH_FILTER,
|
||||
description=(
|
||||
{"suggested_value": filter_default}
|
||||
if filter_default is not vol.UNDEFINED
|
||||
else None
|
||||
),
|
||||
)
|
||||
] = str
|
||||
fields[
|
||||
vol.Optional(
|
||||
CONF_IMMICH_IMAGE_SIZE,
|
||||
default=_default(CONF_IMMICH_IMAGE_SIZE, DEFAULT_IMMICH_IMAGE_SIZE),
|
||||
)
|
||||
] = vol.In(IMMICH_IMAGE_SIZE_OPTIONS)
|
||||
return vol.Schema(fields)
|
||||
|
||||
|
||||
def _parse_immich_select(
|
||||
user_input: dict[str, Any],
|
||||
albums: dict[str, str],
|
||||
people: dict[str, str],
|
||||
) -> tuple[dict[str, Any], dict[str, str]]:
|
||||
"""Turn picker input into entry data fields; return ``(fields, errors)``."""
|
||||
errors: dict[str, str] = {}
|
||||
name = user_input[CONF_ALBUM_NAME].strip()
|
||||
size = user_input.get(CONF_IMMICH_IMAGE_SIZE, DEFAULT_IMMICH_IMAGE_SIZE)
|
||||
raw_filter = (user_input.get(CONF_IMMICH_FILTER) or "").strip()
|
||||
favorites = bool(user_input.get("favorites"))
|
||||
|
||||
chosen_albums = [a for a in user_input.get("albums", []) if a]
|
||||
if _ALL_ALBUMS in chosen_albums:
|
||||
chosen_albums = list(albums.keys())
|
||||
else:
|
||||
chosen_albums = [a for a in chosen_albums if a in albums]
|
||||
|
||||
chosen_people = [p for p in user_input.get("people", []) if p]
|
||||
if _ALL_PEOPLE in chosen_people:
|
||||
chosen_people = list(people.keys())
|
||||
else:
|
||||
chosen_people = [p for p in chosen_people if p in people]
|
||||
|
||||
if raw_filter:
|
||||
try:
|
||||
parsed = json.loads(raw_filter)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
errors[CONF_IMMICH_FILTER] = "immich_filter_invalid"
|
||||
|
||||
selection = {
|
||||
"albums": chosen_albums,
|
||||
"people": chosen_people,
|
||||
"favorites": favorites,
|
||||
}
|
||||
fields = {
|
||||
CONF_IMMICH_SELECTION_TYPE: IMMICH_SELECTION_COMPOSITE,
|
||||
CONF_IMMICH_SELECTION_ID: json.dumps(selection, sort_keys=True),
|
||||
CONF_IMMICH_IMAGE_SIZE: size,
|
||||
CONF_ALBUM_NAME: name,
|
||||
CONF_IMMICH_FILTER: raw_filter,
|
||||
}
|
||||
return fields, errors
|
||||
|
||||
|
||||
def _immich_current_selection(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Map an entry's stored Immich selection onto the picker's fields.
|
||||
|
||||
Composite entries map one to one. Older single-type entries are
|
||||
translated where the picker can express them (albums, people,
|
||||
favorites); ``all``/``random``/``search`` start with nothing ticked,
|
||||
which the picker saves as "all photos" (plus any stored filter).
|
||||
"""
|
||||
from . import immich as immich_api
|
||||
|
||||
sel_type = data.get(CONF_IMMICH_SELECTION_TYPE)
|
||||
sel_id = data.get(CONF_IMMICH_SELECTION_ID) or ""
|
||||
if sel_type == IMMICH_SELECTION_COMPOSITE:
|
||||
return immich_api.parse_composite_selection(sel_id)
|
||||
ids = [part for part in sel_id.split(",") if part]
|
||||
return {
|
||||
"albums": ids if sel_type in ("album", "albums") else [],
|
||||
"people": ids if sel_type in ("person", "people") else [],
|
||||
"favorites": sel_type == "favorites",
|
||||
}
|
||||
|
||||
|
||||
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
VERSION = 1
|
||||
|
||||
@@ -190,9 +382,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
) -> config_entries.OptionsFlow:
|
||||
"""Return the options flow handler.
|
||||
|
||||
Only local-folder entries expose user-tunable options today (the
|
||||
reverse-geocode toggle); Google entries get a no-op handler so
|
||||
that the "Configure" button doesn't appear empty in the UI.
|
||||
Local-folder, Nextcloud and Ente entries expose the reverse-geocode
|
||||
toggle; Immich entries reopen the albums/people/favorites picker.
|
||||
Other providers get a no-op handler so that the "Configure" button
|
||||
doesn't appear empty in the UI.
|
||||
|
||||
Note: do NOT pass ``config_entry`` to the OptionsFlow constructor.
|
||||
Since Home Assistant 2024.12 the base class manages
|
||||
@@ -206,6 +399,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
PROVIDER_ENTE,
|
||||
):
|
||||
return LocalFolderOptionsFlow()
|
||||
if config_entry.data.get(CONF_PROVIDER) == PROVIDER_IMMICH:
|
||||
return ImmichOptionsFlow()
|
||||
if config_entry.data.get(CONF_PROVIDER) == PROVIDER_GOOGLE_SHARED:
|
||||
return GoogleOptionsFlow()
|
||||
return _NoOptionsFlow()
|
||||
|
||||
async def async_step_user(self, user_input: dict[str, Any] | None = None) -> FlowResult:
|
||||
@@ -354,8 +551,6 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
from . import immich as immich_api
|
||||
|
||||
client = immich_api.ImmichClient(self.hass, url, key)
|
||||
albums: list[dict[str, Any]] = []
|
||||
people: list[dict[str, Any]] = []
|
||||
try:
|
||||
await client.async_validate()
|
||||
except Exception as err: # noqa: BLE001 - any failure means bad URL/key
|
||||
@@ -364,46 +559,14 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
client.base_url,
|
||||
_describe_error(err),
|
||||
)
|
||||
errors["base"] = (
|
||||
"immich_invalid_auth"
|
||||
if getattr(err, "status", None) in (401, 403)
|
||||
else "immich_cannot_connect"
|
||||
)
|
||||
errors["base"] = _immich_validation_error(err)
|
||||
else:
|
||||
# A key with limited permissions can read the server but not
|
||||
# albums or people; keep going with whatever it can see.
|
||||
for label, call in (
|
||||
("albums", client.async_list_albums),
|
||||
("people", client.async_list_people),
|
||||
):
|
||||
try:
|
||||
result = await call()
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
"Immich %s listing failed for %s: %s",
|
||||
label,
|
||||
client.base_url,
|
||||
_describe_error(err),
|
||||
)
|
||||
else:
|
||||
if label == "albums":
|
||||
albums = result
|
||||
else:
|
||||
people = result
|
||||
|
||||
self._immich_url = client.base_url
|
||||
self._immich_key = key
|
||||
# id -> name maps for the two multi-select pickers.
|
||||
self._immich_albums = {
|
||||
a["id"]: (a.get("albumName") or a["id"])
|
||||
for a in albums
|
||||
if a.get("id")
|
||||
}
|
||||
self._immich_people = {
|
||||
p["id"]: p["name"]
|
||||
for p in people
|
||||
if p.get("id") and (p.get("name") or "").strip()
|
||||
}
|
||||
(
|
||||
self._immich_albums,
|
||||
self._immich_people,
|
||||
) = await _fetch_immich_choices(client)
|
||||
return await self.async_step_immich_select()
|
||||
|
||||
schema = vol.Schema(
|
||||
@@ -428,41 +591,15 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
name = user_input[CONF_ALBUM_NAME].strip()
|
||||
size = user_input.get(CONF_IMMICH_IMAGE_SIZE, DEFAULT_IMMICH_IMAGE_SIZE)
|
||||
raw_filter = (user_input.get(CONF_IMMICH_FILTER) or "").strip()
|
||||
favorites = bool(user_input.get("favorites"))
|
||||
|
||||
chosen_albums = [a for a in user_input.get("albums", []) if a]
|
||||
if _ALL_ALBUMS in chosen_albums:
|
||||
chosen_albums = list(self._immich_albums.keys())
|
||||
else:
|
||||
chosen_albums = [a for a in chosen_albums if a in self._immich_albums]
|
||||
|
||||
chosen_people = [p for p in user_input.get("people", []) if p]
|
||||
if _ALL_PEOPLE in chosen_people:
|
||||
chosen_people = list(self._immich_people.keys())
|
||||
else:
|
||||
chosen_people = [p for p in chosen_people if p in self._immich_people]
|
||||
|
||||
if raw_filter:
|
||||
try:
|
||||
parsed = json.loads(raw_filter)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
errors[CONF_IMMICH_FILTER] = "immich_filter_invalid"
|
||||
|
||||
fields, errors = _parse_immich_select(
|
||||
user_input, self._immich_albums, self._immich_people
|
||||
)
|
||||
if not errors:
|
||||
selection = {
|
||||
"albums": chosen_albums,
|
||||
"people": chosen_people,
|
||||
"favorites": favorites,
|
||||
}
|
||||
sel_id = json.dumps(selection, sort_keys=True)
|
||||
name = fields[CONF_ALBUM_NAME]
|
||||
raw_filter = fields.pop(CONF_IMMICH_FILTER)
|
||||
unique = (
|
||||
f"{DOMAIN}:{PROVIDER_IMMICH}:{self._immich_url}:"
|
||||
f"composite:{sel_id}:{raw_filter}:{name}"
|
||||
f"composite:{fields[CONF_IMMICH_SELECTION_ID]}:{raw_filter}:{name}"
|
||||
)
|
||||
await self.async_set_unique_id(unique)
|
||||
self._abort_if_unique_id_configured()
|
||||
@@ -470,58 +607,18 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
CONF_PROVIDER: PROVIDER_IMMICH,
|
||||
CONF_IMMICH_URL: self._immich_url,
|
||||
CONF_IMMICH_API_KEY: self._immich_key,
|
||||
CONF_IMMICH_SELECTION_TYPE: IMMICH_SELECTION_COMPOSITE,
|
||||
CONF_IMMICH_SELECTION_ID: sel_id,
|
||||
CONF_IMMICH_IMAGE_SIZE: size,
|
||||
CONF_ALBUM_NAME: name,
|
||||
**fields,
|
||||
}
|
||||
if raw_filter:
|
||||
data[CONF_IMMICH_FILTER] = raw_filter
|
||||
return self.async_create_entry(title=name, data=data)
|
||||
|
||||
fields: dict[Any, Any] = {vol.Required(CONF_ALBUM_NAME): str}
|
||||
if self._immich_albums:
|
||||
album_options = [
|
||||
selector.SelectOptionDict(
|
||||
value=_ALL_ALBUMS, label="Select all albums"
|
||||
)
|
||||
] + [
|
||||
selector.SelectOptionDict(value=aid, label=name)
|
||||
for aid, name in self._immich_albums.items()
|
||||
]
|
||||
fields[vol.Optional("albums")] = selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=album_options,
|
||||
multiple=True,
|
||||
mode=selector.SelectSelectorMode.DROPDOWN,
|
||||
custom_value=False,
|
||||
)
|
||||
)
|
||||
if self._immich_people:
|
||||
people_options = [
|
||||
selector.SelectOptionDict(
|
||||
value=_ALL_PEOPLE, label="Select all people"
|
||||
)
|
||||
] + [
|
||||
selector.SelectOptionDict(value=pid, label=name)
|
||||
for pid, name in self._immich_people.items()
|
||||
]
|
||||
fields[vol.Optional("people")] = selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=people_options,
|
||||
multiple=True,
|
||||
mode=selector.SelectSelectorMode.DROPDOWN,
|
||||
custom_value=False,
|
||||
)
|
||||
)
|
||||
fields[vol.Optional("favorites", default=False)] = selector.BooleanSelector()
|
||||
fields[vol.Optional(CONF_IMMICH_FILTER)] = str
|
||||
fields[
|
||||
vol.Optional(CONF_IMMICH_IMAGE_SIZE, default=DEFAULT_IMMICH_IMAGE_SIZE)
|
||||
] = vol.In(IMMICH_IMAGE_SIZE_OPTIONS)
|
||||
schema = vol.Schema(fields)
|
||||
return self.async_show_form(
|
||||
step_id="immich_select", data_schema=schema, errors=errors
|
||||
step_id="immich_select",
|
||||
data_schema=_immich_select_schema(
|
||||
self._immich_albums, self._immich_people
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def async_step_photoprism(
|
||||
@@ -1263,6 +1360,38 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
|
||||
|
||||
class GoogleOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Control anonymous Google photo metadata enrichment."""
|
||||
|
||||
async def async_step_init(self, user_input: dict[str, Any] | None = None) -> FlowResult:
|
||||
return await self.async_step_google_metadata(user_input)
|
||||
|
||||
async def async_step_google_metadata(
|
||||
self, user_input: dict[str, Any] | None = None,
|
||||
) -> FlowResult:
|
||||
defaults = {
|
||||
CONF_GOOGLE_METADATA: DEFAULT_GOOGLE_METADATA,
|
||||
CONF_GOOGLE_LOCATION: DEFAULT_GOOGLE_LOCATION,
|
||||
CONF_REVERSE_GEOCODE: DEFAULT_GOOGLE_REVERSE_GEOCODE,
|
||||
}
|
||||
if user_input is not None:
|
||||
options = {
|
||||
**self.config_entry.options,
|
||||
**{
|
||||
field: bool(user_input.get(field, self.config_entry.options.get(field, default)))
|
||||
for field, default in defaults.items()
|
||||
},
|
||||
}
|
||||
return self.async_create_entry(title="", data=options)
|
||||
return self.async_show_form(
|
||||
step_id="google_metadata",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(field, default=bool(self.config_entry.options.get(field, default))): bool
|
||||
for field, default in defaults.items()
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
class LocalFolderOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Options for local-folder entries.
|
||||
|
||||
@@ -1295,6 +1424,184 @@ class LocalFolderOptionsFlow(config_entries.OptionsFlow):
|
||||
return self.async_show_form(step_id="init", data_schema=schema)
|
||||
|
||||
|
||||
class ImmichOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Change an Immich entry's source without re-creating the entry.
|
||||
|
||||
The selection lives in ``entry.data`` (the coordinator reads it from
|
||||
there), so this flow writes the new selection back into the entry data;
|
||||
the update listener then reloads the entry. The entry id is unchanged,
|
||||
so entities, their settings and the hidden-photo list are kept.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self._albums: dict[str, str] = {}
|
||||
self._people: dict[str, str] = {}
|
||||
self._url: str | None = None
|
||||
self._key: str | None = None
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> FlowResult:
|
||||
from . import immich as immich_api
|
||||
|
||||
data = self.config_entry.data
|
||||
client = immich_api.ImmichClient(
|
||||
self.hass, data.get(CONF_IMMICH_URL), data.get(CONF_IMMICH_API_KEY)
|
||||
)
|
||||
try:
|
||||
await client.async_validate()
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
"Immich validation failed for %s: %s",
|
||||
client.base_url,
|
||||
_describe_error(err),
|
||||
)
|
||||
return await self.async_step_connection(
|
||||
errors={"base": _immich_validation_error(err)}
|
||||
)
|
||||
self._url = client.base_url
|
||||
self._key = data.get(CONF_IMMICH_API_KEY)
|
||||
self._albums, self._people = await _fetch_immich_choices(client)
|
||||
return await self.async_step_immich_select()
|
||||
|
||||
async def async_step_connection(
|
||||
self,
|
||||
user_input: dict[str, Any] | None = None,
|
||||
errors: dict[str, str] | None = None,
|
||||
) -> FlowResult:
|
||||
"""Fix the URL or API key when the stored ones stop working."""
|
||||
from . import immich as immich_api
|
||||
|
||||
errors = dict(errors or {})
|
||||
data = self.config_entry.data
|
||||
if user_input is not None:
|
||||
url = user_input[CONF_IMMICH_URL].strip()
|
||||
key = user_input[CONF_IMMICH_API_KEY].strip()
|
||||
client = immich_api.ImmichClient(self.hass, url, key)
|
||||
try:
|
||||
await client.async_validate()
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
"Immich validation failed for %s: %s",
|
||||
client.base_url,
|
||||
_describe_error(err),
|
||||
)
|
||||
errors["base"] = _immich_validation_error(err)
|
||||
else:
|
||||
self._url = client.base_url
|
||||
self._key = key
|
||||
self._albums, self._people = await _fetch_immich_choices(client)
|
||||
return await self.async_step_immich_select()
|
||||
|
||||
schema = vol.Schema(
|
||||
{
|
||||
vol.Required(
|
||||
CONF_IMMICH_URL, default=data.get(CONF_IMMICH_URL, "")
|
||||
): str,
|
||||
vol.Required(
|
||||
CONF_IMMICH_API_KEY, default=data.get(CONF_IMMICH_API_KEY, "")
|
||||
): str,
|
||||
}
|
||||
)
|
||||
return self.async_show_form(
|
||||
step_id="connection", data_schema=schema, errors=errors
|
||||
)
|
||||
|
||||
async def async_step_immich_select(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> FlowResult:
|
||||
entry = self.config_entry
|
||||
errors: dict[str, str] = {}
|
||||
current = _immich_current_selection(entry.data)
|
||||
for album_id in current["albums"]:
|
||||
self._albums.setdefault(album_id, f"{album_id} (unavailable)")
|
||||
for person_id in current["people"]:
|
||||
self._people.setdefault(person_id, f"{person_id} (unavailable)")
|
||||
|
||||
if user_input is not None:
|
||||
fields, errors = _parse_immich_select(
|
||||
user_input, self._albums, self._people
|
||||
)
|
||||
if not errors:
|
||||
new_data = {
|
||||
**entry.data,
|
||||
**fields,
|
||||
CONF_IMMICH_URL: self._url,
|
||||
CONF_IMMICH_API_KEY: self._key,
|
||||
}
|
||||
if not new_data[CONF_IMMICH_FILTER]:
|
||||
new_data.pop(CONF_IMMICH_FILTER)
|
||||
try:
|
||||
if _immich_source_changed(entry.data, new_data):
|
||||
await _async_clear_item_cache(self.hass, entry.entry_id)
|
||||
except Exception as err:
|
||||
_LOGGER.warning(
|
||||
"Could not clear Immich source cache for %s (%s)",
|
||||
entry.entry_id, type(err).__name__,
|
||||
)
|
||||
errors["base"] = "immich_cache_clear_failed"
|
||||
else:
|
||||
options = {
|
||||
**entry.options,
|
||||
CONF_REVERSE_GEOCODE: user_input.get(
|
||||
CONF_REVERSE_GEOCODE,
|
||||
entry.options.get(CONF_REVERSE_GEOCODE, DEFAULT_REVERSE_GEOCODE),
|
||||
),
|
||||
}
|
||||
self.hass.config_entries.async_update_entry(
|
||||
entry, data=new_data, title=fields[CONF_ALBUM_NAME], options=options
|
||||
)
|
||||
return self.async_create_entry(title="", data=options)
|
||||
|
||||
defaults = {
|
||||
CONF_ALBUM_NAME: entry.data.get(CONF_ALBUM_NAME) or entry.title,
|
||||
"albums": current["albums"],
|
||||
"people": current["people"],
|
||||
"favorites": current["favorites"],
|
||||
CONF_IMMICH_IMAGE_SIZE: entry.data.get(
|
||||
CONF_IMMICH_IMAGE_SIZE, DEFAULT_IMMICH_IMAGE_SIZE
|
||||
),
|
||||
}
|
||||
if entry.data.get(CONF_IMMICH_FILTER):
|
||||
defaults[CONF_IMMICH_FILTER] = entry.data[CONF_IMMICH_FILTER]
|
||||
schema = _immich_select_schema(self._albums, self._people, defaults).extend({
|
||||
vol.Required(CONF_REVERSE_GEOCODE, default=bool(entry.options.get(
|
||||
CONF_REVERSE_GEOCODE, DEFAULT_REVERSE_GEOCODE,
|
||||
))): bool,
|
||||
})
|
||||
return self.async_show_form(
|
||||
step_id="immich_select",
|
||||
data_schema=schema,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
def _immich_source_changed(old: dict[str, Any], new: dict[str, Any]) -> bool:
|
||||
"""True when the set of photos an Immich entry shows may have changed."""
|
||||
keys = (
|
||||
CONF_IMMICH_URL,
|
||||
CONF_IMMICH_API_KEY,
|
||||
CONF_IMMICH_SELECTION_TYPE,
|
||||
CONF_IMMICH_SELECTION_ID,
|
||||
CONF_IMMICH_FILTER,
|
||||
CONF_IMMICH_IMAGE_SIZE,
|
||||
)
|
||||
return any(old.get(key) != new.get(key) for key in keys)
|
||||
|
||||
|
||||
async def _async_clear_item_cache(hass: Any, entry_id: str) -> None:
|
||||
"""Drop the persisted item list so a new source never shows old photos.
|
||||
|
||||
The coordinator serves this cache when a refresh fails or comes back
|
||||
empty; after a source change that would resurrect the previous album.
|
||||
Uses the same storage key as ``AlbumCoordinator._items_cache_store``.
|
||||
"""
|
||||
from homeassistant.helpers.storage import Store
|
||||
|
||||
await Store(hass, 1, f"{DOMAIN}.{entry_id}.items").async_remove()
|
||||
|
||||
|
||||
class _NoOptionsFlow(config_entries.OptionsFlow):
|
||||
"""Fallback options flow for providers that expose nothing tunable."""
|
||||
|
||||
|
||||
@@ -12,6 +12,15 @@ CONF_ALBUM_NAME = "album_name"
|
||||
CONF_LOCAL_PATH = "local_path"
|
||||
CONF_RECURSIVE = "recursive"
|
||||
CONF_IMAGE_CACHE_MB = "image_cache_mb"
|
||||
CONF_GOOGLE_METADATA = "google_metadata"
|
||||
DEFAULT_GOOGLE_METADATA = True
|
||||
CONF_GOOGLE_LOCATION = "google_location"
|
||||
DEFAULT_GOOGLE_LOCATION = False
|
||||
DEFAULT_GOOGLE_REVERSE_GEOCODE = False
|
||||
CAMERA_METADATA_FIELDS = (
|
||||
"camera_make", "camera_model", "focal_length_mm", "aperture_f_number",
|
||||
"iso", "exposure_time_seconds",
|
||||
)
|
||||
# Media Source provider: a ``media-source://...`` content id pointing at a
|
||||
# folder-like node (e.g. an Immich people/album view, or local media). The
|
||||
# coordinator browses it, collects the image children, and resolves each to
|
||||
@@ -258,6 +267,9 @@ DATE_FILTER_OFF = "off"
|
||||
DATE_FILTER_LAST_7 = "last_7_days"
|
||||
DATE_FILTER_LAST_30 = "last_30_days"
|
||||
DATE_FILTER_LAST_365 = "last_365_days"
|
||||
DATE_FILTER_CUSTOM = "custom_days"
|
||||
DEFAULT_CUSTOM_LOOKBACK_DAYS = 365
|
||||
MAX_CUSTOM_LOOKBACK_DAYS = 36500
|
||||
DATE_FILTER_THIS_MONTH = "this_month"
|
||||
DATE_FILTER_THIS_YEAR = "this_year"
|
||||
DATE_FILTER_ON_THIS_DAY = "on_this_day"
|
||||
@@ -267,6 +279,7 @@ DATE_FILTER_OPTIONS = [
|
||||
DATE_FILTER_LAST_7,
|
||||
DATE_FILTER_LAST_30,
|
||||
DATE_FILTER_LAST_365,
|
||||
DATE_FILTER_CUSTOM,
|
||||
DATE_FILTER_THIS_MONTH,
|
||||
DATE_FILTER_THIS_YEAR,
|
||||
DATE_FILTER_ON_THIS_DAY,
|
||||
@@ -293,6 +306,7 @@ DEFAULT_REFRESH_HOURS = 24
|
||||
DEFAULT_FILL_MODE = FILL_BLUR
|
||||
DEFAULT_ORIENTATION_MISMATCH_MODE = ORIENTATION_MISMATCH_PAIR
|
||||
DEFAULT_ORDER_MODE = ORDER_RANDOM
|
||||
DEFAULT_SHUFFLE_AGE_BIAS = 0
|
||||
DEFAULT_ASPECT_RATIO = "16:9"
|
||||
DEFAULT_PAIR_DIVIDER_PX = 8
|
||||
DEFAULT_PAIR_DIVIDER_COLOR = "#FFFFFF"
|
||||
|
||||
@@ -6,11 +6,13 @@ from datetime import timedelta
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import async_timeout
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -22,6 +24,12 @@ from .const import (
|
||||
PUBLICALBUM_ENDPOINT,
|
||||
CONF_PROVIDER,
|
||||
CONF_ALBUM_URL,
|
||||
CONF_GOOGLE_METADATA,
|
||||
DEFAULT_GOOGLE_METADATA,
|
||||
CONF_GOOGLE_LOCATION,
|
||||
DEFAULT_GOOGLE_LOCATION,
|
||||
DEFAULT_GOOGLE_REVERSE_GEOCODE,
|
||||
CAMERA_METADATA_FIELDS,
|
||||
CONF_LOCAL_PATH,
|
||||
CONF_MEDIA_CONTENT_ID,
|
||||
CONF_RECURSIVE,
|
||||
@@ -97,6 +105,7 @@ from .const import (
|
||||
from .store import SlideshowStore
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_GOOGLE_METADATA_INTERVAL = 1.0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -127,12 +136,20 @@ class MediaItem:
|
||||
# Provider-specific source identifier (e.g. the Immich asset id) used by
|
||||
# background enrichment to fetch per-item metadata.
|
||||
source_id: str | None = None
|
||||
# Detected faces as normalised [x1, y1, x2, y2, weight, selected] boxes (0..1 in
|
||||
# displayed-image coordinates). Cover-mode cropping keeps as many whole
|
||||
# faces as fit. None means no face data (non-Immich source, not scanned
|
||||
# yet or the face lookup failed); an empty list means "no faces".
|
||||
faces: list[list[float | bool]] | None = None
|
||||
# True once the local-folder EXIF reader has visited this file.
|
||||
# Prevents re-reading EXIF on every coordinator refresh and lets the
|
||||
# background enrichment task skip already-processed files even after
|
||||
# an HA restart (the flag round-trips through the items cache).
|
||||
exif_scanned: bool = False
|
||||
photo_id: str | None = None
|
||||
face_scanned: bool = False
|
||||
camera_metadata: dict[str, Any] | None = None
|
||||
google_location_scanned: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.photo_id is None:
|
||||
@@ -311,11 +328,11 @@ def _pick_timestamp_ms(d: dict[str, Any], *path: str) -> int | None:
|
||||
if not isinstance(cur, dict):
|
||||
return None
|
||||
cur = cur.get(p)
|
||||
if cur is None:
|
||||
if cur is None or isinstance(cur, bool):
|
||||
return None
|
||||
if isinstance(cur, int):
|
||||
# Heuristic: < 1e12 means seconds, otherwise milliseconds.
|
||||
return cur * 1000 if cur < 10**12 else cur
|
||||
# Infer seconds only within the plausible 1800-2100 date range.
|
||||
return cur * 1000 if -5_364_662_400 <= cur <= 4_102_444_800 else cur
|
||||
if isinstance(cur, str):
|
||||
try:
|
||||
iso = cur.replace("Z", "+00:00")
|
||||
@@ -451,6 +468,7 @@ _EXIF_GPS_LAT_REF = 1 # "N" / "S"
|
||||
_EXIF_GPS_LAT = 2 # rational tuple
|
||||
_EXIF_GPS_LON_REF = 3 # "E" / "W"
|
||||
_EXIF_GPS_LON = 4 # rational tuple
|
||||
_HEIF_EXIF_RE = re.compile(rb"Exif\x00\x00(?:MM\x00\x2a|II\x2a\x00)")
|
||||
|
||||
# Nominatim (OpenStreetMap) is free but rate-limited to 1 request/second
|
||||
# per IP and asks integrators to identify themselves with a descriptive
|
||||
@@ -777,7 +795,7 @@ def _read_exif_from_image(img: Any, out: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _read_exif_from_bytes(
|
||||
data: bytes, mtime_fallback_ms: int | None
|
||||
data: bytes, mtime_fallback_ms: int | None, *, strict: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Read EXIF metadata from already-downloaded image bytes.
|
||||
|
||||
@@ -802,11 +820,61 @@ def _read_exif_from_bytes(
|
||||
with Image.open(io.BytesIO(data)) as img:
|
||||
_read_exif_from_image(img, out)
|
||||
except Exception as err:
|
||||
if strict:
|
||||
raise
|
||||
_LOGGER.debug("EXIF: failed to read image bytes: %s", err)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def _read_gps_from_header(data: bytes) -> dict[str, float]:
|
||||
"""Read GPS from an original-image prefix; raise ``ValueError`` if it is too short to tell."""
|
||||
if data[:2] == b"\xff\xd8":
|
||||
payload = _jpeg_exif_segment(data)
|
||||
elif data[4:8] == b"ftyp":
|
||||
match = _HEIF_EXIF_RE.search(data)
|
||||
if match is None:
|
||||
raise ValueError("HEIF EXIF not found in header")
|
||||
payload = data[match.start():]
|
||||
else:
|
||||
metadata = _read_exif_from_bytes(data, None, strict=True)
|
||||
return {key: metadata[key] for key in ("latitude", "longitude") if key in metadata}
|
||||
if payload is None:
|
||||
return {}
|
||||
|
||||
from PIL import Image
|
||||
|
||||
try:
|
||||
exif = Image.Exif()
|
||||
exif.load(payload)
|
||||
gps = exif.get_ifd(_EXIF_TAG_GPS_IFD)
|
||||
except Exception:
|
||||
return {}
|
||||
lat = _gps_to_decimal(gps.get(_EXIF_GPS_LAT), gps.get(_EXIF_GPS_LAT_REF))
|
||||
lon = _gps_to_decimal(gps.get(_EXIF_GPS_LON), gps.get(_EXIF_GPS_LON_REF))
|
||||
return {} if lat is None or lon is None else {"latitude": lat, "longitude": lon}
|
||||
|
||||
|
||||
def _jpeg_exif_segment(data: bytes) -> bytes | None:
|
||||
pos = 2
|
||||
while pos + 4 <= len(data):
|
||||
if data[pos] != 0xFF:
|
||||
return None
|
||||
marker = data[pos + 1]
|
||||
if marker == 0xFF:
|
||||
pos += 1
|
||||
continue
|
||||
if marker in (0xD9, 0xDA):
|
||||
return None
|
||||
end = pos + 2 + int.from_bytes(data[pos + 2:pos + 4], "big")
|
||||
if marker == 0xE1 and data[pos + 4:pos + 10] == b"Exif\x00\x00":
|
||||
if end > len(data):
|
||||
raise ValueError("JPEG EXIF segment is truncated")
|
||||
return data[pos + 4:end]
|
||||
pos = end
|
||||
raise ValueError("JPEG header ends before image data")
|
||||
|
||||
|
||||
def _format_nominatim_location(payload: dict[str, Any]) -> str | None:
|
||||
"""Turn a Nominatim reverse-geocode response into a short label.
|
||||
|
||||
@@ -988,8 +1056,12 @@ def _merge_prior_enrichment(
|
||||
item.location = prev.location
|
||||
if prev.description and not item.description:
|
||||
item.description = prev.description
|
||||
if prev.faces is not None and item.faces is None:
|
||||
item.faces = prev.faces
|
||||
if prev.exif_scanned:
|
||||
item.exif_scanned = True
|
||||
if prev.face_scanned and prev.faces is not None:
|
||||
item.face_scanned = True
|
||||
|
||||
|
||||
class AlbumCoordinator(DataUpdateCoordinator):
|
||||
@@ -1008,6 +1080,13 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
self.store = store
|
||||
|
||||
self.provider: str = entry.data.get(CONF_PROVIDER, PROVIDER_GOOGLE_SHARED)
|
||||
self._immich_cache_source = None
|
||||
if self.provider == PROVIDER_IMMICH:
|
||||
source = [entry.data.get(key) for key in (
|
||||
CONF_IMMICH_URL, CONF_IMMICH_API_KEY, CONF_IMMICH_SELECTION_TYPE,
|
||||
CONF_IMMICH_SELECTION_ID, CONF_IMMICH_FILTER, CONF_IMMICH_IMAGE_SIZE,
|
||||
)]
|
||||
self._immich_cache_source = sha256(json.dumps(source).encode()).hexdigest()
|
||||
self.album_url: str | None = entry.data.get(CONF_ALBUM_URL)
|
||||
self.local_path: str | None = entry.data.get(CONF_LOCAL_PATH)
|
||||
self.recursive: bool = bool(entry.data.get(CONF_RECURSIVE, True))
|
||||
@@ -1106,7 +1185,29 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
raise
|
||||
|
||||
items = data.get("items") or []
|
||||
if self.provider in ENRICHING_PROVIDERS and items:
|
||||
self._apply_google_location_privacy(items)
|
||||
if (self.google_metadata_enabled or self.google_location_enabled) and items:
|
||||
prior = (self.data or {}).get("items", []) if isinstance(self.data, dict) else []
|
||||
if not self._items_cache_loaded:
|
||||
cached = await self._load_cached_items()
|
||||
prior = (cached or {}).get("items", []) + prior
|
||||
self._items_cache_loaded = True
|
||||
by_id = {item.source_id: item for item in prior if item.source_id}
|
||||
for item in items:
|
||||
previous = by_id.get(item.source_id)
|
||||
if previous is None:
|
||||
continue
|
||||
if self.google_metadata_enabled and isinstance(previous.camera_metadata, dict):
|
||||
item.camera_metadata = dict(previous.camera_metadata)
|
||||
item.description = previous.description
|
||||
if self.google_location_enabled and previous.google_location_scanned:
|
||||
item.latitude = previous.latitude
|
||||
item.longitude = previous.longitude
|
||||
item.location = previous.location
|
||||
item.google_location_scanned = True
|
||||
self._apply_google_location_privacy(items)
|
||||
self._schedule_enrichment(data)
|
||||
elif self.provider in ENRICHING_PROVIDERS and items:
|
||||
# Carry forward EXIF/geocode metadata for items we've already
|
||||
# scanned this session; new items get filled in by the
|
||||
# background worker below.
|
||||
@@ -1144,13 +1245,57 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
finally:
|
||||
self._enrichment_task = None
|
||||
|
||||
@property
|
||||
def google_metadata_enabled(self) -> bool:
|
||||
options = getattr(getattr(self, "entry", None), "options", None) or {}
|
||||
return self.provider == PROVIDER_GOOGLE_SHARED and bool(
|
||||
options.get(CONF_GOOGLE_METADATA, DEFAULT_GOOGLE_METADATA)
|
||||
)
|
||||
|
||||
@property
|
||||
def google_location_enabled(self) -> bool:
|
||||
options = getattr(getattr(self, "entry", None), "options", None) or {}
|
||||
return self.provider == PROVIDER_GOOGLE_SHARED and bool(
|
||||
options.get(CONF_GOOGLE_LOCATION, DEFAULT_GOOGLE_LOCATION)
|
||||
)
|
||||
|
||||
@property
|
||||
def google_reverse_geocode_enabled(self) -> bool:
|
||||
options = getattr(getattr(self, "entry", None), "options", None) or {}
|
||||
return self.google_location_enabled and bool(
|
||||
options.get(CONF_REVERSE_GEOCODE, DEFAULT_GOOGLE_REVERSE_GEOCODE)
|
||||
)
|
||||
|
||||
def _apply_google_location_privacy(self, items: list[MediaItem]) -> None:
|
||||
if getattr(self, "provider", None) != PROVIDER_GOOGLE_SHARED:
|
||||
return
|
||||
for item in items:
|
||||
if not self.google_location_enabled:
|
||||
item.latitude = None
|
||||
item.longitude = None
|
||||
item.location = None
|
||||
item.google_location_scanned = False
|
||||
elif not self.google_reverse_geocode_enabled:
|
||||
item.location = None
|
||||
|
||||
def _needs_enrichment(self, item: MediaItem) -> bool:
|
||||
if self.provider == PROVIDER_GOOGLE_SHARED:
|
||||
return (
|
||||
self.google_metadata_enabled and bool(item.source_id) and item.camera_metadata is None
|
||||
) or (self.google_location_enabled and not item.google_location_scanned)
|
||||
if not item.exif_scanned:
|
||||
return True
|
||||
return self.provider == PROVIDER_IMMICH and not item.face_scanned
|
||||
|
||||
def _schedule_enrichment(self, data: dict[str, Any]) -> None:
|
||||
"""Kick off the background EXIF + geocode worker if there's work."""
|
||||
items: list[MediaItem] = data.get("items") or []
|
||||
unscanned = [it for it in items if not it.exif_scanned]
|
||||
unscanned = [it for it in items if self._needs_enrichment(it)]
|
||||
# Providers that decrypt/return GPS inline (Ente) have nothing to scan
|
||||
# but still need the coordinates turned into a place label.
|
||||
needs_geocode = any(
|
||||
needs_geocode = (
|
||||
self.provider != PROVIDER_GOOGLE_SHARED or self.google_reverse_geocode_enabled
|
||||
) and any(
|
||||
it.latitude is not None and it.longitude is not None and not it.location
|
||||
for it in items
|
||||
)
|
||||
@@ -1174,7 +1319,8 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
"geocode_done": 0,
|
||||
}
|
||||
self._enrichment_task = self.hass.async_create_background_task(
|
||||
self._enrich_items_background(data),
|
||||
self._enrich_google_items_background(data) if self.provider == PROVIDER_GOOGLE_SHARED
|
||||
else self._enrich_items_background(data),
|
||||
name=f"album_slideshow_enrich_{self.entry.entry_id}",
|
||||
)
|
||||
|
||||
@@ -1187,6 +1333,10 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
|
||||
cached_source = payload.get("immich_source")
|
||||
if cached_source is not None and cached_source != getattr(self, "_immich_cache_source", None):
|
||||
return None
|
||||
|
||||
raw_items = payload.get("items")
|
||||
if not isinstance(raw_items, list):
|
||||
return None
|
||||
@@ -1210,12 +1360,21 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
location=raw.get("location"),
|
||||
description=raw.get("description"),
|
||||
source_id=raw.get("source_id"),
|
||||
faces=raw.get("faces"),
|
||||
exif_scanned=bool(raw.get("exif_scanned", False)),
|
||||
photo_id=raw.get("photo_id"),
|
||||
face_scanned=bool(raw.get("face_scanned", False))
|
||||
and isinstance(raw.get("faces"), list),
|
||||
camera_metadata={
|
||||
key: value for key, value in raw["camera_metadata"].items()
|
||||
if key in CAMERA_METADATA_FIELDS
|
||||
} if isinstance(raw.get("camera_metadata"), dict) else None,
|
||||
google_location_scanned=bool(raw.get("google_location_scanned", False)),
|
||||
))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
self._apply_google_location_privacy(items)
|
||||
return {
|
||||
"title": payload.get("title"),
|
||||
"items": items,
|
||||
@@ -1223,6 +1382,7 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
|
||||
async def _save_cached_items(self, data: dict[str, Any]) -> None:
|
||||
items = data.get("items") or []
|
||||
self._apply_google_location_privacy(items)
|
||||
# Local-folder URLs are absolute paths on the host; persisting them
|
||||
# is fine but they don't survive a host reformat. Persist anyway,
|
||||
# the URL check at load time will skip any stale entries.
|
||||
@@ -1243,12 +1403,18 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
"location": it.location,
|
||||
"description": it.description,
|
||||
"source_id": it.source_id,
|
||||
"faces": it.faces,
|
||||
"exif_scanned": it.exif_scanned,
|
||||
"photo_id": it.photo_id,
|
||||
"face_scanned": it.face_scanned,
|
||||
"camera_metadata": it.camera_metadata,
|
||||
"google_location_scanned": it.google_location_scanned,
|
||||
}
|
||||
for it in items
|
||||
],
|
||||
}
|
||||
if source := getattr(self, "_immich_cache_source", None):
|
||||
payload["immich_source"] = source
|
||||
try:
|
||||
await self._items_cache_store.async_save(payload)
|
||||
except Exception as err: # pragma: no cover - storage layer
|
||||
@@ -2168,7 +2334,7 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
return None, {}
|
||||
|
||||
async def _enrich_immich_item(self, item: MediaItem) -> None:
|
||||
"""Fetch one Immich asset's detail and fill location/description."""
|
||||
"""Fetch Immich metadata and the face boxes used for cropping."""
|
||||
from . import immich as immich_api
|
||||
|
||||
url = self.entry.data.get(CONF_IMMICH_URL)
|
||||
@@ -2177,23 +2343,164 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
item.exif_scanned = True
|
||||
return
|
||||
client = immich_api.ImmichClient(self.hass, url, api_key)
|
||||
try:
|
||||
asset = await client.async_get_asset(item.source_id)
|
||||
except Exception as err:
|
||||
_LOGGER.debug("Immich: failed to fetch asset %s: %s", item.source_id, err)
|
||||
item.exif_scanned = True
|
||||
person_ids = immich_api.selected_person_ids(
|
||||
self.entry.data.get(CONF_IMMICH_SELECTION_TYPE),
|
||||
self.entry.data.get(CONF_IMMICH_SELECTION_ID),
|
||||
)
|
||||
|
||||
requests = {}
|
||||
needs_faces = not item.face_scanned
|
||||
if not item.exif_scanned or needs_faces:
|
||||
requests["asset"] = client.async_get_asset(item.source_id)
|
||||
if needs_faces:
|
||||
requests["faces"] = client.async_get_faces(item.source_id)
|
||||
results = await asyncio.gather(*requests.values(), return_exceptions=True)
|
||||
asset = None
|
||||
|
||||
for kind, result in zip(requests, results):
|
||||
if isinstance(result, asyncio.CancelledError):
|
||||
raise result
|
||||
if isinstance(result, Exception):
|
||||
_LOGGER.debug(
|
||||
"Immich: failed to fetch %s for asset %s: %s",
|
||||
kind,
|
||||
item.source_id,
|
||||
result,
|
||||
)
|
||||
continue
|
||||
if kind == "asset":
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
asset = result
|
||||
info = immich_api.parse_asset_exif(result)
|
||||
if "captured_at" in info:
|
||||
item.captured_at = info["captured_at"]
|
||||
if "latitude" in info and "longitude" in info:
|
||||
item.latitude = info["latitude"]
|
||||
item.longitude = info["longitude"]
|
||||
if "location" in info:
|
||||
item.location = info["location"]
|
||||
if "description" in info:
|
||||
item.description = info["description"]
|
||||
item.exif_scanned = True
|
||||
else:
|
||||
if asset is None:
|
||||
continue
|
||||
edits = []
|
||||
if asset.get("isEdited"):
|
||||
try:
|
||||
edits = await client.async_get_asset_edits(item.source_id)
|
||||
if not edits:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
_LOGGER.debug("Immich: edit metadata unavailable for asset %s", item.source_id)
|
||||
continue
|
||||
try:
|
||||
boxes = immich_api.parse_face_boxes(
|
||||
result, person_ids, edits=edits,
|
||||
original_size=immich_api.original_image_size(asset),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
_LOGGER.debug("Immich: unsupported face geometry for asset %s", item.source_id)
|
||||
continue
|
||||
item.faces = boxes
|
||||
item.face_scanned = True
|
||||
|
||||
async def _enrich_google_items_background(self, data: dict[str, Any]) -> None:
|
||||
"""Cache optional Google metadata without delaying or failing the playlist."""
|
||||
from . import google_scraper
|
||||
|
||||
jobs = []
|
||||
for item in data.get("items", []):
|
||||
if self.google_metadata_enabled and item.source_id and item.camera_metadata is None:
|
||||
jobs.append((item, False))
|
||||
if self.google_location_enabled and not item.google_location_scanned:
|
||||
jobs.append((item, True))
|
||||
if not jobs:
|
||||
try:
|
||||
if self.google_reverse_geocode_enabled:
|
||||
await self._geocode_items_background(data)
|
||||
finally:
|
||||
self._enrich_progress["phase"] = "done"
|
||||
return
|
||||
info = immich_api.parse_asset_exif(asset)
|
||||
if "captured_at" in info:
|
||||
item.captured_at = info["captured_at"]
|
||||
if "latitude" in info and "longitude" in info:
|
||||
item.latitude = info["latitude"]
|
||||
item.longitude = info["longitude"]
|
||||
if "location" in info:
|
||||
item.location = info["location"]
|
||||
if "description" in info:
|
||||
item.description = info["description"]
|
||||
item.exif_scanned = True
|
||||
failures = 0
|
||||
completed = 0
|
||||
next_request = 0.0
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
async with aiohttp.ClientSession(
|
||||
cookie_jar=aiohttp.DummyCookieJar(), trust_env=False,
|
||||
) as session:
|
||||
keys = None
|
||||
for item, location_job in jobs:
|
||||
delay = next_request - loop.time()
|
||||
if delay > 0:
|
||||
await asyncio.sleep(delay)
|
||||
try:
|
||||
if location_job:
|
||||
header = await google_scraper.fetch_photo_location_header(session, item.url)
|
||||
try:
|
||||
metadata = await self.hass.async_add_executor_job(
|
||||
_read_gps_from_header, header,
|
||||
)
|
||||
except Exception as err:
|
||||
# A photo that cannot be parsed must not stop the scan for the rest.
|
||||
_LOGGER.debug("Google photo GPS unreadable (%s)", type(err).__name__)
|
||||
continue
|
||||
latitude = metadata.get("latitude")
|
||||
longitude = metadata.get("longitude")
|
||||
if (
|
||||
all(type(value) in (int, float) and math.isfinite(value)
|
||||
for value in (latitude, longitude))
|
||||
and -90 <= latitude <= 90 and -180 <= longitude <= 180
|
||||
and (abs(latitude) > 1e-6 or abs(longitude) > 1e-6)
|
||||
):
|
||||
item.latitude, item.longitude = latitude, longitude
|
||||
else:
|
||||
item.latitude = item.longitude = None
|
||||
item.location = None
|
||||
item.google_location_scanned = True
|
||||
else:
|
||||
if keys is None:
|
||||
keys = await google_scraper.fetch_metadata_keys(session, self.album_url)
|
||||
metadata = await google_scraper.fetch_photo_metadata(
|
||||
session, keys, item.source_id,
|
||||
)
|
||||
item.description = metadata.pop("description", None)
|
||||
item.camera_metadata = metadata
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as err:
|
||||
failures += 1
|
||||
_LOGGER.debug(
|
||||
"Google photo metadata unavailable (%s, status=%s)",
|
||||
type(err).__name__, getattr(err, "status", None),
|
||||
)
|
||||
if failures >= 3 or getattr(err, "status", None) in (401, 403, 429):
|
||||
break
|
||||
else:
|
||||
failures = 0
|
||||
completed += 1
|
||||
if not self._needs_enrichment(item):
|
||||
self._enrich_progress["exif_done"] += 1
|
||||
if completed == 1 or completed % 10 == 0:
|
||||
await self._save_cached_items(data)
|
||||
self.async_set_updated_data(data)
|
||||
finally:
|
||||
next_request = loop.time() + _GOOGLE_METADATA_INTERVAL
|
||||
if self.google_reverse_geocode_enabled:
|
||||
await self._geocode_items_background(data)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as err:
|
||||
_LOGGER.debug("Google photo enrichment stopped (%s)", type(err).__name__)
|
||||
finally:
|
||||
self._enrich_progress["phase"] = "done"
|
||||
await self._save_cached_items(data)
|
||||
if completed:
|
||||
self.async_set_updated_data(data)
|
||||
|
||||
async def _enrich_items_background(self, data: dict[str, Any]) -> None:
|
||||
"""Read EXIF for unscanned local files, then reverse-geocode.
|
||||
@@ -2213,7 +2520,7 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
scanned_since_save = 0
|
||||
try:
|
||||
for idx, item in enumerate(items):
|
||||
if item.exif_scanned:
|
||||
if not self._needs_enrichment(item):
|
||||
# Fast path: yield occasionally so we don't starve
|
||||
# the event loop when (re-)visiting a long list of
|
||||
# already-processed items.
|
||||
@@ -2318,6 +2625,8 @@ class AlbumCoordinator(DataUpdateCoordinator):
|
||||
the GPS coordinates themselves. Successful labels are written
|
||||
back into the items in-place and persisted via the items cache.
|
||||
"""
|
||||
if getattr(self, "provider", None) == PROVIDER_GOOGLE_SHARED and not self.google_reverse_geocode_enabled:
|
||||
return
|
||||
if not bool(
|
||||
self.entry.options.get(CONF_REVERSE_GEOCODE, DEFAULT_REVERSE_GEOCODE)
|
||||
if hasattr(self.entry, "options") and self.entry.options is not None
|
||||
|
||||
@@ -26,9 +26,10 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote, urlsplit, urlunsplit
|
||||
|
||||
from .coordinator import MediaItem
|
||||
|
||||
@@ -61,6 +62,7 @@ _SIZE_SUFFIX_RE = re.compile(r"=[wh]\d+(?:-[a-z0-9]+)*$", re.IGNORECASE)
|
||||
|
||||
_VIDEO_DURATION_KEY = 76647426 # presence indicates a video; we skip those
|
||||
_LIVEPHOTO_KEY = 146008172
|
||||
_LOCATION_HEADER_BYTES = 256 * 1024
|
||||
|
||||
|
||||
class _AlbumKeys:
|
||||
@@ -129,6 +131,146 @@ async def fetch_album(
|
||||
return title, items, video_keys
|
||||
|
||||
|
||||
async def fetch_metadata_keys(session, share_url: str, *, timeout: float = 15.0):
|
||||
"""Read public share keys for optional enrichment, without changing pagination."""
|
||||
async with session.get(
|
||||
share_url, headers={"User-Agent": _BROWSER_UA}, timeout=timeout,
|
||||
allow_redirects=True,
|
||||
) as response:
|
||||
html = await _read_metadata_body(response, 4 * 1024 * 1024)
|
||||
keys = _extract_keys(html)
|
||||
if keys is None:
|
||||
raise ValueError("Public Google album metadata keys unavailable")
|
||||
return keys
|
||||
|
||||
|
||||
async def fetch_photo_location_header(
|
||||
session, image_url: str, *, timeout: float = 15.0,
|
||||
) -> bytes:
|
||||
"""Read a bounded original-image prefix for explicitly enabled GPS extraction."""
|
||||
parsed = urlsplit(image_url)
|
||||
if (
|
||||
parsed.scheme != "https"
|
||||
or not (parsed.hostname or "").endswith(".googleusercontent.com")
|
||||
or parsed.port not in (None, 443)
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
):
|
||||
raise ValueError("Unexpected Google image URL")
|
||||
original = urlunsplit(parsed._replace(
|
||||
path=_SIZE_SUFFIX_RE.sub("", parsed.path) + "=d", fragment="",
|
||||
))
|
||||
async with session.get(
|
||||
original, headers={"Range": f"bytes=0-{_LOCATION_HEADER_BYTES - 1}"},
|
||||
timeout=timeout, allow_redirects=False,
|
||||
) as response:
|
||||
response.raise_for_status()
|
||||
if response.status not in (200, 206):
|
||||
raise ValueError("Unexpected Google image response")
|
||||
content_type = response.headers.get("Content-Type", "").split(";", 1)[0].lower()
|
||||
if not content_type.startswith("image/") and content_type != "application/octet-stream":
|
||||
raise ValueError("Google image response is not an image")
|
||||
if response.status == 206 and not re.fullmatch(
|
||||
r"bytes 0-\d+/(?:\d+|\*)", response.headers.get("Content-Range", ""),
|
||||
):
|
||||
raise ValueError("Unexpected Google image byte range")
|
||||
content = bytearray()
|
||||
async for chunk in response.content.iter_chunked(32768):
|
||||
content.extend(chunk[:_LOCATION_HEADER_BYTES - len(content)])
|
||||
if len(content) >= _LOCATION_HEADER_BYTES:
|
||||
break
|
||||
return bytes(content)
|
||||
|
||||
|
||||
async def fetch_photo_metadata(
|
||||
session, keys: _AlbumKeys, media_key: str, *, timeout: float = 15.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Read camera metadata and description from Google's public photo endpoint."""
|
||||
payload = [media_key, None, keys.auth_key, None, keys.album_key]
|
||||
envelope = json.dumps([[["VrseUb", json.dumps(payload), None, "generic"]]])
|
||||
endpoint = "https://photos.google.com/u/0/_/PhotosUi/data/batchexecute"
|
||||
headers = {
|
||||
"User-Agent": _BROWSER_UA,
|
||||
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
|
||||
"Origin": "https://photos.google.com",
|
||||
"Referer": f"https://photos.google.com/share/{keys.album_key}?key={keys.auth_key}",
|
||||
}
|
||||
async with session.post(
|
||||
endpoint, params={"rpcids": "VrseUb", "source-path": f"/share/{keys.album_key}"},
|
||||
headers=headers, data=f"f.req={quote(envelope)}", timeout=timeout,
|
||||
allow_redirects=False,
|
||||
) as response:
|
||||
body = await _read_metadata_body(response, 1024 * 1024)
|
||||
for line in body.splitlines():
|
||||
try:
|
||||
entries = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if not isinstance(entries, list):
|
||||
continue
|
||||
for entry in entries:
|
||||
if (
|
||||
isinstance(entry, list) and len(entry) >= 3
|
||||
and entry[:2] == ["wrb.fr", "VrseUb"] and isinstance(entry[2], str)
|
||||
):
|
||||
detail = json.loads(entry[2])
|
||||
if _metadata_value(detail, 0, 0) != media_key:
|
||||
raise ValueError("Google photo metadata identity mismatch")
|
||||
return parse_photo_metadata(detail)
|
||||
raise ValueError("Google photo metadata response unavailable")
|
||||
|
||||
|
||||
async def _read_metadata_body(response, limit: int) -> str:
|
||||
response.raise_for_status()
|
||||
if response.status != 200:
|
||||
raise ValueError("Unexpected Google metadata response")
|
||||
chunks = []
|
||||
length = 0
|
||||
async for chunk in response.content.iter_chunked(65536):
|
||||
length += len(chunk)
|
||||
if length > limit:
|
||||
raise ValueError("Google metadata response exceeds size limit")
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks).decode("utf-8")
|
||||
|
||||
|
||||
def _metadata_value(value: Any, *indices: int) -> Any:
|
||||
for index in indices:
|
||||
if not isinstance(value, list) or index >= len(value):
|
||||
return None
|
||||
value = value[index]
|
||||
return value
|
||||
|
||||
|
||||
def parse_photo_metadata(detail: Any) -> dict[str, Any]:
|
||||
"""Extract the camera and description fields verified in public responses."""
|
||||
photo = _metadata_value(detail, 0)
|
||||
if not isinstance(photo, list):
|
||||
raise ValueError("Invalid Google photo metadata")
|
||||
camera = _metadata_value(detail, 0, 1, 8, 4)
|
||||
result: dict[str, Any] = {}
|
||||
for field, index in (("camera_make", 0), ("camera_model", 1)):
|
||||
value = _metadata_value(camera, index)
|
||||
if isinstance(value, str) and value.strip():
|
||||
result[field] = value.strip()[:128]
|
||||
for field, index in (
|
||||
("focal_length_mm", 3), ("aperture_f_number", 4),
|
||||
("iso", 5), ("exposure_time_seconds", 6),
|
||||
):
|
||||
value = _metadata_value(camera, index)
|
||||
if type(value) in (int, float) and math.isfinite(value) and value > 0:
|
||||
if field != "iso" or float(value).is_integer():
|
||||
result[field] = int(value) if field == "iso" else float(value)
|
||||
for section in photo:
|
||||
if not isinstance(section, dict):
|
||||
continue
|
||||
description = _metadata_value(section.get("396644657", section.get(396644657)), 0)
|
||||
if isinstance(description, str) and description.strip():
|
||||
result["description"] = description.strip()
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
# -- Internals ---------------------------------------------------------------
|
||||
|
||||
async def _fetch_album_keys(
|
||||
@@ -398,13 +540,13 @@ def _parse_album_item(raw: Any) -> MediaItem | None:
|
||||
)
|
||||
|
||||
|
||||
# Plausible epoch-ms range: 2000-01-01 to 2100-01-01.
|
||||
_MIN_TS_MS = 946_684_800_000
|
||||
# Plausible epoch-ms range: 1800-01-01 to 2100-01-01.
|
||||
_MIN_TS_MS = -5_364_662_400_000
|
||||
_MAX_TS_MS = 4_102_444_800_000
|
||||
|
||||
|
||||
def _looks_like_timestamp_ms(value: Any) -> bool:
|
||||
return isinstance(value, int) and _MIN_TS_MS <= value <= _MAX_TS_MS
|
||||
return type(value) is int and _MIN_TS_MS <= value <= _MAX_TS_MS
|
||||
|
||||
|
||||
# -- AF block parsing (for the initial 300 items embedded in the HTML) ------
|
||||
|
||||
@@ -2,8 +2,10 @@ from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import NamedTuple
|
||||
|
||||
from PIL import Image, ImageColor, ImageFilter, ImageOps
|
||||
from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont, ImageOps
|
||||
|
||||
from .coordinator import MediaItem
|
||||
|
||||
@@ -14,6 +16,42 @@ FILL_COVER = "cover"
|
||||
FILL_CONTAIN = "contain"
|
||||
FILL_BLUR = "blur"
|
||||
|
||||
class FaceBox(NamedTuple):
|
||||
left: float
|
||||
top: float
|
||||
right: float
|
||||
bottom: float
|
||||
weight: float
|
||||
selected: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CropHints:
|
||||
"""Per-photo inputs for face-aware cropping and the debug overlay.
|
||||
|
||||
``faces`` is None when no face data is known for the photo (not an
|
||||
Immich source, or not scanned yet) and an empty tuple when the photo
|
||||
was scanned and has no faces.
|
||||
"""
|
||||
|
||||
faces: tuple[FaceBox, ...] | None = None
|
||||
debug: bool = False
|
||||
name: str | None = None
|
||||
|
||||
|
||||
# Padding around a face box, as a fraction of the face's own size, so the
|
||||
# crop keeps the whole head rather than just the tight face box.
|
||||
_FACE_PAD_SIDE = 0.3
|
||||
_FACE_PAD_TOP = 0.6
|
||||
_FACE_PAD_BOTTOM = 0.3
|
||||
# A face that is cut by the crop edge counts this much worse than one that is
|
||||
# left out entirely: half a face looks like a mistake, a missing face doesn't.
|
||||
_PARTIAL_PENALTY = 1.5
|
||||
|
||||
FACE_KEPT = "kept"
|
||||
FACE_CUT = "cut"
|
||||
FACE_DROPPED = "dropped"
|
||||
|
||||
# Absolute pixel ceiling. A 20000x20000 JPEG decodes to ~1.2 GB of RGB; Pillow
|
||||
# raises DecompressionBombError above MAX_IMAGE_PIXELS. We set this high enough
|
||||
# that 4K+ sources still decode, but reject anything absurd to protect
|
||||
@@ -120,13 +158,20 @@ def resolve_output_size(
|
||||
return (width, height)
|
||||
|
||||
|
||||
def render_image(img: Image.Image, fill_mode: str, width: int, height: int) -> Image.Image:
|
||||
def render_image(
|
||||
img: Image.Image,
|
||||
fill_mode: str,
|
||||
width: int,
|
||||
height: int,
|
||||
hints: CropHints | None = None,
|
||||
) -> Image.Image:
|
||||
"""Render img into a (width x height) canvas using the given fill mode."""
|
||||
hints = hints or CropHints()
|
||||
if fill_mode == FILL_CONTAIN:
|
||||
return _resize_contain(img, width, height)
|
||||
return _resize_contain(img, width, height, hints=hints)
|
||||
if fill_mode == FILL_BLUR:
|
||||
return _blur_fill(img, width, height)
|
||||
return _resize_cover(img, width, height)
|
||||
return _blur_fill(img, width, height, hints=hints)
|
||||
return _resize_cover(img, width, height, hints)
|
||||
|
||||
|
||||
def pair_images(
|
||||
@@ -139,6 +184,8 @@ def pair_images(
|
||||
divider: int,
|
||||
divider_fill: tuple[int, int, int] | tuple[int, int, int, int],
|
||||
transparent_divider: bool,
|
||||
hints1: CropHints | None = None,
|
||||
hints2: CropHints | None = None,
|
||||
) -> Image.Image:
|
||||
canvas_mode = "RGBA" if transparent_divider else "RGB"
|
||||
canvas = Image.new(canvas_mode, (target_w, target_h), divider_fill)
|
||||
@@ -146,8 +193,8 @@ def pair_images(
|
||||
if portrait_canvas:
|
||||
top_h = max(1, (target_h - divider) // 2)
|
||||
bottom_h = max(1, target_h - divider - top_h)
|
||||
top_img = render_image(img1, fill_mode, target_w, top_h)
|
||||
bottom_img = render_image(img2, fill_mode, target_w, bottom_h)
|
||||
top_img = render_image(img1, fill_mode, target_w, top_h, hints1)
|
||||
bottom_img = render_image(img2, fill_mode, target_w, bottom_h, hints2)
|
||||
canvas.paste(top_img.convert(canvas_mode), (0, 0))
|
||||
canvas.paste(bottom_img.convert(canvas_mode), (0, top_h + divider))
|
||||
safe_close(top_img)
|
||||
@@ -156,8 +203,8 @@ def pair_images(
|
||||
|
||||
left_w = max(1, (target_w - divider) // 2)
|
||||
right_w = max(1, target_w - divider - left_w)
|
||||
left_img = render_image(img1, fill_mode, left_w, target_h)
|
||||
right_img = render_image(img2, fill_mode, right_w, target_h)
|
||||
left_img = render_image(img1, fill_mode, left_w, target_h, hints1)
|
||||
right_img = render_image(img2, fill_mode, right_w, target_h, hints2)
|
||||
canvas.paste(left_img.convert(canvas_mode), (0, 0))
|
||||
canvas.paste(right_img.convert(canvas_mode), (left_w + divider, 0))
|
||||
safe_close(left_img)
|
||||
@@ -252,7 +299,131 @@ def _parse_aspect_ratio(ratio: str) -> tuple[int, int]:
|
||||
return (16, 9)
|
||||
|
||||
|
||||
def _resize_cover(img: Image.Image, target_w: int, target_h: int) -> Image.Image:
|
||||
def _padded_face(face: FaceBox) -> tuple[float, float, float, float]:
|
||||
x1, y1, x2, y2 = face[:4]
|
||||
fw, fh = x2 - x1, y2 - y1
|
||||
return (
|
||||
max(0.0, x1 - fw * _FACE_PAD_SIDE),
|
||||
max(0.0, y1 - fh * _FACE_PAD_TOP),
|
||||
min(1.0, x2 + fw * _FACE_PAD_SIDE),
|
||||
min(1.0, y2 + fh * _FACE_PAD_BOTTOM),
|
||||
)
|
||||
|
||||
|
||||
def _span_status(a: float, b: float, offset: float, window: float) -> str:
|
||||
# One pixel of slack absorbs rounding when the image is scaled to fit
|
||||
# an axis exactly.
|
||||
if a >= offset - 1 and b <= offset + window + 1:
|
||||
return FACE_KEPT
|
||||
if b <= offset or a >= offset + window:
|
||||
return FACE_DROPPED
|
||||
return FACE_CUT
|
||||
|
||||
|
||||
def choose_crop_offset(
|
||||
spans: list[tuple[float, float, float]],
|
||||
src_len: float,
|
||||
window: float,
|
||||
*,
|
||||
selected: list[bool] | None = None,
|
||||
padded_spans: list[tuple[float, float]] | None = None,
|
||||
) -> float:
|
||||
"""Pick where a crop window of ``window`` px starts along one axis.
|
||||
|
||||
``spans`` are unpadded ``(start, end, weight)`` face intervals. Selected
|
||||
people rank ahead of all bystanders. Keep whole faces where possible,
|
||||
retain visible face area otherwise, and use padding as a preference.
|
||||
"""
|
||||
max_offset = max(0.0, src_len - window)
|
||||
centred = max_offset / 2
|
||||
if max_offset <= 0 or not spans:
|
||||
return centred
|
||||
|
||||
def clamp(value: float) -> float:
|
||||
return max(0.0, min(max_offset, value))
|
||||
|
||||
priorities = selected if selected is not None else [False] * len(spans)
|
||||
padding = padded_spans if padded_spans is not None else [span[:2] for span in spans]
|
||||
|
||||
def visible_fraction(start: float, end: float, offset: float) -> float:
|
||||
overlap = max(0.0, min(end, offset + window) - max(start, offset))
|
||||
return overlap / (end - start)
|
||||
|
||||
def score(offset: float) -> tuple[float, ...]:
|
||||
tiers = []
|
||||
for priority in (True, False):
|
||||
kept_weight = cut_weight = visible_weight = 0.0
|
||||
for (start, end, weight), is_selected in zip(spans, priorities):
|
||||
if is_selected != priority:
|
||||
continue
|
||||
state = _span_status(start, end, offset, window)
|
||||
if state == FACE_KEPT:
|
||||
kept_weight += weight
|
||||
elif state == FACE_CUT:
|
||||
cut_weight += weight
|
||||
visible_weight += weight * visible_fraction(start, end, offset)
|
||||
tiers.extend((
|
||||
kept_weight,
|
||||
-_PARTIAL_PENALTY * cut_weight if kept_weight else visible_weight,
|
||||
))
|
||||
tiers.append(sum(
|
||||
span[2] * visible_fraction(start, end, offset)
|
||||
for span, (start, end) in zip(spans, padding)
|
||||
))
|
||||
return tuple(round(value, 12) for value in tiers)
|
||||
|
||||
candidates = {0.0, centred, max_offset}
|
||||
for start, end in [span[:2] for span in spans] + padding:
|
||||
for offset in (start, end - window, end, start - window, (start + end - window) / 2):
|
||||
candidates.add(clamp(offset))
|
||||
best = max(candidates, key=lambda offset: (score(offset), -abs(offset - centred), -offset))
|
||||
|
||||
kept = [
|
||||
index for index, (start, end, _weight) in enumerate(spans)
|
||||
if _span_status(start, end, best, window) == FACE_KEPT
|
||||
]
|
||||
if not kept:
|
||||
return best
|
||||
group_start = min(padding[index][0] for index in kept)
|
||||
group_end = max(padding[index][1] for index in kept)
|
||||
if group_end - group_start > window:
|
||||
group_start = min(spans[index][0] for index in kept)
|
||||
group_end = max(spans[index][1] for index in kept)
|
||||
target = clamp((group_start + group_end - window) / 2)
|
||||
candidates.add(target)
|
||||
return max(candidates, key=lambda offset: (score(offset), -abs(offset - target), -offset))
|
||||
|
||||
|
||||
def _face_statuses(
|
||||
faces: tuple[FaceBox, ...],
|
||||
new_w: int,
|
||||
new_h: int,
|
||||
left: int,
|
||||
top: int,
|
||||
target_w: int,
|
||||
target_h: int,
|
||||
) -> list[str]:
|
||||
statuses = []
|
||||
for face in faces:
|
||||
px1, py1, px2, py2 = face[:4]
|
||||
x = _span_status(px1 * new_w, px2 * new_w, left, target_w)
|
||||
y = _span_status(py1 * new_h, py2 * new_h, top, target_h)
|
||||
if FACE_DROPPED in (x, y):
|
||||
statuses.append(FACE_DROPPED)
|
||||
elif FACE_CUT in (x, y):
|
||||
statuses.append(FACE_CUT)
|
||||
else:
|
||||
statuses.append(FACE_KEPT)
|
||||
return statuses
|
||||
|
||||
|
||||
def _resize_cover(
|
||||
img: Image.Image,
|
||||
target_w: int,
|
||||
target_h: int,
|
||||
hints: CropHints | None = None,
|
||||
) -> Image.Image:
|
||||
hints = hints or CropHints()
|
||||
src_w, src_h = img.size
|
||||
if src_w <= 0 or src_h <= 0:
|
||||
return img.resize((target_w, target_h))
|
||||
@@ -260,15 +431,137 @@ def _resize_cover(img: Image.Image, target_w: int, target_h: int) -> Image.Image
|
||||
new_w = max(1, int(round(src_w * scale)))
|
||||
new_h = max(1, int(round(src_h * scale)))
|
||||
resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
left = max(0, int(round((new_w - target_w) / 2)))
|
||||
top = max(0, int(round((new_h - target_h) / 2)))
|
||||
|
||||
faces = tuple(FaceBox(*face) for face in hints.faces or ())
|
||||
padded = [_padded_face(face) for face in faces]
|
||||
left = choose_crop_offset(
|
||||
[(face.left * new_w, face.right * new_w, face.weight) for face in faces],
|
||||
new_w,
|
||||
target_w,
|
||||
selected=[face.selected for face in faces],
|
||||
padded_spans=[(box[0] * new_w, box[2] * new_w) for box in padded],
|
||||
)
|
||||
top = choose_crop_offset(
|
||||
[(face.top * new_h, face.bottom * new_h, face.weight) for face in faces],
|
||||
new_h,
|
||||
target_h,
|
||||
selected=[face.selected for face in faces],
|
||||
padded_spans=[(box[1] * new_h, box[3] * new_h) for box in padded],
|
||||
)
|
||||
left = max(0, min(max(0, new_w - target_w), int(round(left))))
|
||||
top = max(0, min(max(0, new_h - target_h), int(round(top))))
|
||||
|
||||
statuses = _face_statuses(faces, new_w, new_h, left, top, target_w, target_h)
|
||||
summary = _face_summary(hints.faces, statuses)
|
||||
if faces:
|
||||
_LOGGER.debug("Crop %s: %s", hints.name or "photo", summary)
|
||||
if hints.debug:
|
||||
_draw_debug_marks(resized, faces, statuses)
|
||||
|
||||
cropped = resized.crop((left, top, left + target_w, top + target_h))
|
||||
if cropped is not resized:
|
||||
safe_close(resized)
|
||||
if hints.debug:
|
||||
_draw_offscreen_centre(cropped, new_w / 2 - left, new_h / 2 - top)
|
||||
_draw_debug_label(cropped, summary)
|
||||
return cropped
|
||||
|
||||
|
||||
def _resize_contain(img: Image.Image, target_w: int, target_h: int, bg=(0, 0, 0)) -> Image.Image:
|
||||
def _face_summary(faces: tuple[FaceBox, ...] | None, statuses: list[str]) -> str:
|
||||
if faces is None:
|
||||
return "no face data"
|
||||
return (
|
||||
f"faces {len(statuses)} · kept {statuses.count(FACE_KEPT)} · "
|
||||
f"cut {statuses.count(FACE_CUT)} · dropped {statuses.count(FACE_DROPPED)}"
|
||||
)
|
||||
|
||||
|
||||
_DEBUG_COLORS = {
|
||||
FACE_KEPT: (0, 220, 0),
|
||||
FACE_CUT: (255, 40, 40),
|
||||
FACE_DROPPED: (160, 160, 160),
|
||||
}
|
||||
_CROSSHAIR_COLOR = (255, 220, 0)
|
||||
|
||||
|
||||
def _draw_debug_marks(
|
||||
img: Image.Image, faces: tuple[FaceBox, ...], statuses: list[str]
|
||||
) -> None:
|
||||
"""Draw face boxes and a crosshair on the photo's own centre.
|
||||
|
||||
Drawn before cropping, so the marks get cut exactly like the photo: a
|
||||
crosshair that is off-centre or missing shows how much was cropped away.
|
||||
"""
|
||||
w, h = img.size
|
||||
draw = ImageDraw.Draw(img)
|
||||
line = max(2, round(min(w, h) / 200))
|
||||
for face, status in zip(faces, statuses):
|
||||
color = _DEBUG_COLORS[status]
|
||||
x1, y1, x2, y2 = face[:4]
|
||||
draw.rectangle((x1 * w, y1 * h, x2 * w, y2 * h), outline=color, width=line)
|
||||
px1, py1, px2, py2 = _padded_face(face)
|
||||
draw.rectangle(
|
||||
(px1 * w, py1 * h, px2 * w, py2 * h),
|
||||
outline=color,
|
||||
width=max(1, line // 2),
|
||||
)
|
||||
cx, cy = w / 2, h / 2
|
||||
arm = max(12, round(min(w, h) / 12))
|
||||
for width, color in ((line + 2, (0, 0, 0)), (line, _CROSSHAIR_COLOR)):
|
||||
draw.line((cx - arm, cy, cx + arm, cy), fill=color, width=width)
|
||||
draw.line((cx, cy - arm, cx, cy + arm), fill=color, width=width)
|
||||
radius = arm / 3
|
||||
draw.ellipse(
|
||||
(cx - radius, cy - radius, cx + radius, cy + radius),
|
||||
outline=_CROSSHAIR_COLOR,
|
||||
width=line,
|
||||
)
|
||||
|
||||
|
||||
def _draw_offscreen_centre(img: Image.Image, cx: float, cy: float) -> None:
|
||||
"""When the photo's centre was cropped away, point at it from the edge."""
|
||||
w, h = img.size
|
||||
if 0 <= cx <= w and 0 <= cy <= h:
|
||||
return
|
||||
size = max(10, round(min(w, h) / 20))
|
||||
x = max(size, min(w - size, cx))
|
||||
y = max(size, min(h - size, cy))
|
||||
if cx < 0:
|
||||
points = [(0, y), (size, y - size), (size, y + size)]
|
||||
elif cx > w:
|
||||
points = [(w, y), (w - size, y - size), (w - size, y + size)]
|
||||
elif cy < 0:
|
||||
points = [(x, 0), (x - size, size), (x + size, size)]
|
||||
else:
|
||||
points = [(x, h), (x - size, h - size), (x + size, h - size)]
|
||||
ImageDraw.Draw(img).polygon(points, fill=_CROSSHAIR_COLOR, outline=(0, 0, 0))
|
||||
|
||||
|
||||
def _debug_font(size: int):
|
||||
try:
|
||||
return ImageFont.load_default(size=size)
|
||||
except TypeError: # Pillow < 10.1 has a fixed-size default font
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _draw_debug_label(img: Image.Image, text: str) -> None:
|
||||
w, h = img.size
|
||||
draw = ImageDraw.Draw(img)
|
||||
size = max(12, round(min(w, h) / 30))
|
||||
font = _debug_font(size)
|
||||
pad = max(4, size // 3)
|
||||
x1, y1, x2, y2 = draw.textbbox((pad, pad), text, font=font)
|
||||
draw.rectangle((x1 - pad, y1 - pad, x2 + pad, y2 + pad), fill=(0, 0, 0))
|
||||
draw.text((pad, pad), text, fill=(255, 255, 255), font=font)
|
||||
|
||||
|
||||
def _resize_contain(
|
||||
img: Image.Image,
|
||||
target_w: int,
|
||||
target_h: int,
|
||||
bg=(0, 0, 0),
|
||||
hints: CropHints | None = None,
|
||||
) -> Image.Image:
|
||||
src_w, src_h = img.size
|
||||
if src_w <= 0 or src_h <= 0:
|
||||
return img.resize((target_w, target_h))
|
||||
@@ -276,6 +569,7 @@ def _resize_contain(img: Image.Image, target_w: int, target_h: int, bg=(0, 0, 0)
|
||||
new_w = max(1, int(src_w * scale))
|
||||
new_h = max(1, int(src_h * scale))
|
||||
resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
_debug_uncropped(resized, hints)
|
||||
canvas = Image.new("RGB", (target_w, target_h), bg)
|
||||
rgb_resized = resized if resized.mode == "RGB" else resized.convert("RGB")
|
||||
canvas.paste(rgb_resized, ((target_w - new_w) // 2, (target_h - new_h) // 2))
|
||||
@@ -285,7 +579,22 @@ def _resize_contain(img: Image.Image, target_w: int, target_h: int, bg=(0, 0, 0)
|
||||
return canvas
|
||||
|
||||
|
||||
def _blur_fill(img: Image.Image, target_w: int, target_h: int) -> Image.Image:
|
||||
def _debug_uncropped(img: Image.Image, hints: CropHints | None) -> None:
|
||||
"""Debug marks for fill modes that never crop: every face is kept."""
|
||||
if hints is None or not hints.debug:
|
||||
return
|
||||
faces = hints.faces or ()
|
||||
statuses = [FACE_KEPT] * len(faces)
|
||||
_draw_debug_marks(img, faces, statuses)
|
||||
_draw_debug_label(img, _face_summary(hints.faces, statuses))
|
||||
|
||||
|
||||
def _blur_fill(
|
||||
img: Image.Image,
|
||||
target_w: int,
|
||||
target_h: int,
|
||||
hints: CropHints | None = None,
|
||||
) -> Image.Image:
|
||||
bg = _resize_cover(img, target_w, target_h).filter(ImageFilter.GaussianBlur(radius=24))
|
||||
src_w, src_h = img.size
|
||||
if src_w <= 0 or src_h <= 0:
|
||||
@@ -294,10 +603,10 @@ def _blur_fill(img: Image.Image, target_w: int, target_h: int) -> Image.Image:
|
||||
new_w = max(1, int(src_w * scale))
|
||||
new_h = max(1, int(src_h * scale))
|
||||
fg = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
||||
_debug_uncropped(fg, hints)
|
||||
rgb_fg = fg if fg.mode == "RGB" else fg.convert("RGB")
|
||||
bg.paste(rgb_fg, ((target_w - new_w) // 2, (target_h - new_h) // 2))
|
||||
if rgb_fg is not fg:
|
||||
safe_close(rgb_fg)
|
||||
safe_close(fg)
|
||||
return bg
|
||||
|
||||
|
||||
@@ -14,12 +14,15 @@ API shape (Immich v1.13x / v3, ``/api`` prefix, ``x-api-key`` header):
|
||||
``originalFileName`` but NOT ``exifInfo``.
|
||||
- ``GET /api/assets/{id}`` -> full asset incl ``exifInfo`` (lat/long, city,
|
||||
country, description) - used to enrich location/description per asset.
|
||||
- ``GET /api/faces?id={id}`` -> recognised faces and bounding boxes - used to
|
||||
keep faces whole in cover-mode crops.
|
||||
- Image bytes: ``/api/assets/{id}/thumbnail?size=preview|fullsize`` or
|
||||
``/api/assets/{id}/original`` (all require the ``x-api-key`` header).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
@@ -241,6 +244,198 @@ def parse_asset_exif(asset: Any) -> dict[str, Any]:
|
||||
return out
|
||||
|
||||
|
||||
def selected_person_ids(
|
||||
selection_type: str | None, selection_id: str | None
|
||||
) -> set[str]:
|
||||
"""Return the people explicitly selected for an Immich source.
|
||||
|
||||
Current entries use a composite JSON selection, while older entries can
|
||||
still carry the legacy ``person``/``people`` shapes. Album-only, favorite,
|
||||
random and custom-search sources intentionally return an empty set: there
|
||||
is no user-selected face to prioritise for those sources.
|
||||
"""
|
||||
if selection_type == "person":
|
||||
return {selection_id} if selection_id else set()
|
||||
if selection_type == "people":
|
||||
return {person_id for person_id in (selection_id or "").split(",") if person_id}
|
||||
if selection_type == "composite":
|
||||
return set(parse_composite_selection(selection_id)["people"])
|
||||
return set()
|
||||
|
||||
|
||||
def _normalised_face_box(
|
||||
face: Any,
|
||||
edits: list[dict[str, Any]] | None = None,
|
||||
original_size: tuple[float, float] | None = None,
|
||||
) -> tuple[float, float, float, float] | None:
|
||||
"""Return a face's bounding box normalised to 0..1, or None if invalid."""
|
||||
if not isinstance(face, dict):
|
||||
return None
|
||||
width = face.get("imageWidth")
|
||||
height = face.get("imageHeight")
|
||||
coords = (
|
||||
face.get("boundingBoxX1"),
|
||||
face.get("boundingBoxY1"),
|
||||
face.get("boundingBoxX2"),
|
||||
face.get("boundingBoxY2"),
|
||||
)
|
||||
if (
|
||||
any(isinstance(value, bool) or not isinstance(value, (int, float))
|
||||
or not math.isfinite(value) for value in (width, height, *coords))
|
||||
or width <= 0
|
||||
or height <= 0
|
||||
):
|
||||
return None
|
||||
x1, y1, x2, y2 = coords
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return None
|
||||
box = _original_face_box(
|
||||
(x1 / width, y1 / height, x2 / width, y2 / height),
|
||||
edits or [], original_size,
|
||||
)
|
||||
box = tuple(max(0.0, min(1.0, value)) for value in box)
|
||||
return box if box[2] > box[0] and box[3] > box[1] else None
|
||||
|
||||
|
||||
def parse_face_boxes(
|
||||
faces: Any,
|
||||
person_ids: set[str] | None = None,
|
||||
*,
|
||||
edits: list[dict[str, Any]] | None = None,
|
||||
original_size: tuple[float, float] | None = None,
|
||||
) -> list[list[float | bool]]:
|
||||
"""Return normalised ``[x1, y1, x2, y2, area, selected]`` face boxes.
|
||||
|
||||
Immich reports face boxes in the coordinate space described by each
|
||||
face's ``imageWidth``/``imageHeight``. Normalising each box makes it
|
||||
independent of whether Album Slideshow downloads a preview, full-size
|
||||
derivative or original. Faces Immich has not linked to a named person
|
||||
are included. Explicit person selection is a separate priority from area.
|
||||
"""
|
||||
if not isinstance(faces, list):
|
||||
return []
|
||||
boxes: list[list[float | bool]] = []
|
||||
for face in faces:
|
||||
box = _normalised_face_box(face, edits, original_size)
|
||||
if box is None:
|
||||
continue
|
||||
x1, y1, x2, y2 = box
|
||||
weight = (x2 - x1) * (y2 - y1)
|
||||
person = face.get("person")
|
||||
selected = bool(
|
||||
person_ids and isinstance(person, dict) and person.get("id") in person_ids
|
||||
)
|
||||
boxes.append([x1, y1, x2, y2, weight, selected])
|
||||
return boxes
|
||||
|
||||
|
||||
def _original_face_box(
|
||||
box: tuple[float, float, float, float],
|
||||
edits: list[dict[str, Any]],
|
||||
original_size: tuple[float, float] | None,
|
||||
) -> tuple[float, float, float, float]:
|
||||
points = [(box[0], box[1]), (box[2], box[3])]
|
||||
crop = None
|
||||
for edit in reversed(edits):
|
||||
if not isinstance(edit, dict) or not isinstance(edit.get("parameters"), dict):
|
||||
raise ValueError("Invalid Immich edit metadata")
|
||||
params = edit["parameters"]
|
||||
action = edit.get("action")
|
||||
if action == "rotate":
|
||||
angle = params.get("angle")
|
||||
if angle == 90:
|
||||
points = [(vertical, 1 - horizontal) for horizontal, vertical in points]
|
||||
elif angle == 180:
|
||||
points = [(1 - horizontal, 1 - vertical) for horizontal, vertical in points]
|
||||
elif angle == 270:
|
||||
points = [(1 - vertical, horizontal) for horizontal, vertical in points]
|
||||
elif angle != 0:
|
||||
raise ValueError("Unsupported Immich rotation")
|
||||
elif action == "mirror":
|
||||
axis = params.get("axis")
|
||||
if axis == "horizontal":
|
||||
points = [(horizontal, 1 - vertical) for horizontal, vertical in points]
|
||||
elif axis == "vertical":
|
||||
points = [(1 - horizontal, vertical) for horizontal, vertical in points]
|
||||
else:
|
||||
raise ValueError("Unsupported Immich mirror axis")
|
||||
elif action == "crop" and crop is None:
|
||||
crop = params
|
||||
else:
|
||||
raise ValueError("Unsupported Immich edit")
|
||||
if crop is not None:
|
||||
values = [crop.get(name) for name in ("x", "y", "width", "height")]
|
||||
if original_size is None or any(
|
||||
isinstance(value, bool) or not isinstance(value, (int, float))
|
||||
or not math.isfinite(value) for value in values
|
||||
):
|
||||
raise ValueError("Missing Immich crop dimensions")
|
||||
crop_left, crop_top, crop_width, crop_height = values
|
||||
original_width, original_height = original_size
|
||||
if (
|
||||
crop_left < 0 or crop_top < 0 or crop_width <= 0 or crop_height <= 0
|
||||
or crop_left + crop_width > original_width
|
||||
or crop_top + crop_height > original_height
|
||||
):
|
||||
raise ValueError("Invalid Immich crop dimensions")
|
||||
points = [
|
||||
((horizontal * crop_width + crop_left) / original_width,
|
||||
(vertical * crop_height + crop_top) / original_height)
|
||||
for horizontal, vertical in points
|
||||
]
|
||||
return (
|
||||
min(point[0] for point in points), min(point[1] for point in points),
|
||||
max(point[0] for point in points), max(point[1] for point in points),
|
||||
)
|
||||
|
||||
|
||||
def original_image_size(asset: Any) -> tuple[float, float] | None:
|
||||
info = asset.get("exifInfo") if isinstance(asset, dict) else None
|
||||
if not isinstance(info, dict):
|
||||
return None
|
||||
width, height = info.get("exifImageWidth"), info.get("exifImageHeight")
|
||||
if any(
|
||||
isinstance(value, bool) or not isinstance(value, (int, float))
|
||||
or not math.isfinite(value) or value <= 0 for value in (width, height)
|
||||
):
|
||||
return None
|
||||
if str(info.get("orientation")) in {"5", "6", "7", "8", "-90", "90"}:
|
||||
return (float(height), float(width))
|
||||
return (float(width), float(height))
|
||||
|
||||
|
||||
def parse_face_focus(
|
||||
faces: Any,
|
||||
person_ids: set[str],
|
||||
*,
|
||||
edits: list[dict[str, Any]] | None = None,
|
||||
original_size: tuple[float, float] | None = None,
|
||||
) -> tuple[float, float] | None:
|
||||
"""Return a normalised crop focus for the selected people in an asset.
|
||||
|
||||
Immich reports face boxes in the coordinate space described by each
|
||||
face's ``imageWidth``/``imageHeight``. Normalising each box makes the
|
||||
focus independent of resolution. Edited coordinates are mapped back to the
|
||||
unedited image before clamping. When several selected people appear in the
|
||||
same photo, focus on the centre of their combined region.
|
||||
"""
|
||||
if not isinstance(faces, list) or not person_ids:
|
||||
return None
|
||||
selected_faces = [
|
||||
face for face in faces
|
||||
if isinstance(face, dict) and isinstance(face.get("person"), dict)
|
||||
and face["person"].get("id") in person_ids
|
||||
]
|
||||
boxes = parse_face_boxes(selected_faces, edits=edits, original_size=original_size)
|
||||
if not boxes:
|
||||
return None
|
||||
left = min(box[0] for box in boxes)
|
||||
top = min(box[1] for box in boxes)
|
||||
right = max(box[2] for box in boxes)
|
||||
bottom = max(box[3] for box in boxes)
|
||||
return ((left + right) / 2, (top + bottom) / 2)
|
||||
|
||||
|
||||
class ImmichClient:
|
||||
"""Thin async wrapper over the Immich REST API."""
|
||||
|
||||
@@ -373,3 +568,15 @@ class ImmichClient:
|
||||
|
||||
async def async_get_asset(self, asset_id: str) -> dict[str, Any]:
|
||||
return await self._get(f"/api/assets/{asset_id}")
|
||||
|
||||
async def async_get_faces(self, asset_id: str) -> list[dict[str, Any]]:
|
||||
data = await self._get(f"/api/faces?id={asset_id}")
|
||||
if not isinstance(data, list):
|
||||
raise ValueError("Invalid Immich face response")
|
||||
return data
|
||||
|
||||
async def async_get_asset_edits(self, asset_id: str) -> list[dict[str, Any]]:
|
||||
data = await self._get(f"/api/assets/{asset_id}/edits")
|
||||
if not isinstance(data, dict) or not isinstance(data.get("edits"), list):
|
||||
raise ValueError("Invalid Immich edit response")
|
||||
return data["edits"]
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
"documentation": "https://github.com/eyalgal/album_slideshow",
|
||||
"iot_class": "cloud_polling",
|
||||
"issue_tracker": "https://github.com/eyalgal/album_slideshow/issues",
|
||||
"requirements": ["Pillow", "PyNaCl>=1.5.0"],
|
||||
"version": "1.11.0"
|
||||
"requirements": ["PyNaCl>=1.5.0"],
|
||||
"version": "1.13.0"
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
from .const import DOMAIN
|
||||
from .const import DOMAIN, MAX_CUSTOM_LOOKBACK_DAYS
|
||||
from .coordinator import AlbumCoordinator
|
||||
from .store import SlideshowStore
|
||||
|
||||
@@ -23,6 +23,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
|
||||
PairMinGapPercentNumber(entry, store),
|
||||
NavigationBufferSizeNumber(entry, store),
|
||||
ImageCacheMbNumber(entry, store),
|
||||
CustomLookbackDaysNumber(entry, store),
|
||||
ShuffleAgeBiasNumber(entry, store),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -49,6 +51,66 @@ class _BaseNumber(NumberEntity, RestoreEntity):
|
||||
}
|
||||
|
||||
|
||||
class CustomLookbackDaysNumber(_BaseNumber):
|
||||
_attr_icon = "mdi:calendar-range"
|
||||
_attr_native_min_value = 1
|
||||
_attr_native_max_value = MAX_CUSTOM_LOOKBACK_DAYS
|
||||
_attr_native_step = 1
|
||||
_attr_native_unit_of_measurement = "d"
|
||||
|
||||
def __init__(self, entry: ConfigEntry, store: SlideshowStore) -> None:
|
||||
super().__init__(entry, store)
|
||||
self._attr_unique_id = f"{entry.entry_id}_custom_lookback_days"
|
||||
self._attr_name = "Custom lookback days"
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
return int(self.store.custom_lookback_days)
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
self.store.custom_lookback_days = max(1, min(MAX_CUSTOM_LOOKBACK_DAYS, int(value)))
|
||||
self.store.notify()
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
await super().async_added_to_hass()
|
||||
old = await self.async_get_last_state()
|
||||
if old and old.state not in (None, "unknown", "unavailable"):
|
||||
try:
|
||||
await self.async_set_native_value(float(old.state))
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return
|
||||
|
||||
|
||||
class ShuffleAgeBiasNumber(_BaseNumber):
|
||||
_attr_icon = "mdi:shuffle-variant"
|
||||
_attr_native_min_value = -100
|
||||
_attr_native_max_value = 100
|
||||
_attr_native_step = 1
|
||||
_attr_mode = NumberMode.SLIDER
|
||||
|
||||
def __init__(self, entry: ConfigEntry, store: SlideshowStore) -> None:
|
||||
super().__init__(entry, store)
|
||||
self._attr_unique_id = f"{entry.entry_id}_shuffle_age_bias"
|
||||
self._attr_name = "Shuffle age bias"
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
return int(self.store.shuffle_age_bias)
|
||||
|
||||
async def async_set_native_value(self, value: float) -> None:
|
||||
self.store.shuffle_age_bias = max(-100, min(100, int(value)))
|
||||
self.store.notify()
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
await super().async_added_to_hass()
|
||||
old = await self.async_get_last_state()
|
||||
if old and old.state not in (None, "unknown", "unavailable"):
|
||||
try:
|
||||
await self.async_set_native_value(float(old.state))
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return
|
||||
|
||||
|
||||
class SlideIntervalNumber(_BaseNumber):
|
||||
_attr_icon = "mdi:timer-outline"
|
||||
_attr_native_min_value = 3
|
||||
|
||||
@@ -7,9 +7,11 @@ implementation. Operates on ``MediaItem``-like objects that expose
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import math
|
||||
from typing import Iterable, TypeVar
|
||||
|
||||
from .const import (
|
||||
DATE_FILTER_CUSTOM,
|
||||
DATE_FILTER_LAST_7,
|
||||
DATE_FILTER_LAST_30,
|
||||
DATE_FILTER_LAST_365,
|
||||
@@ -17,7 +19,9 @@ from .const import (
|
||||
DATE_FILTER_ON_THIS_DAY,
|
||||
DATE_FILTER_THIS_MONTH,
|
||||
DATE_FILTER_THIS_YEAR,
|
||||
DEFAULT_CUSTOM_LOOKBACK_DAYS,
|
||||
DEFAULT_MISSING_DATE_MODE,
|
||||
MAX_CUSTOM_LOOKBACK_DAYS,
|
||||
MISSING_DATE_EXCLUDE,
|
||||
MISSING_DATE_USE_UPLOADED,
|
||||
ORDER_ALBUM,
|
||||
@@ -31,6 +35,39 @@ from .const import (
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def age_weights(
|
||||
items: list[T],
|
||||
bias: float,
|
||||
*,
|
||||
missing_date: str = DEFAULT_MISSING_DATE_MODE,
|
||||
) -> list[float]:
|
||||
"""Return relative draw weights, from 1 to 10, favoring newer (+) or older (-)."""
|
||||
if isinstance(bias, bool) or not isinstance(bias, (int, float)) or not math.isfinite(bias):
|
||||
bias = 0
|
||||
bias = max(-100, min(100, bias))
|
||||
if not bias:
|
||||
return [1.0] * len(items)
|
||||
timestamps = []
|
||||
for item in items:
|
||||
timestamp = getattr(item, "captured_at", None)
|
||||
if type(timestamp) is not int and missing_date == MISSING_DATE_USE_UPLOADED:
|
||||
timestamp = getattr(item, "uploaded_at", None)
|
||||
timestamps.append(timestamp if type(timestamp) is int else None)
|
||||
dated = [timestamp for timestamp in timestamps if timestamp is not None]
|
||||
if not dated or min(dated) == max(dated):
|
||||
return [1.0] * len(items)
|
||||
oldest, newest = min(dated), max(dated)
|
||||
strength = 9 * abs(bias) / 100
|
||||
weights = []
|
||||
for timestamp in timestamps:
|
||||
if timestamp is None:
|
||||
weights.append(1.0)
|
||||
continue
|
||||
position = (timestamp - oldest) / (newest - oldest)
|
||||
weights.append(1 + strength * (position if bias > 0 else 1 - position))
|
||||
return weights
|
||||
|
||||
|
||||
def order_items(items: list[T], order_mode: str) -> list[T]:
|
||||
"""Return a new list ordered per ``order_mode``.
|
||||
|
||||
@@ -76,6 +113,7 @@ def filter_items(
|
||||
*,
|
||||
mode: str,
|
||||
missing_date: str = DEFAULT_MISSING_DATE_MODE,
|
||||
lookback_days: int = DEFAULT_CUSTOM_LOOKBACK_DAYS,
|
||||
now: datetime | None = None,
|
||||
) -> list[T]:
|
||||
"""Filter items by date according to ``mode``.
|
||||
@@ -97,7 +135,7 @@ def filter_items(
|
||||
|
||||
today_utc = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
|
||||
|
||||
pred, strict = _build_predicate(mode, today_utc)
|
||||
pred, strict = _build_predicate(mode, today_utc, lookback_days)
|
||||
if pred is None:
|
||||
return list(items)
|
||||
|
||||
@@ -130,8 +168,14 @@ def filter_items(
|
||||
def _build_predicate(
|
||||
mode: str,
|
||||
today_utc: datetime,
|
||||
lookback_days: int = DEFAULT_CUSTOM_LOOKBACK_DAYS,
|
||||
):
|
||||
"""Return (predicate, strict). ``strict`` drops items without timestamps."""
|
||||
if mode == DATE_FILTER_CUSTOM:
|
||||
days = lookback_days if type(lookback_days) is int else DEFAULT_CUSTOM_LOOKBACK_DAYS
|
||||
days = max(1, min(MAX_CUSTOM_LOOKBACK_DAYS, days))
|
||||
cutoff = int((today_utc - timedelta(days=days)).timestamp() * 1000)
|
||||
return (lambda timestamp: timestamp >= cutoff), False
|
||||
if mode == DATE_FILTER_LAST_7:
|
||||
cutoff = int((today_utc - timedelta(days=7)).timestamp() * 1000)
|
||||
return (lambda ts: ts >= cutoff), False
|
||||
|
||||
@@ -22,7 +22,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
|
||||
CacheUsageSensor(entry, coordinator),
|
||||
HiddenPhotoCountSensor(entry, coordinator),
|
||||
]
|
||||
if coordinator.provider in ENRICHING_PROVIDERS:
|
||||
if (
|
||||
coordinator.provider in ENRICHING_PROVIDERS
|
||||
or coordinator.google_metadata_enabled
|
||||
or coordinator.google_location_enabled
|
||||
):
|
||||
# Diagnostic surface for the background enrichment pass (per-photo
|
||||
# metadata reads and/or reverse-geocode). Providers with nothing to
|
||||
# enrich omit it to keep the device screen tidy.
|
||||
|
||||
@@ -13,6 +13,7 @@ from .const import (
|
||||
DEFAULT_FILL_MODE,
|
||||
DEFAULT_ORIENTATION_MISMATCH_MODE,
|
||||
DEFAULT_ORDER_MODE,
|
||||
DEFAULT_SHUFFLE_AGE_BIAS,
|
||||
DEFAULT_ASPECT_RATIO,
|
||||
DEFAULT_PAIR_DIVIDER_PX,
|
||||
DEFAULT_PAIR_DIVIDER_COLOR,
|
||||
@@ -21,6 +22,7 @@ from .const import (
|
||||
DEFAULT_NAVIGATION_BUFFER_SIZE,
|
||||
DEFAULT_MAX_RESOLUTION,
|
||||
DEFAULT_DATE_FILTER,
|
||||
DEFAULT_CUSTOM_LOOKBACK_DAYS,
|
||||
DEFAULT_MISSING_DATE_MODE,
|
||||
)
|
||||
|
||||
@@ -35,6 +37,7 @@ class SlideshowStore:
|
||||
fill_mode: str = DEFAULT_FILL_MODE
|
||||
portrait_mode: str = DEFAULT_ORIENTATION_MISMATCH_MODE
|
||||
order_mode: str = DEFAULT_ORDER_MODE
|
||||
shuffle_age_bias: int = DEFAULT_SHUFFLE_AGE_BIAS
|
||||
aspect_ratio: str = DEFAULT_ASPECT_RATIO
|
||||
pair_divider_px: int = DEFAULT_PAIR_DIVIDER_PX
|
||||
pair_divider_color: str = DEFAULT_PAIR_DIVIDER_COLOR
|
||||
@@ -45,6 +48,7 @@ class SlideshowStore:
|
||||
|
||||
# Date filter mode (preset windows like this_year / on_this_day).
|
||||
date_filter: str = DEFAULT_DATE_FILTER
|
||||
custom_lookback_days: int = DEFAULT_CUSTOM_LOOKBACK_DAYS
|
||||
|
||||
# How the date filter treats photos with no EXIF capture date.
|
||||
missing_date_mode: str = DEFAULT_MISSING_DATE_MODE
|
||||
@@ -52,6 +56,9 @@ class SlideshowStore:
|
||||
# Pause toggle - when True, the slideshow holds on the current frame.
|
||||
paused: bool = False
|
||||
|
||||
# Draw face boxes, a centre crosshair and a crop summary on each slide.
|
||||
face_debug: bool = False
|
||||
|
||||
# In-memory last rendered frame. Not user-configurable; used to re-serve
|
||||
# the previous slide instantly across a camera reload.
|
||||
last_frame: bytes | None = None
|
||||
|
||||
@@ -172,19 +172,55 @@
|
||||
"nextcloud_cannot_connect": "Could not connect to Nextcloud. Check the URL, username, app password and folder path.",
|
||||
"invalid_nextcloud_url": "That does not look like a Nextcloud Photos public album link.",
|
||||
"nextcloud_public_cannot_connect": "Could not connect to that Nextcloud album. Check the link is still valid.",
|
||||
"invalid_ente_url": "That does not look like an Ente public album link. It should look like {example_url}, including the part after the #."
|
||||
,"ente_cannot_connect": "Could not open that Ente album. The link may be expired, revoked, or password-protected."
|
||||
"invalid_ente_url": "That does not look like an Ente public album link. It should look like {example_url}, including the part after the #.",
|
||||
"ente_cannot_connect": "Could not open that Ente album. The link may be expired, revoked, or password-protected."
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"google_metadata": {
|
||||
"title": "Google Photos metadata and privacy",
|
||||
"description": "Photo descriptions, camera details, and exposure metadata use Google's undocumented public endpoint without a Google login. Results are cached; unavailable metadata does not prevent the slideshow from loading.\n\nOriginal photo GPS is a separate opt-in, off by default. It reads up to 256 KB per photo. Google only includes GPS in shared originals when location sharing is turned on for the album; anyone with the album link can then see precise GPS. After changing the album's location sharing, turn this off and back on to rescan. Coordinates are cached in Home Assistant and exposed in camera attributes. Google-added or estimated locations are not included.\n\nPlace-name lookup is also off by default. It requires original GPS reading and sends coordinates to the public OpenStreetMap Nominatim service. Disabling original GPS hides coordinates and place names and stops both lookups; it does not erase previous history or backups.",
|
||||
"data": {
|
||||
"google_metadata": "Fetch photo metadata (experimental)",
|
||||
"google_location": "Read original photo GPS (opt-in)",
|
||||
"reverse_geocode": "Look up GPS place names via OpenStreetMap (opt-in)"
|
||||
}
|
||||
},
|
||||
"init": {
|
||||
"title": "Location & privacy options",
|
||||
"description": "Reverse geocoding sends your photos' EXIF GPS coordinates to the public OpenStreetMap Nominatim service to look up a human-readable place name. Coordinates are rounded to ~100 m before lookup and cached on disk. Turn this off to keep coordinates entirely local; the latitude and longitude attributes still work either way.",
|
||||
"data": {
|
||||
"reverse_geocode": "Reverse-geocode EXIF GPS coordinates via OpenStreetMap"
|
||||
}
|
||||
},
|
||||
"immich_select": {
|
||||
"title": "Immich source",
|
||||
"description": "Change which albums, people and favorites this slideshow shows. Saving reloads the slideshow; its entities, settings and hidden photos are kept.",
|
||||
"data": {
|
||||
"album_name": "Name",
|
||||
"albums": "Albums",
|
||||
"people": "People",
|
||||
"favorites": "Include favorites",
|
||||
"immich_filter": "Extra search filter (JSON, optional)",
|
||||
"immich_image_size": "Image quality",
|
||||
"reverse_geocode": "Look up EXIF GPS locations via OpenStreetMap"
|
||||
}
|
||||
},
|
||||
"connection": {
|
||||
"title": "Immich connection",
|
||||
"description": "The stored Immich URL or API key no longer works. Update them to continue.",
|
||||
"data": {
|
||||
"immich_url": "Immich URL (e.g. http://192.168.1.10:2283)",
|
||||
"immich_api_key": "API key"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"immich_cache_clear_failed": "Could not clear the previous photo source cache. No source settings were changed. Please try again.",
|
||||
"immich_cannot_connect": "Could not connect to Immich. Check the URL and API key.",
|
||||
"immich_invalid_auth": "Immich rejected the API key. Check that it is valid and that its permissions include server.about, album.read and person.read.",
|
||||
"immich_filter_invalid": "The filter must be a valid JSON object. See the README for examples."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
from homeassistant.components.switch import SwitchEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity import EntityCategory
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
|
||||
@@ -12,7 +13,7 @@ from .store import SlideshowStore
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> None:
|
||||
store: SlideshowStore = hass.data[DOMAIN][entry.entry_id]["store"]
|
||||
async_add_entities([PauseSwitch(entry, store)])
|
||||
async_add_entities([PauseSwitch(entry, store), CropDebugSwitch(entry, store)])
|
||||
|
||||
|
||||
class PauseSwitch(SwitchEntity, RestoreEntity):
|
||||
@@ -53,3 +54,46 @@ class PauseSwitch(SwitchEntity, RestoreEntity):
|
||||
if old is not None and old.state in ("on", "off"):
|
||||
self.store.paused = old.state == "on"
|
||||
self.store.notify()
|
||||
|
||||
|
||||
class CropDebugSwitch(SwitchEntity, RestoreEntity):
|
||||
"""Overlay face boxes, a centre crosshair and a crop summary on slides."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_should_poll = False
|
||||
_attr_icon = "mdi:face-recognition"
|
||||
_attr_entity_category = EntityCategory.CONFIG
|
||||
|
||||
def __init__(self, entry: ConfigEntry, store: SlideshowStore) -> None:
|
||||
self.entry = entry
|
||||
self.store = store
|
||||
self._attr_unique_id = f"{entry.entry_id}_crop_debug"
|
||||
self._attr_name = "Crop debug overlay"
|
||||
|
||||
@property
|
||||
def is_on(self) -> bool:
|
||||
return bool(self.store.face_debug)
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
return {
|
||||
"identifiers": {(DOMAIN, self.entry.entry_id)},
|
||||
"name": f"Album Slideshow {self.entry.title}",
|
||||
"manufacturer": "Album Slideshow",
|
||||
}
|
||||
|
||||
async def async_turn_on(self, **kwargs) -> None:
|
||||
self.store.face_debug = True
|
||||
self.store.notify()
|
||||
|
||||
async def async_turn_off(self, **kwargs) -> None:
|
||||
self.store.face_debug = False
|
||||
self.store.notify()
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
await super().async_added_to_hass()
|
||||
self.store.add_listener(self.async_write_ha_state)
|
||||
old = await self.async_get_last_state()
|
||||
if old is not None and old.state in ("on", "off"):
|
||||
self.store.face_debug = old.state == "on"
|
||||
self.store.notify()
|
||||
|
||||
@@ -172,19 +172,55 @@
|
||||
"nextcloud_cannot_connect": "Could not connect to Nextcloud. Check the URL, username, app password and folder path.",
|
||||
"invalid_nextcloud_url": "That does not look like a Nextcloud Photos public album link.",
|
||||
"nextcloud_public_cannot_connect": "Could not connect to that Nextcloud album. Check the link is still valid.",
|
||||
"invalid_ente_url": "That does not look like an Ente public album link. It should look like {example_url}, including the part after the #."
|
||||
,"ente_cannot_connect": "Could not open that Ente album. The link may be expired, revoked, or password-protected."
|
||||
"invalid_ente_url": "That does not look like an Ente public album link. It should look like {example_url}, including the part after the #.",
|
||||
"ente_cannot_connect": "Could not open that Ente album. The link may be expired, revoked, or password-protected."
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"google_metadata": {
|
||||
"title": "Google Photos metadata and privacy",
|
||||
"description": "Photo descriptions, camera details, and exposure metadata use Google's undocumented public endpoint without a Google login. Results are cached; unavailable metadata does not prevent the slideshow from loading.\n\nOriginal photo GPS is a separate opt-in, off by default. It reads up to 256 KB per photo. Google only includes GPS in shared originals when location sharing is turned on for the album; anyone with the album link can then see precise GPS. After changing the album's location sharing, turn this off and back on to rescan. Coordinates are cached in Home Assistant and exposed in camera attributes. Google-added or estimated locations are not included.\n\nPlace-name lookup is also off by default. It requires original GPS reading and sends coordinates to the public OpenStreetMap Nominatim service. Disabling original GPS hides coordinates and place names and stops both lookups; it does not erase previous history or backups.",
|
||||
"data": {
|
||||
"google_metadata": "Fetch photo metadata (experimental)",
|
||||
"google_location": "Read original photo GPS (opt-in)",
|
||||
"reverse_geocode": "Look up GPS place names via OpenStreetMap (opt-in)"
|
||||
}
|
||||
},
|
||||
"init": {
|
||||
"title": "Location & privacy options",
|
||||
"description": "Reverse geocoding sends your photos' EXIF GPS coordinates to the public OpenStreetMap Nominatim service to look up a human-readable place name. Coordinates are rounded to ~100 m before lookup and cached on disk. Turn this off to keep coordinates entirely local; the latitude and longitude attributes still work either way.",
|
||||
"data": {
|
||||
"reverse_geocode": "Reverse-geocode EXIF GPS coordinates via OpenStreetMap"
|
||||
}
|
||||
},
|
||||
"immich_select": {
|
||||
"title": "Immich source",
|
||||
"description": "Change which albums, people and favorites this slideshow shows. Saving reloads the slideshow; its entities, settings and hidden photos are kept.",
|
||||
"data": {
|
||||
"album_name": "Name",
|
||||
"albums": "Albums",
|
||||
"people": "People",
|
||||
"favorites": "Include favorites",
|
||||
"immich_filter": "Extra search filter (JSON, optional)",
|
||||
"immich_image_size": "Image quality",
|
||||
"reverse_geocode": "Look up EXIF GPS locations via OpenStreetMap"
|
||||
}
|
||||
},
|
||||
"connection": {
|
||||
"title": "Immich connection",
|
||||
"description": "The stored Immich URL or API key no longer works. Update them to continue.",
|
||||
"data": {
|
||||
"immich_url": "Immich URL (e.g. http://192.168.1.10:2283)",
|
||||
"immich_api_key": "API key"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"immich_cache_clear_failed": "Could not clear the previous photo source cache. No source settings were changed. Please try again.",
|
||||
"immich_cannot_connect": "Could not connect to Immich. Check the URL and API key.",
|
||||
"immich_invalid_auth": "Immich rejected the API key. Check that it is valid and that its permissions include server.about, album.read and person.read.",
|
||||
"immich_filter_invalid": "The filter must be a valid JSON object. See the README for examples."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ from homeassistant.auth import EVENT_USER_REMOVED
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_STOP
|
||||
from homeassistant.core import (
|
||||
CoreState,
|
||||
Event,
|
||||
HomeAssistant,
|
||||
ServiceCall,
|
||||
@@ -1502,6 +1503,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: MaintenanceSupporterConf
|
||||
await todo_mirror.async_setup()
|
||||
hass.data[DOMAIN][TODO_MIRROR_KEY] = todo_mirror
|
||||
|
||||
# 2026-10 places: tell a person what is due where they just arrived —
|
||||
# same lifecycle as the mirrors (global entry owns it).
|
||||
from .helpers.places import PLACES_KEY, PlaceArrivals
|
||||
|
||||
if PLACES_KEY not in hass.data[DOMAIN]:
|
||||
place_arrivals = PlaceArrivals(hass)
|
||||
place_arrivals.async_setup()
|
||||
hass.data[DOMAIN][PLACES_KEY] = place_arrivals
|
||||
|
||||
# One-time migration: auto-enable advanced feature flags for existing users
|
||||
options = dict(entry.options or entry.data)
|
||||
if CONF_ADVANCED_ADAPTIVE not in options:
|
||||
@@ -1727,6 +1737,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: MaintenanceSupporterConf
|
||||
entry.runtime_data = MaintenanceSupporterData(coordinator=coordinator, store=store)
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
# A shopping-list row checked while this object was not loaded (a
|
||||
# reload after a task edit, a setup retry) waits for it — the resync
|
||||
# books it now. At startup the pass after "started" covers it.
|
||||
if hass.state is CoreState.running:
|
||||
from .shopping_sync import schedule_resync
|
||||
|
||||
schedule_resync(hass)
|
||||
|
||||
# #148: a battery type that becomes known only after fleet setup (a
|
||||
# Battery Notes note added later, a typed low-only Matter binary)
|
||||
# never got its spare part — reconcile once per start, after the
|
||||
@@ -2118,6 +2136,11 @@ async def async_unload_entry(hass: HomeAssistant, entry: MaintenanceSupporterCon
|
||||
todo_mirror = hass.data.get(DOMAIN, {}).pop(TODO_MIRROR_KEY, None)
|
||||
if todo_mirror is not None:
|
||||
todo_mirror.async_teardown()
|
||||
from .helpers.places import PLACES_KEY
|
||||
|
||||
place_arrivals = hass.data.get(DOMAIN, {}).pop(PLACES_KEY, None)
|
||||
if place_arrivals is not None:
|
||||
place_arrivals.async_teardown()
|
||||
# NOT the full-text index: it is shared runtime (built once per boot
|
||||
# by _async_setup_shared, which a hub reload does not re-run) — a
|
||||
# reload of the global entry (any settings save) closed it for the
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import logging
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -700,6 +701,12 @@ class MaintenanceCalendar(CalendarEntity):
|
||||
else:
|
||||
live_tasks = {}
|
||||
|
||||
# 2026-10 places: an object maintained away from home names its
|
||||
# place as the events' location (phone calendars show it).
|
||||
from .helpers.places import object_place, zone_name
|
||||
|
||||
place_name = zone_name(self._hass, object_place(entry.data.get(CONF_OBJECT)))
|
||||
|
||||
# Merge static (ConfigEntry) + dynamic (Store) task data
|
||||
tasks_data = merged_tasks(entry)
|
||||
schedule_time_enabled = self._is_schedule_time_feature_enabled()
|
||||
@@ -731,6 +738,8 @@ class MaintenanceCalendar(CalendarEntity):
|
||||
|
||||
event = self._create_event_for_task(task, obj_name, start_d, end_d, live_status=live.get("_status"))
|
||||
if event:
|
||||
if place_name:
|
||||
event = dataclasses.replace(event, location=place_name)
|
||||
events.append(event)
|
||||
|
||||
return events
|
||||
|
||||
@@ -29,6 +29,7 @@ from .const import (
|
||||
CONF_ADVANCED_COMPLETION_ACTIONS,
|
||||
CONF_ADVANCED_ENVIRONMENTAL,
|
||||
CONF_ADVANCED_GROUPS,
|
||||
CONF_ADVANCED_PLACES,
|
||||
CONF_ADVANCED_SCHEDULE_TIME,
|
||||
CONF_ADVANCED_SEASONAL,
|
||||
CONF_ARCHIVE_ONEOFF_DAYS,
|
||||
@@ -771,6 +772,10 @@ class GlobalOptionsFlow(OptionsFlow):
|
||||
CONF_ADVANCED_COMPLETION_ACTIONS,
|
||||
default=self._opt(CONF_ADVANCED_COMPLETION_ACTIONS),
|
||||
): selector.BooleanSelector(),
|
||||
vol.Optional(
|
||||
CONF_ADVANCED_PLACES,
|
||||
default=self._opt(CONF_ADVANCED_PLACES),
|
||||
): selector.BooleanSelector(),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
@@ -197,17 +197,14 @@ class TriggerStepsMixin(TriggerConfigMixin):
|
||||
def _clear_stale_trigger_runtime(self, old_tc: dict[str, Any], new_tc: dict[str, Any]) -> None:
|
||||
"""Drop persisted trigger runtime when the trigger fundamentally changed.
|
||||
|
||||
Mirrors the WS update path (websocket/tasks_crud.py): the Store
|
||||
runtime wins over config on restore (#102), so an options-flow edit
|
||||
that changes type/entities/baseline must clear it or the old
|
||||
The same rule as the WS update path (trigger_runtime_stale): the
|
||||
Store runtime wins over config on restore (#102), so an options-flow
|
||||
edit that changes type/entities/baseline must clear it or the old
|
||||
counters/anchors silently survive the edit (bug audit 2026-08-22).
|
||||
"""
|
||||
if (
|
||||
old_tc.get("type") != new_tc.get("type")
|
||||
or old_tc.get("entity_id") != new_tc.get("entity_id")
|
||||
or old_tc.get("entity_ids") != new_tc.get("entity_ids")
|
||||
or old_tc.get("trigger_baseline_value") != new_tc.get("trigger_baseline_value")
|
||||
):
|
||||
from .entity.triggers import trigger_runtime_stale
|
||||
|
||||
if trigger_runtime_stale(old_tc, new_tc):
|
||||
rd = getattr(self.config_entry, "runtime_data", None)
|
||||
store = getattr(rd, "store", None) if rd else None
|
||||
if store is not None:
|
||||
|
||||
@@ -162,6 +162,9 @@ CONF_ADVANCED_SCHEDULE_TIME = "advanced_schedule_time_visible"
|
||||
# Print-QR generator. Default OFF — beginners aren't overwhelmed; data
|
||||
# still persists if a user toggles the flag off again.
|
||||
CONF_ADVANCED_COMPLETION_ACTIONS = "advanced_completion_actions_visible"
|
||||
# 2026-10: shows the object's place (an HA zone) and "remind only on site" in
|
||||
# the panel. Visibility only, like the others: a place set before keeps working.
|
||||
CONF_ADVANCED_PLACES = "advanced_places_visible"
|
||||
|
||||
# Panel-access overrides: HA user IDs who get the full admin panel despite
|
||||
# not being HA admins. Empty list means only admins see the full panel.
|
||||
@@ -419,6 +422,10 @@ VENDOR_URL = "/maintenance_supporter_vendor"
|
||||
CONF_OBJECT = "object"
|
||||
CONF_OBJECT_NAME = "name"
|
||||
CONF_OBJECT_AREA = "area_id"
|
||||
# 2026-10 places: an HA zone the object is maintained at (None = home), and
|
||||
# whether its reminders wait until somebody is there (helpers/places.py).
|
||||
CONF_OBJECT_PLACE = "place"
|
||||
CONF_OBJECT_REMIND_ON_SITE = "remind_on_site"
|
||||
CONF_OBJECT_MANUFACTURER = "manufacturer"
|
||||
CONF_OBJECT_MODEL = "model"
|
||||
CONF_OBJECT_SERIAL_NUMBER = "serial_number"
|
||||
@@ -838,6 +845,12 @@ SIGNAL_DOCUMENTS_UPDATED = f"{DOMAIN}_documents_updated"
|
||||
|
||||
# --- Trigger Completion Cooldown ---
|
||||
TRIGGER_COMPLETION_COOLDOWN_SECONDS = 600 # 10 minutes
|
||||
|
||||
# Places (helpers/places.py): a person must stay this long in a zone before
|
||||
# the arrival message goes out (a drive past a zone edge is no visit), and
|
||||
# gets it at most once per this window for the same place.
|
||||
PLACE_ARRIVAL_DWELL_SECONDS = 120
|
||||
PLACE_ARRIVAL_COOLDOWN_SECONDS = 6 * 3600
|
||||
# Household double-complete window: two people tapping Complete on the same
|
||||
# task within this many seconds count as ONE real-world action (journey M1).
|
||||
# Short on purpose — a deliberate complete → reset → complete-again correction
|
||||
|
||||
@@ -89,6 +89,10 @@ _TRIGGER_EPOCH_TYPES = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
# Trigger types whose refresh-time fallback reads the live entity states (the
|
||||
# others read persisted counters): only a reading may end their episode.
|
||||
_STATE_READING_TRIGGER_TYPES = frozenset({"threshold", "counter", "due_date"})
|
||||
|
||||
|
||||
def _takes_day_suggestion(schedule: Schedule) -> bool:
|
||||
"""True when a suggested interval IN DAYS can be applied to the schedule:
|
||||
@@ -706,6 +710,14 @@ class MaintenanceCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
task._trigger_current_value = result.current_value
|
||||
if in_cooldown:
|
||||
return # the value for display only — no re-activation yet
|
||||
if result.active is False and trigger_type in _STATE_READING_TRIGGER_TYPES and not self._trigger_has_reading(entity_ids):
|
||||
# An episode ends on a reading, never on sensors that are all
|
||||
# offline. The evaluators already give no verdict then; this
|
||||
# keeps the rule for any evaluator to come: a counter read as
|
||||
# "not reached" while it was unavailable flipped the task to OK
|
||||
# and back, and the next restart announced the same activation
|
||||
# again (live installation 2026-10-04).
|
||||
return
|
||||
if result.active is not None:
|
||||
if task._trigger_active and not result.active:
|
||||
# A recovery only this sweep saw still ends the episode.
|
||||
@@ -1959,6 +1971,15 @@ class MaintenanceCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
task_result["_trigger_current_value"] = value
|
||||
task_result["_status"] = compute_status_from_task_dict(task_result)
|
||||
|
||||
def _trigger_has_reading(self, entity_ids: list[str]) -> bool:
|
||||
"""Whether at least one of a trigger's entities has a state at all
|
||||
(exists, and is not unavailable / unknown)."""
|
||||
for entity_id in entity_ids:
|
||||
state = self.hass.states.get(entity_id)
|
||||
if state is not None and state.state not in UNAVAILABLE_STATES:
|
||||
return True
|
||||
return False
|
||||
|
||||
def note_trigger_cleared(self, task_id: str) -> None:
|
||||
"""The task's trigger episode ended (every entity back in range).
|
||||
Persisted, so :meth:`trigger_already_announced` sees the episode
|
||||
|
||||
@@ -70,6 +70,28 @@ def primary_entity_id(trigger_config: Any) -> str | None:
|
||||
return next((eid for eid in normalize_entity_ids(trigger_config) if isinstance(eid, str) and eid), None)
|
||||
|
||||
|
||||
def trigger_runtime_stale(old: Any, new: Any) -> bool:
|
||||
"""Whether a trigger edit invalidates the task's persisted trigger
|
||||
runtime (counter baselines, runtime hours, change counts): another type,
|
||||
other entities or an edited counting start value. The ONE rule for the
|
||||
WebSocket update and the options flow.
|
||||
|
||||
The entities are compared normalized. An old task stores only the legacy
|
||||
``entity_id``, while every validated edit carries ``entity_ids`` too;
|
||||
comparing the raw keys read that as "other entities", so the first save
|
||||
of such a task wiped its baseline or hours even when only the target
|
||||
changed (live installation 2026-10-04). A compound keeps its runtime per
|
||||
condition and, as before, only a type change resets it.
|
||||
"""
|
||||
old_tc = old if isinstance(old, dict) else {}
|
||||
new_tc = new if isinstance(new, dict) else {}
|
||||
if old_tc.get("type") != new_tc.get("type"):
|
||||
return True
|
||||
if new_tc.get("type") != TriggerType.COMPOUND and normalize_entity_ids(old_tc) != normalize_entity_ids(new_tc):
|
||||
return True
|
||||
return bool(old_tc.get("trigger_baseline_value") != new_tc.get("trigger_baseline_value"))
|
||||
|
||||
|
||||
def _migrate_flat_to_per_entity(config: dict[str, Any], first_entity_id: str) -> dict[str, dict[str, Any]]:
|
||||
"""Create ``_trigger_state`` from legacy flat keys on first load.
|
||||
|
||||
|
||||
@@ -227,6 +227,13 @@ def _build_export_object(
|
||||
# gallery) — only emitted when set, like the fleet flag below.
|
||||
if obj_data.get("template_id"):
|
||||
export_obj["template_id"] = obj_data["template_id"]
|
||||
# 2026-10 places — only when set, so an object at home exports as before.
|
||||
# A zone id is instance-specific: on another instance without that zone
|
||||
# the object behaves as at home and the panel says the zone is missing.
|
||||
if obj_data.get("place"):
|
||||
export_obj["place"] = obj_data["place"]
|
||||
if obj_data.get("remind_on_site") is True:
|
||||
export_obj["remind_on_site"] = True
|
||||
# Battery fleet identity — only emitted for the fleet object so a plain
|
||||
# object's export stays byte-identical to earlier versions. The importer
|
||||
# mirrors these (and keeps the deterministic ``batt_<type>`` part ids).
|
||||
|
||||
@@ -42,12 +42,13 @@ export interface MockFeatures {
|
||||
checklists: boolean;
|
||||
schedule_time: boolean;
|
||||
completion_actions: boolean;
|
||||
places: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_FEATURES: MockFeatures = {
|
||||
adaptive: false, seasonal: false,
|
||||
environmental: false, budget: false, groups: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false, places: false,
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -69,7 +69,7 @@ function ctx(overrides: Partial<TaskDetailContext> = {}): TaskDetailContext {
|
||||
features: {
|
||||
adaptive: false, seasonal: false,
|
||||
environmental: false, budget: false, groups: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false, places: false,
|
||||
},
|
||||
currencySymbol: "€",
|
||||
collapsedSections: new Set(),
|
||||
@@ -297,7 +297,7 @@ describe("task-detail renderer", () => {
|
||||
features: {
|
||||
adaptive: false, seasonal: false,
|
||||
environmental: false, budget: false, groups: false,
|
||||
checklists: true, schedule_time: false, completion_actions: false,
|
||||
checklists: true, schedule_time: false, completion_actions: false, places: false,
|
||||
},
|
||||
setChecklistItem: (item, done) => calls.push([item, done]),
|
||||
}),
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ function ctx(overrides: Partial<TaskDetailContext> = {}): TaskDetailContext {
|
||||
features: {
|
||||
adaptive: false, seasonal: false,
|
||||
environmental: false, budget: false, groups: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false,
|
||||
checklists: false, schedule_time: false, completion_actions: false, places: false,
|
||||
},
|
||||
currencySymbol: "€",
|
||||
collapsedSections: new Set(),
|
||||
|
||||
@@ -21,6 +21,8 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
/** All objects — choices for the parent-object picker (2.19). */
|
||||
@property({ attribute: false }) public objects: MaintenanceObjectResponse[] = [];
|
||||
/** 2026-10 places: the advanced feature switch shows the place fields. */
|
||||
@property({ type: Boolean }) public placesEnabled = false;
|
||||
@state() private _open = false;
|
||||
@state() private _loading = false;
|
||||
@state() private _error = "";
|
||||
@@ -39,6 +41,9 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
// 2.19: attach to an existing HA device / nest under another object
|
||||
@state() private _haDeviceId = "";
|
||||
@state() private _parentEntryId = "";
|
||||
// 2026-10 places: an HA zone ("" = home) and "remind only on site".
|
||||
@state() private _place = "";
|
||||
@state() private _remindOnSite = false;
|
||||
@state() private _entryId: string | null = null; // null = create, string = update
|
||||
// Replace (journey N1): the successor's device. The old unit's device is
|
||||
// what the object links to now; a new unit usually is a new device.
|
||||
@@ -63,6 +68,8 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
this._notes = "";
|
||||
this._haDeviceId = "";
|
||||
this._parentEntryId = "";
|
||||
this._place = "";
|
||||
this._remindOnSite = false;
|
||||
this._replacing = false;
|
||||
this._error = "";
|
||||
this._open = true;
|
||||
@@ -96,6 +103,8 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
this._notes = obj.notes || "";
|
||||
this._haDeviceId = obj.ha_device_id || "";
|
||||
this._parentEntryId = obj.parent_entry_id || "";
|
||||
this._place = obj.place || "";
|
||||
this._remindOnSite = !!obj.remind_on_site;
|
||||
this._replacing = false;
|
||||
this._error = "";
|
||||
this._open = true;
|
||||
@@ -194,6 +203,35 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
/** 2026-10 places: the zone the object is maintained at ("" = home) and
|
||||
* whether its reminders wait until somebody is there. */
|
||||
private _renderPlace(L: string) {
|
||||
const missing = !!this._place && !this.hass?.states?.[this._place];
|
||||
return html`
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${{ place: this._place || undefined }}
|
||||
.schema=${[{ name: "place", selector: { entity: { domain: "zone" } } }]}
|
||||
.computeLabel=${() => t("place_optional", L)}
|
||||
@value-changed=${(e: CustomEvent) => {
|
||||
this._place = ((e.detail.value as { place?: string })?.place as string) || "";
|
||||
if (!this._place) this._remindOnSite = false;
|
||||
}}
|
||||
></ha-form>
|
||||
${missing ? html`<div class="place-missing">${t("place_missing", L)}</div>` : nothing}
|
||||
<label class="place-on-site ${this._place ? "" : "disabled"}">
|
||||
<input
|
||||
type="checkbox"
|
||||
.checked=${this._remindOnSite}
|
||||
?disabled=${!this._place}
|
||||
@change=${(e: Event) => (this._remindOnSite = (e.target as HTMLInputElement).checked)}
|
||||
/>
|
||||
<span>${t("remind_on_site", L)}</span>
|
||||
</label>
|
||||
${this._place ? html`<div class="place-hint">${t("remind_on_site_hint", L)}</div>` : nothing}
|
||||
`;
|
||||
}
|
||||
|
||||
private async _save(): Promise<void> {
|
||||
if (this._loading) return; // synchronous re-entry guard (double-click)
|
||||
if (!this._name.trim()) return;
|
||||
@@ -211,6 +249,8 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
notes: this._notes.trim() || null,
|
||||
ha_device_id: this._haDeviceId || null,
|
||||
parent_entry_id: this._parentEntryId || null,
|
||||
// Only with the feature on: switched off, a stored place is kept as is.
|
||||
...(this.placesEnabled ? { place: this._place || null, remind_on_site: !!this._place && this._remindOnSite } : {}),
|
||||
};
|
||||
const res = await runWs<{ device_swap?: DeviceSwap }>(
|
||||
this,
|
||||
@@ -278,6 +318,7 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
@value-changed=${(e: CustomEvent) =>
|
||||
(this._areaId = (e.detail.value as string) || "")}
|
||||
></ha-area-picker>
|
||||
${this.placesEnabled ? this._renderPlace(L) : nothing}
|
||||
<ms-date-field
|
||||
kind="date"
|
||||
clearable
|
||||
@@ -352,6 +393,25 @@ export class MaintenanceObjectDialog extends LitElement {
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
.place-on-site {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: var(--primary-text-color);
|
||||
}
|
||||
.place-on-site.disabled {
|
||||
color: var(--disabled-text-color, var(--secondary-text-color));
|
||||
}
|
||||
.place-hint,
|
||||
.place-missing {
|
||||
font-size: 12px;
|
||||
color: var(--secondary-text-color);
|
||||
margin-top: -4px;
|
||||
}
|
||||
.place-missing {
|
||||
color: var(--warning-color, #c77700);
|
||||
}
|
||||
.dialog-title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
|
||||
@@ -703,6 +703,7 @@ export class MaintenanceSettingsView extends LitElement {
|
||||
{ key: "checklists", settingKey: "advanced_checklists_visible", label: t("feat_checklists", L), desc: t("feat_checklists_desc", L) },
|
||||
{ key: "schedule_time", settingKey: "advanced_schedule_time_visible", label: t("feat_schedule_time", L), desc: t("feat_schedule_time_desc", L) },
|
||||
{ key: "completion_actions", settingKey: "advanced_completion_actions_visible", label: t("feat_completion_actions", L), desc: t("feat_completion_actions_desc", L) },
|
||||
{ key: "places", settingKey: "advanced_places_visible", label: t("feat_places", L), desc: t("feat_places_desc", L) },
|
||||
];
|
||||
|
||||
return html`
|
||||
|
||||
@@ -28,6 +28,7 @@ import type { TriggerType } from "../types";
|
||||
import { REQUIRED_COMPLETION_KEYS, REQUIRED_COMPLETION_LABELS } from "./required-completion-labels";
|
||||
import "./ms-textfield";
|
||||
import { defaultNotifyIcon } from "../helpers/notify-icons";
|
||||
import { primaryTriggerEntity, triggerEntityIds } from "../helpers/trigger-entities";
|
||||
import "./ms-date-field";
|
||||
import "./ms-cost-input";
|
||||
|
||||
@@ -160,7 +161,7 @@ export function applyTypeFields(c: TriggerConfig, d: TriggerTypeFields): void {
|
||||
|
||||
/** Map a persisted compound condition (storage shape) to an editable draft. */
|
||||
function conditionToDraft(c: TriggerConfig): CompoundConditionDraft {
|
||||
const ids = c.entity_ids || (c.entity_id ? [c.entity_id] : []);
|
||||
const ids = triggerEntityIds(c);
|
||||
return {
|
||||
entityIds: ids.join(", "),
|
||||
...typeFieldsFromConfig(c),
|
||||
@@ -617,8 +618,8 @@ export class MaintenanceTaskDialog extends LitElement {
|
||||
// Fleet task) must still hydrate the singular field — the save path
|
||||
// gates on _triggerEntityId and would otherwise NULL the whole trigger
|
||||
// on an unrelated edit (issue #106).
|
||||
this._triggerEntityId = tc.entity_id || (tc.entity_ids && tc.entity_ids[0]) || "";
|
||||
this._triggerEntityIds = tc.entity_ids || (tc.entity_id ? [tc.entity_id] : []);
|
||||
this._triggerEntityId = primaryTriggerEntity(tc) || "";
|
||||
this._triggerEntityIds = triggerEntityIds(tc);
|
||||
this._triggerEntityLogic = tc.entity_logic || "any";
|
||||
this._setTypeFields(typeFieldsFromConfig(tc));
|
||||
this._triggerCombinator = tc.trigger_combinator === "all" ? "all" : "any";
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ export class MaintenanceTaskQuickActionsDialog extends LitElement {
|
||||
@state() private _features: AdvancedFeatures = {
|
||||
adaptive: false, seasonal: false, environmental: false,
|
||||
budget: false, groups: false, checklists: false, schedule_time: false,
|
||||
completion_actions: false,
|
||||
completion_actions: false, places: false,
|
||||
};
|
||||
@state() private _toast = "";
|
||||
private readonly _toastTimer = new ToastTimer();
|
||||
|
||||
@@ -129,9 +129,19 @@ export function openCreateObjectDialog(): boolean {
|
||||
if (!syncHass(dlg)) return false;
|
||||
// openCreate is defined on MaintenanceObjectDialog
|
||||
dlg.openCreate();
|
||||
void applyObjectDialogSettings(dlg);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 2026-10 places: the object dialog shows its place fields by the same
|
||||
* feature switch as in the panel. Opened at once; the fields appear when
|
||||
* the (page-wide cached) settings are in. */
|
||||
async function applyObjectDialogSettings(dlg: MaintenanceObjectDialog): Promise<void> {
|
||||
const hass = getHass();
|
||||
if (!hass) return;
|
||||
dlg.placesEnabled = (await fetchSettingsOnce(hass)).features.places;
|
||||
}
|
||||
|
||||
export function openEditObjectDialog(
|
||||
entryId: string,
|
||||
obj: MaintenanceObject,
|
||||
@@ -139,6 +149,7 @@ export function openEditObjectDialog(
|
||||
const dlg = getOrCreate<MaintenanceObjectDialog>(OBJECT_DIALOG_TAG);
|
||||
if (!syncHass(dlg)) return false;
|
||||
dlg.openEdit(entryId, obj);
|
||||
void applyObjectDialogSettings(dlg);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Zatím žádné objekty.",
|
||||
"action_error": "Akce se nezdařila. Zkuste to znovu.",
|
||||
"area_id_optional": "Oblast (volitelná)",
|
||||
"place_optional": "Místo (zóna, volitelné)",
|
||||
"remind_on_site": "Připomínat jen, když tam někdo je",
|
||||
"remind_on_site_hint": "Připomínky čekají, dokud někdo nebude v této zóně. Kdo tam přijede, dostane zprávu s tím, co je potřeba udělat.",
|
||||
"place_missing": "Zóna nenalezena: připomínky jako doma",
|
||||
"place_home": "Domov",
|
||||
"installation_date_optional": "Datum instalace (volitelné)",
|
||||
"warranty_expiry_optional": "Konec záruky (volitelné)",
|
||||
"warranty": "Záruka",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Vlastník",
|
||||
"feat_completion_actions": "Akce při dokončení",
|
||||
"feat_completion_actions_desc": "Akce HA na úlohu při dokončení + QR rychlého dokončení s předvolenými hodnotami.",
|
||||
"feat_places": "Místa",
|
||||
"feat_places_desc": "Objekty udržované na jiném místě (zóna Home Assistantu): připomínky jen když tam někdo je a zpráva při příjezdu.",
|
||||
"on_complete_action_title": "Při dokončení: spustit akci HA (volitelné)",
|
||||
"on_complete_action_desc": "Volá službu HA, když je úloha dokončena — např. resetuje čítač na zařízení.",
|
||||
"on_complete_action_target": "Cílová entita",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Používá díl: {name}",
|
||||
"label_filter": "Štítek",
|
||||
"all_labels": "Všechny štítky",
|
||||
"filter_place": "Místo",
|
||||
"filter_place_all": "Všechna místa",
|
||||
"settings_notify_scope": "Upozorňovat jen pro zobrazení",
|
||||
"settings_notify_scope_all": "Všechny úkoly",
|
||||
"settings_notify_scope_hint": "Připomenutí posílají jen úkoly odpovídající filtrům štítku/uživatele zvoleného zobrazení. Stav, řazení a seskupení zobrazení se zde ignorují.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ingen objekter endnu.",
|
||||
"action_error": "Handlingen mislykkedes. Prøv igen.",
|
||||
"area_id_optional": "Område (valgfrit)",
|
||||
"place_optional": "Sted (zone, valgfrit)",
|
||||
"remind_on_site": "Påmind kun, når nogen er der",
|
||||
"remind_on_site_hint": "Påmindelser venter, til nogen er i denne zone. Den, der ankommer, får en besked med det, der skal gøres.",
|
||||
"place_missing": "Zone ikke fundet: påmindelser som hjemme",
|
||||
"place_home": "Hjemme",
|
||||
"installation_date_optional": "Installationsdato (valgfrit)",
|
||||
"warranty_expiry_optional": "Garantiens udløb (valgfrit)",
|
||||
"warranty": "Garanti",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Ejer",
|
||||
"feat_completion_actions": "Fuldførelseshandlinger",
|
||||
"feat_completion_actions_desc": "HA-handling pr. opgave ved fuldførelse + hurtig-fuldfør-QR med forudindstillede værdier.",
|
||||
"feat_places": "Steder",
|
||||
"feat_places_desc": "Objekter, der vedligeholdes et andet sted (en Home Assistant-zone): påmindelser kun når nogen er der, og en besked ved ankomst.",
|
||||
"on_complete_action_title": "Ved fuldførelse: udløs HA-handling (valgfrit)",
|
||||
"on_complete_action_desc": "Kalder en HA-tjeneste, når opgaven fuldføres — f.eks. nulstil en tæller på enheden.",
|
||||
"on_complete_action_target": "Målenhed",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Bruger reservedel: {name}",
|
||||
"label_filter": "Etiket",
|
||||
"all_labels": "Alle etiketter",
|
||||
"filter_place": "Sted",
|
||||
"filter_place_all": "Alle steder",
|
||||
"settings_notify_scope": "Underret kun for visning",
|
||||
"settings_notify_scope_all": "Alle opgaver",
|
||||
"settings_notify_scope_hint": "Kun opgaver, der matcher den valgte visnings etiket-/brugerfiltre, sender påmindelser. Visningens status, sortering og gruppering ignoreres her.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Keine Objekte vorhanden.",
|
||||
"action_error": "Aktion fehlgeschlagen. Bitte erneut versuchen.",
|
||||
"area_id_optional": "Bereich (optional)",
|
||||
"place_optional": "Ort (Zone, optional)",
|
||||
"remind_on_site": "Nur erinnern, wenn jemand dort ist",
|
||||
"remind_on_site_hint": "Erinnerungen warten, bis jemand in dieser Zone ist. Wer dort ankommt, bekommt eine Nachricht mit dem, was fällig ist.",
|
||||
"place_missing": "Zone nicht gefunden: Erinnerungen wie zuhause",
|
||||
"place_home": "Zuhause",
|
||||
"installation_date_optional": "Installationsdatum (optional)",
|
||||
"warranty_expiry_optional": "Garantie-Ablauf (optional)",
|
||||
"warranty": "Garantie",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Besitzer",
|
||||
"feat_completion_actions": "Completion-Actions",
|
||||
"feat_completion_actions_desc": "Pro Aufgabe HA-Action beim Abschluss konfigurieren + Quick-Complete-QR mit voreingestellten Werten.",
|
||||
"feat_places": "Orte",
|
||||
"feat_places_desc": "Objekte an einem anderen Ort (eine Home-Assistant-Zone): Erinnerungen nur, wenn jemand dort ist, und eine Nachricht bei Ankunft.",
|
||||
"on_complete_action_title": "Beim Abschluss: HA-Action auslösen (optional)",
|
||||
"on_complete_action_desc": "Ruft beim Erledigen der Aufgabe einen HA-Service auf — z. B. einen Zähler am Gerät zurücksetzen.",
|
||||
"on_complete_action_target": "Ziel-Entität",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Nutzt Ersatzteil: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "Alle Labels",
|
||||
"filter_place": "Ort",
|
||||
"filter_place_all": "Alle Orte",
|
||||
"settings_notify_scope": "Nur benachrichtigen für Ansicht",
|
||||
"settings_notify_scope_all": "Alle Aufgaben",
|
||||
"settings_notify_scope_hint": "Nur Aufgaben, die zu den Label-/Nutzer-Filtern der gewählten Ansicht passen, senden Erinnerungen. Status, Sortierung und Gruppierung der Ansicht werden hier ignoriert.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "No objects yet.",
|
||||
"action_error": "Action failed. Please try again.",
|
||||
"area_id_optional": "Area (optional)",
|
||||
"place_optional": "Place (zone, optional)",
|
||||
"remind_on_site": "Remind only while somebody is there",
|
||||
"remind_on_site_hint": "Reminders wait until somebody is in this zone. Whoever arrives there gets a message with what is due.",
|
||||
"place_missing": "Zone not found: reminders as at home",
|
||||
"place_home": "Home",
|
||||
"installation_date_optional": "Installation date (optional)",
|
||||
"warranty_expiry_optional": "Warranty expiry (optional)",
|
||||
"warranty": "Warranty",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Owner",
|
||||
"feat_completion_actions": "Completion actions",
|
||||
"feat_completion_actions_desc": "Per-task HA action on complete + quick-complete QR with pre-set values.",
|
||||
"feat_places": "Places",
|
||||
"feat_places_desc": "Objects maintained at another place (a Home Assistant zone): reminders only while somebody is there, and a message on arrival.",
|
||||
"on_complete_action_title": "On complete: trigger HA action (optional)",
|
||||
"on_complete_action_desc": "Calls an HA service when the task is completed — e.g. reset a counter on the device.",
|
||||
"on_complete_action_target": "Target entity",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Uses part: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "All labels",
|
||||
"filter_place": "Place",
|
||||
"filter_place_all": "All places",
|
||||
"settings_notify_scope": "Notify only for view",
|
||||
"settings_notify_scope_all": "All tasks",
|
||||
"settings_notify_scope_hint": "Only tasks matching the selected saved view's label/user filters send reminders. Status, sorting and grouping of the view are ignored here.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Aún no hay objetos.",
|
||||
"action_error": "Acción fallida. Inténtelo de nuevo.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Lugar (zona, opcional)",
|
||||
"remind_on_site": "Recordar solo cuando alguien esté allí",
|
||||
"remind_on_site_hint": "Los recordatorios esperan a que alguien esté en esta zona. Quien llega allí recibe un mensaje con lo pendiente.",
|
||||
"place_missing": "Zona no encontrada: recordatorios como en casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Fecha de instalación (opcional)",
|
||||
"warranty_expiry_optional": "Vencimiento de garantía (opcional)",
|
||||
"warranty": "Garantía",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Propietario",
|
||||
"feat_completion_actions": "Acciones de finalización",
|
||||
"feat_completion_actions_desc": "Acción HA por tarea al completar + QR de finalización rápida con valores prefijados.",
|
||||
"feat_places": "Lugares",
|
||||
"feat_places_desc": "Objetos mantenidos en otro lugar (una zona de Home Assistant): recordatorios solo cuando alguien está allí y un mensaje al llegar.",
|
||||
"on_complete_action_title": "Al completar: ejecutar acción HA (opcional)",
|
||||
"on_complete_action_desc": "Llama un servicio HA cuando se completa la tarea — p. ej. reiniciar un contador del dispositivo.",
|
||||
"on_complete_action_target": "Entidad objetivo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa la pieza: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas las etiquetas",
|
||||
"filter_place": "Lugar",
|
||||
"filter_place_all": "Todos los lugares",
|
||||
"settings_notify_scope": "Notificar solo para la vista",
|
||||
"settings_notify_scope_all": "Todas las tareas",
|
||||
"settings_notify_scope_hint": "Solo las tareas que coinciden con los filtros de etiqueta/usuario de la vista seleccionada envían recordatorios. El estado, el orden y la agrupación de la vista se ignoran aquí.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ei vielä kohteita.",
|
||||
"action_error": "Toiminto epäonnistui. Yritä uudelleen.",
|
||||
"area_id_optional": "Alue (valinnainen)",
|
||||
"place_optional": "Paikka (vyöhyke, valinnainen)",
|
||||
"remind_on_site": "Muistuta vain, kun joku on paikalla",
|
||||
"remind_on_site_hint": "Muistutukset odottavat, kunnes joku on tällä vyöhykkeellä. Sinne saapuva saa viestin tehtävistä asioista.",
|
||||
"place_missing": "Vyöhykettä ei löydy: muistutukset kuin kotona",
|
||||
"place_home": "Koti",
|
||||
"installation_date_optional": "Asennuspäivä (valinnainen)",
|
||||
"warranty_expiry_optional": "Takuun päättyminen (valinnainen)",
|
||||
"warranty": "Takuu",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Omistaja",
|
||||
"feat_completion_actions": "Suoritustoiminnot",
|
||||
"feat_completion_actions_desc": "Tehtäväkohtainen HA-toiminto suorituksen yhteydessä + pikasuoritus-QR esiasetetuilla arvoilla.",
|
||||
"feat_places": "Paikat",
|
||||
"feat_places_desc": "Toisessa paikassa (Home Assistant -vyöhyke) huollettavat kohteet: muistutukset vain, kun joku on paikalla, ja viesti saavuttaessa.",
|
||||
"on_complete_action_title": "Suorituksen yhteydessä: laukaise HA-toiminto (valinnainen)",
|
||||
"on_complete_action_desc": "Kutsuu HA-palvelua, kun tehtävä suoritetaan — esim. nollaa laitteen laskuri.",
|
||||
"on_complete_action_target": "Kohde-entiteetti",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Käyttää varaosaa: {name}",
|
||||
"label_filter": "Tunniste",
|
||||
"all_labels": "Kaikki tunnisteet",
|
||||
"filter_place": "Paikka",
|
||||
"filter_place_all": "Kaikki paikat",
|
||||
"settings_notify_scope": "Ilmoita vain näkymälle",
|
||||
"settings_notify_scope_all": "Kaikki tehtävät",
|
||||
"settings_notify_scope_hint": "Vain valitun näkymän tunniste-/käyttäjäsuodattimiin osuvat tehtävät lähettävät muistutuksia. Näkymän tila, lajittelu ja ryhmittely ohitetaan tässä.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Aucun objet pour l'instant.",
|
||||
"action_error": "Action échouée. Veuillez réessayer.",
|
||||
"area_id_optional": "Zone (optionnel)",
|
||||
"place_optional": "Lieu (zone, facultatif)",
|
||||
"remind_on_site": "Rappeler seulement quand quelqu'un y est",
|
||||
"remind_on_site_hint": "Les rappels attendent que quelqu'un soit dans cette zone. Qui y arrive reçoit un message avec ce qui est à faire.",
|
||||
"place_missing": "Zone introuvable : rappels comme à la maison",
|
||||
"place_home": "Domicile",
|
||||
"installation_date_optional": "Date d'installation (optionnel)",
|
||||
"warranty_expiry_optional": "Fin de garantie (optionnel)",
|
||||
"warranty": "Garantie",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Propriétaire",
|
||||
"feat_completion_actions": "Actions de finalisation",
|
||||
"feat_completion_actions_desc": "Action HA par tâche lors de la finalisation + QR de finalisation rapide avec valeurs pré-définies.",
|
||||
"feat_places": "Lieux",
|
||||
"feat_places_desc": "Objets entretenus à un autre endroit (une zone Home Assistant) : rappels seulement quand quelqu'un y est, et un message à l'arrivée.",
|
||||
"on_complete_action_title": "À la finalisation : déclencher une action HA (optionnel)",
|
||||
"on_complete_action_desc": "Appelle un service HA quand la tâche est terminée — p. ex. réinitialiser un compteur sur l'appareil.",
|
||||
"on_complete_action_target": "Entité cible",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Utilise la pièce : {name}",
|
||||
"label_filter": "Étiquette",
|
||||
"all_labels": "Toutes les étiquettes",
|
||||
"filter_place": "Lieu",
|
||||
"filter_place_all": "Tous les lieux",
|
||||
"settings_notify_scope": "Notifier uniquement pour la vue",
|
||||
"settings_notify_scope_all": "Toutes les tâches",
|
||||
"settings_notify_scope_hint": "Seules les tâches correspondant aux filtres étiquette/utilisateur de la vue choisie envoient des rappels. Le statut, le tri et le regroupement de la vue sont ignorés ici.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "अभी कोई वस्तु नहीं।",
|
||||
"action_error": "क्रिया विफल। कृपया पुनः प्रयास करें।",
|
||||
"area_id_optional": "क्षेत्र (वैकल्पिक)",
|
||||
"place_optional": "स्थान (ज़ोन, वैकल्पिक)",
|
||||
"remind_on_site": "केवल तब याद दिलाएँ जब कोई वहाँ हो",
|
||||
"remind_on_site_hint": "रिमाइंडर तब तक रुकते हैं जब तक कोई इस ज़ोन में न हो। वहाँ पहुँचने वाले को बाकी कामों का संदेश मिलता है।",
|
||||
"place_missing": "ज़ोन नहीं मिला: रिमाइंडर घर जैसे",
|
||||
"place_home": "घर",
|
||||
"installation_date_optional": "स्थापना तिथि (वैकल्पिक)",
|
||||
"warranty_expiry_optional": "वारंटी समाप्ति (वैकल्पिक)",
|
||||
"warranty": "वारंटी",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "स्वामी",
|
||||
"feat_completion_actions": "पूर्णता क्रियाएँ",
|
||||
"feat_completion_actions_desc": "पूर्ण होने पर प्रति-कार्य HA क्रिया + पूर्व-निर्धारित मानों के साथ त्वरित-पूर्ण QR।",
|
||||
"feat_places": "स्थान",
|
||||
"feat_places_desc": "किसी दूसरी जगह (Home Assistant ज़ोन) पर रखरखाव वाले ऑब्जेक्ट: रिमाइंडर तभी जब कोई वहाँ हो, और पहुँचने पर एक संदेश।",
|
||||
"on_complete_action_title": "पूर्ण होने पर: HA क्रिया ट्रिगर करें (वैकल्पिक)",
|
||||
"on_complete_action_desc": "कार्य पूर्ण होने पर एक HA सेवा कॉल करता है — उदा. डिवाइस पर काउंटर रीसेट करना।",
|
||||
"on_complete_action_target": "लक्ष्य एंटिटी",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "पुर्ज़ा उपयोग करता है: {name}",
|
||||
"label_filter": "लेबल",
|
||||
"all_labels": "सभी लेबल",
|
||||
"filter_place": "स्थान",
|
||||
"filter_place_all": "सभी स्थान",
|
||||
"settings_notify_scope": "केवल इस व्यू के लिए सूचित करें",
|
||||
"settings_notify_scope_all": "सभी कार्य",
|
||||
"settings_notify_scope_hint": "केवल वे कार्य अनुस्मारक भेजते हैं जो चुने गए व्यू के लेबल/उपयोगकर्ता फ़िल्टर से मेल खाते हैं। व्यू की स्थिति, क्रम और समूहन यहाँ अनदेखे रहते हैं।",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Még nincsenek objektumok.",
|
||||
"action_error": "A művelet nem sikerült. Próbálja újra.",
|
||||
"area_id_optional": "Terület (opcionális)",
|
||||
"place_optional": "Helyszín (zóna, opcionális)",
|
||||
"remind_on_site": "Csak akkor emlékeztessen, ha valaki ott van",
|
||||
"remind_on_site_hint": "Az emlékeztetők megvárják, amíg valaki ebben a zónában lesz. Aki odaér, üzenetet kap az esedékes teendőkről.",
|
||||
"place_missing": "A zóna nem található: emlékeztetők, mint otthon",
|
||||
"place_home": "Otthon",
|
||||
"installation_date_optional": "Telepítés dátuma (opcionális)",
|
||||
"warranty_expiry_optional": "Garancia lejárta (opcionális)",
|
||||
"warranty": "Garancia",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Tulajdonos",
|
||||
"feat_completion_actions": "Elvégzési műveletek",
|
||||
"feat_completion_actions_desc": "Feladatonkénti HA művelet elvégzéskor + gyorselvégző QR előre beállított értékekkel.",
|
||||
"feat_places": "Helyszínek",
|
||||
"feat_places_desc": "Másik helyszínen (Home Assistant-zóna) karbantartott objektumok: emlékeztető csak akkor, ha valaki ott van, és üzenet érkezéskor.",
|
||||
"on_complete_action_title": "Elvégzéskor: HA művelet indítása (opcionális)",
|
||||
"on_complete_action_desc": "HA szolgáltatást hív meg a feladat elvégzésekor — pl. számláló nullázása az eszközön.",
|
||||
"on_complete_action_target": "Cél entitás",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Alkatrészt használ: {name}",
|
||||
"label_filter": "Címke",
|
||||
"all_labels": "Minden címke",
|
||||
"filter_place": "Helyszín",
|
||||
"filter_place_all": "Minden helyszín",
|
||||
"settings_notify_scope": "Értesítés csak erre a nézetre",
|
||||
"settings_notify_scope_all": "Minden feladat",
|
||||
"settings_notify_scope_hint": "Csak a kiválasztott mentett nézet címke-/felhasználószűrőinek megfelelő feladatok küldenek emlékeztetőt. A nézet állapot-, rendezési és csoportosítási beállításait itt figyelmen kívül hagyjuk.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Nessun oggetto ancora.",
|
||||
"action_error": "Azione fallita. Riprova.",
|
||||
"area_id_optional": "Area (opzionale)",
|
||||
"place_optional": "Luogo (zona, facoltativo)",
|
||||
"remind_on_site": "Ricorda solo quando qualcuno è lì",
|
||||
"remind_on_site_hint": "I promemoria aspettano che qualcuno sia in questa zona. Chi arriva lì riceve un messaggio con ciò che è da fare.",
|
||||
"place_missing": "Zona non trovata: promemoria come a casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data di installazione (opzionale)",
|
||||
"warranty_expiry_optional": "Scadenza garanzia (opzionale)",
|
||||
"warranty": "Garanzia",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Proprietario",
|
||||
"feat_completion_actions": "Azioni di completamento",
|
||||
"feat_completion_actions_desc": "Azione HA per attività al completamento + QR completamento rapido con valori predefiniti.",
|
||||
"feat_places": "Luoghi",
|
||||
"feat_places_desc": "Oggetti curati in un altro luogo (una zona di Home Assistant): promemoria solo quando qualcuno è lì e un messaggio all'arrivo.",
|
||||
"on_complete_action_title": "Al completamento: attiva azione HA (opzionale)",
|
||||
"on_complete_action_desc": "Chiama un servizio HA quando l'attività viene completata — es. azzerare un contatore sul dispositivo.",
|
||||
"on_complete_action_target": "Entità target",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa il ricambio: {name}",
|
||||
"label_filter": "Etichetta",
|
||||
"all_labels": "Tutte le etichette",
|
||||
"filter_place": "Luogo",
|
||||
"filter_place_all": "Tutti i luoghi",
|
||||
"settings_notify_scope": "Notifica solo per la vista",
|
||||
"settings_notify_scope_all": "Tutte le attività",
|
||||
"settings_notify_scope_hint": "Solo le attività che corrispondono ai filtri etichetta/utente della vista scelta inviano promemoria. Stato, ordinamento e raggruppamento della vista qui vengono ignorati.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "対象がまだありません。",
|
||||
"action_error": "操作に失敗しました。もう一度お試しください。",
|
||||
"area_id_optional": "エリア(任意)",
|
||||
"place_optional": "場所(ゾーン、任意)",
|
||||
"remind_on_site": "誰かがいるときだけリマインド",
|
||||
"remind_on_site_hint": "リマインドは誰かがこのゾーンにいるまで待機します。到着した人には、やるべきことをまとめたメッセージが届きます。",
|
||||
"place_missing": "ゾーンが見つかりません:自宅と同じようにリマインドします",
|
||||
"place_home": "自宅",
|
||||
"installation_date_optional": "設置日(任意)",
|
||||
"warranty_expiry_optional": "保証期限(任意)",
|
||||
"warranty": "保証",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "オーナー",
|
||||
"feat_completion_actions": "完了時アクション",
|
||||
"feat_completion_actions_desc": "タスクごとの完了時HAアクション+事前設定値付きのクイック完了QR。",
|
||||
"feat_places": "場所",
|
||||
"feat_places_desc": "別の場所(Home Assistant のゾーン)で管理するオブジェクト:誰かがその場にいるときだけリマインドし、到着時に通知します。",
|
||||
"on_complete_action_title": "完了時: HAアクションを実行(任意)",
|
||||
"on_complete_action_desc": "タスク完了時にHAサービスを呼び出します — 例: デバイスのカウンターをリセット。",
|
||||
"on_complete_action_target": "対象エンティティ",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "使用する部品: {name}",
|
||||
"label_filter": "ラベル",
|
||||
"all_labels": "すべてのラベル",
|
||||
"filter_place": "場所",
|
||||
"filter_place_all": "すべての場所",
|
||||
"settings_notify_scope": "このビューのみ通知",
|
||||
"settings_notify_scope_all": "すべてのタスク",
|
||||
"settings_notify_scope_hint": "選択した保存済みビューのラベル/ユーザーフィルターに一致するタスクのみがリマインダーを送信します。ビューのステータス・並び順・グループ化はここでは無視されます。",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "아직 객체가 없습니다.",
|
||||
"action_error": "동작에 실패했습니다. 다시 시도해 주세요.",
|
||||
"area_id_optional": "구역 (선택)",
|
||||
"place_optional": "장소 (구역, 선택 사항)",
|
||||
"remind_on_site": "누군가 있을 때만 알림",
|
||||
"remind_on_site_hint": "누군가 이 구역에 있을 때까지 알림이 대기합니다. 그곳에 도착한 사람은 해야 할 일을 담은 메시지를 받습니다.",
|
||||
"place_missing": "구역을 찾을 수 없음: 집과 같이 알림",
|
||||
"place_home": "집",
|
||||
"installation_date_optional": "설치일 (선택)",
|
||||
"warranty_expiry_optional": "보증 만료일 (선택)",
|
||||
"warranty": "보증",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "소유자",
|
||||
"feat_completion_actions": "완료 동작",
|
||||
"feat_completion_actions_desc": "완료 시 작업별 HA 동작 실행 + 사전 설정값이 있는 빠른 완료 QR.",
|
||||
"feat_places": "장소",
|
||||
"feat_places_desc": "다른 장소(Home Assistant 구역)에서 관리하는 개체: 누군가 그곳에 있을 때만 알림을 보내고, 도착하면 메시지를 보냅니다.",
|
||||
"on_complete_action_title": "완료 시: HA 동작 실행 (선택)",
|
||||
"on_complete_action_desc": "작업이 완료되면 HA 서비스를 호출합니다 — 예: 기기의 카운터 초기화.",
|
||||
"on_complete_action_target": "대상 엔티티",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "사용 부품: {name}",
|
||||
"label_filter": "라벨",
|
||||
"all_labels": "모든 라벨",
|
||||
"filter_place": "장소",
|
||||
"filter_place_all": "모든 장소",
|
||||
"settings_notify_scope": "특정 보기만 알림",
|
||||
"settings_notify_scope_all": "모든 작업",
|
||||
"settings_notify_scope_hint": "선택한 저장된 보기의 라벨/사용자 필터와 일치하는 작업만 알림을 보냅니다. 보기의 상태·정렬·그룹화는 여기서 무시됩니다.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ingen objekter ennå.",
|
||||
"action_error": "Handlingen mislyktes. Prøv igjen.",
|
||||
"area_id_optional": "Område (valgfritt)",
|
||||
"place_optional": "Sted (sone, valgfritt)",
|
||||
"remind_on_site": "Påminn bare når noen er der",
|
||||
"remind_on_site_hint": "Påminnelser venter til noen er i denne sonen. Den som kommer dit, får en melding med det som skal gjøres.",
|
||||
"place_missing": "Fant ikke sonen: påminnelser som hjemme",
|
||||
"place_home": "Hjemme",
|
||||
"installation_date_optional": "Installasjonsdato (valgfritt)",
|
||||
"warranty_expiry_optional": "Garanti utløper (valgfritt)",
|
||||
"warranty": "Garanti",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Eier",
|
||||
"feat_completion_actions": "Fullføringshandlinger",
|
||||
"feat_completion_actions_desc": "HA-handling per oppgave ved fullføring + hurtigfullføring med QR og forhåndsinnstilte verdier.",
|
||||
"feat_places": "Steder",
|
||||
"feat_places_desc": "Objekter som vedlikeholdes et annet sted (en Home Assistant-sone): påminnelser bare når noen er der, og en melding ved ankomst.",
|
||||
"on_complete_action_title": "Ved fullføring: utløs HA-handling (valgfritt)",
|
||||
"on_complete_action_desc": "Kaller en HA-tjeneste når oppgaven fullføres — f.eks. tilbakestille en teller på enheten.",
|
||||
"on_complete_action_target": "Målentitet",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Bruker del: {name}",
|
||||
"label_filter": "Etikett",
|
||||
"all_labels": "Alle etiketter",
|
||||
"filter_place": "Sted",
|
||||
"filter_place_all": "Alle steder",
|
||||
"settings_notify_scope": "Varsle kun for visning",
|
||||
"settings_notify_scope_all": "Alle oppgaver",
|
||||
"settings_notify_scope_hint": "Bare oppgaver som matcher etikett-/brukerfiltrene til valgt visning sender påminnelser. Visningens status, sortering og gruppering ignoreres her.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Nog geen objecten.",
|
||||
"action_error": "Actie mislukt. Probeer het opnieuw.",
|
||||
"area_id_optional": "Gebied (optioneel)",
|
||||
"place_optional": "Locatie (zone, optioneel)",
|
||||
"remind_on_site": "Alleen herinneren als er iemand is",
|
||||
"remind_on_site_hint": "Herinneringen wachten tot iemand in deze zone is. Wie daar aankomt, krijgt een bericht met wat er te doen is.",
|
||||
"place_missing": "Zone niet gevonden: herinneringen zoals thuis",
|
||||
"place_home": "Thuis",
|
||||
"installation_date_optional": "Installatiedatum (optioneel)",
|
||||
"warranty_expiry_optional": "Garantie verloopt (optioneel)",
|
||||
"warranty": "Garantie",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Eigenaar",
|
||||
"feat_completion_actions": "Voltooiings-acties",
|
||||
"feat_completion_actions_desc": "Per taak HA-actie bij voltooien + snel-voltooien-QR met vooraf ingestelde waarden.",
|
||||
"feat_places": "Locaties",
|
||||
"feat_places_desc": "Objecten op een andere locatie (een Home Assistant-zone): herinneringen alleen als er iemand is, en een bericht bij aankomst.",
|
||||
"on_complete_action_title": "Bij voltooien: HA-actie uitvoeren (optioneel)",
|
||||
"on_complete_action_desc": "Roept een HA-service aan wanneer de taak is voltooid — bv. een teller op het apparaat resetten.",
|
||||
"on_complete_action_target": "Doel-entiteit",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Gebruikt onderdeel: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "Alle labels",
|
||||
"filter_place": "Locatie",
|
||||
"filter_place_all": "Alle locaties",
|
||||
"settings_notify_scope": "Alleen melden voor weergave",
|
||||
"settings_notify_scope_all": "Alle taken",
|
||||
"settings_notify_scope_hint": "Alleen taken die overeenkomen met de label-/gebruikersfilters van de gekozen weergave sturen herinneringen. Status, sortering en groepering van de weergave worden hier genegeerd.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Brak obiektów.",
|
||||
"action_error": "Akcja nie powiodła się. Spróbuj ponownie.",
|
||||
"area_id_optional": "Obszar (opcjonalny)",
|
||||
"place_optional": "Miejsce (strefa, opcjonalnie)",
|
||||
"remind_on_site": "Przypominaj tylko, gdy ktoś tam jest",
|
||||
"remind_on_site_hint": "Przypomnienia czekają, aż ktoś będzie w tej strefie. Kto tam przyjedzie, dostaje wiadomość z tym, co jest do zrobienia.",
|
||||
"place_missing": "Nie znaleziono strefy: przypomnienia jak w domu",
|
||||
"place_home": "Dom",
|
||||
"installation_date_optional": "Data instalacji (opcjonalna)",
|
||||
"warranty_expiry_optional": "Wygaśnięcie gwarancji (opcjonalnie)",
|
||||
"warranty": "Gwarancja",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Właściciel",
|
||||
"feat_completion_actions": "Akcje po zakończeniu",
|
||||
"feat_completion_actions_desc": "Akcja HA per zadanie po zakończeniu + QR szybkiego zakończenia z predefiniowanymi wartościami.",
|
||||
"feat_places": "Miejsca",
|
||||
"feat_places_desc": "Obiekty w innym miejscu (strefa Home Assistant): przypomnienia tylko wtedy, gdy ktoś tam jest, i wiadomość po przybyciu.",
|
||||
"on_complete_action_title": "Po zakończeniu: wywołaj akcję HA (opcjonalnie)",
|
||||
"on_complete_action_desc": "Wywołuje usługę HA po zakończeniu zadania — np. zresetuj licznik urządzenia.",
|
||||
"on_complete_action_target": "Encja docelowa",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Używa części: {name}",
|
||||
"label_filter": "Etykieta",
|
||||
"all_labels": "Wszystkie etykiety",
|
||||
"filter_place": "Miejsce",
|
||||
"filter_place_all": "Wszystkie miejsca",
|
||||
"settings_notify_scope": "Powiadamiaj tylko dla widoku",
|
||||
"settings_notify_scope_all": "Wszystkie zadania",
|
||||
"settings_notify_scope_hint": "Przypomnienia wysyłają tylko zadania pasujące do filtrów etykiety/użytkownika wybranego widoku. Status, sortowanie i grupowanie widoku są tu ignorowane.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ainda não há objetos.",
|
||||
"action_error": "A ação falhou. Tente novamente.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Local (zona, opcional)",
|
||||
"remind_on_site": "Lembrar só quando alguém estiver lá",
|
||||
"remind_on_site_hint": "Os lembretes esperam até alguém estar nesta zona. Quem chega lá recebe uma mensagem com o que está pendente.",
|
||||
"place_missing": "Zona não encontrada: lembretes como em casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data de instalação (opcional)",
|
||||
"warranty_expiry_optional": "Fim da garantia (opcional)",
|
||||
"warranty": "Garantia",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Proprietário",
|
||||
"feat_completion_actions": "Ações de conclusão",
|
||||
"feat_completion_actions_desc": "Ação do HA por tarefa ao concluir + QR de conclusão rápida com valores predefinidos.",
|
||||
"feat_places": "Locais",
|
||||
"feat_places_desc": "Objetos mantidos em outro local (uma zona do Home Assistant): lembretes só quando alguém está lá e uma mensagem na chegada.",
|
||||
"on_complete_action_title": "Ao concluir: acionar ação do HA (opcional)",
|
||||
"on_complete_action_desc": "Chama um serviço do HA quando a tarefa é concluída — ex.: zerar um contador no dispositivo.",
|
||||
"on_complete_action_target": "Entidade alvo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa a peça: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas as etiquetas",
|
||||
"filter_place": "Local",
|
||||
"filter_place_all": "Todos os locais",
|
||||
"settings_notify_scope": "Notificar apenas para a visualização",
|
||||
"settings_notify_scope_all": "Todas as tarefas",
|
||||
"settings_notify_scope_hint": "Apenas tarefas que correspondem aos filtros de etiqueta/usuário da visualização salva selecionada enviam lembretes. Status, ordenação e agrupamento da visualização são ignorados aqui.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Ainda sem objetos.",
|
||||
"action_error": "Ação falhada. Tente novamente.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Local (zona, opcional)",
|
||||
"remind_on_site": "Lembrar só quando alguém lá estiver",
|
||||
"remind_on_site_hint": "Os lembretes esperam até alguém estar nesta zona. Quem lá chega recebe uma mensagem com o que está pendente.",
|
||||
"place_missing": "Zona não encontrada: lembretes como em casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data de instalação (opcional)",
|
||||
"warranty_expiry_optional": "Validade da garantia (opcional)",
|
||||
"warranty": "Garantia",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Proprietário",
|
||||
"feat_completion_actions": "Ações de conclusão",
|
||||
"feat_completion_actions_desc": "Ação HA por tarefa ao concluir + QR de conclusão rápida com valores predefinidos.",
|
||||
"feat_places": "Locais",
|
||||
"feat_places_desc": "Objetos mantidos noutro local (uma zona do Home Assistant): lembretes só quando alguém lá está e uma mensagem à chegada.",
|
||||
"on_complete_action_title": "Na conclusão: acionar ação HA (opcional)",
|
||||
"on_complete_action_desc": "Chama um serviço HA quando a tarefa é concluída — p. ex. reiniciar um contador no dispositivo.",
|
||||
"on_complete_action_target": "Entidade alvo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa a peça: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas as etiquetas",
|
||||
"filter_place": "Local",
|
||||
"filter_place_all": "Todos os locais",
|
||||
"settings_notify_scope": "Notificar apenas para a vista",
|
||||
"settings_notify_scope_all": "Todas as tarefas",
|
||||
"settings_notify_scope_hint": "Apenas as tarefas que correspondem aos filtros de etiqueta/utilizador da vista escolhida enviam lembretes. O estado, a ordenação e o agrupamento da vista são ignorados aqui.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Пока нет объектов.",
|
||||
"action_error": "Не удалось выполнить действие. Попробуйте ещё раз.",
|
||||
"area_id_optional": "Зона (опционально)",
|
||||
"place_optional": "Место (зона, необязательно)",
|
||||
"remind_on_site": "Напоминать, только когда там кто-то есть",
|
||||
"remind_on_site_hint": "Напоминания ждут, пока кто-нибудь окажется в этой зоне. Кто туда приезжает, получает сообщение о том, что нужно сделать.",
|
||||
"place_missing": "Зона не найдена: напоминания как дома",
|
||||
"place_home": "Дом",
|
||||
"installation_date_optional": "Дата установки (опционально)",
|
||||
"warranty_expiry_optional": "Окончание гарантии (опционально)",
|
||||
"warranty": "Гарантия",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Владелец",
|
||||
"feat_completion_actions": "Действия при завершении",
|
||||
"feat_completion_actions_desc": "HA-действие по задаче при завершении + QR быстрого завершения с предустановленными значениями.",
|
||||
"feat_places": "Места",
|
||||
"feat_places_desc": "Объекты в другом месте (зона Home Assistant): напоминания только когда там кто-то есть, и сообщение по прибытии.",
|
||||
"on_complete_action_title": "При завершении: запустить HA-действие (опционально)",
|
||||
"on_complete_action_desc": "Вызывает HA-сервис при завершении задачи — напр., сбросить счётчик на устройстве.",
|
||||
"on_complete_action_target": "Целевая сущность",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Использует деталь: {name}",
|
||||
"label_filter": "Метка",
|
||||
"all_labels": "Все метки",
|
||||
"filter_place": "Место",
|
||||
"filter_place_all": "Все места",
|
||||
"settings_notify_scope": "Уведомлять только для представления",
|
||||
"settings_notify_scope_all": "Все задачи",
|
||||
"settings_notify_scope_hint": "Напоминания отправляют только задачи, совпадающие с фильтрами метки/пользователя выбранного представления. Статус, сортировка и группировка представления здесь игнорируются.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Inga objekt än.",
|
||||
"action_error": "Åtgärden misslyckades. Försök igen.",
|
||||
"area_id_optional": "Område (valfritt)",
|
||||
"place_optional": "Plats (zon, valfritt)",
|
||||
"remind_on_site": "Påminn bara när någon är där",
|
||||
"remind_on_site_hint": "Påminnelser väntar tills någon är i den här zonen. Den som kommer dit får ett meddelande med det som ska göras.",
|
||||
"place_missing": "Zonen hittades inte: påminnelser som hemma",
|
||||
"place_home": "Hemma",
|
||||
"installation_date_optional": "Installationsdatum (valfritt)",
|
||||
"warranty_expiry_optional": "Garantins utgång (valfritt)",
|
||||
"warranty": "Garanti",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Ägare",
|
||||
"feat_completion_actions": "Slutförande-åtgärder",
|
||||
"feat_completion_actions_desc": "HA-åtgärd per uppgift vid slutförande + snabb-slutför-QR med förinställda värden.",
|
||||
"feat_places": "Platser",
|
||||
"feat_places_desc": "Objekt som sköts på en annan plats (en Home Assistant-zon): påminnelser bara när någon är där, och ett meddelande vid ankomst.",
|
||||
"on_complete_action_title": "Vid slutförande: utlös HA-åtgärd (valfritt)",
|
||||
"on_complete_action_desc": "Anropar en HA-tjänst när uppgiften slutförs — t.ex. återställ en räknare på enheten.",
|
||||
"on_complete_action_target": "Målentitet",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Använder reservdel: {name}",
|
||||
"label_filter": "Etikett",
|
||||
"all_labels": "Alla etiketter",
|
||||
"filter_place": "Plats",
|
||||
"filter_place_all": "Alla platser",
|
||||
"settings_notify_scope": "Avisera endast för vy",
|
||||
"settings_notify_scope_all": "Alla uppgifter",
|
||||
"settings_notify_scope_hint": "Endast uppgifter som matchar den valda vyns etikett-/användarfilter skickar påminnelser. Vyns status, sortering och gruppering ignoreras här.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Henüz nesne yok.",
|
||||
"action_error": "Eylem başarısız oldu. Lütfen tekrar deneyin.",
|
||||
"area_id_optional": "Alan (isteğe bağlı)",
|
||||
"place_optional": "Yer (bölge, isteğe bağlı)",
|
||||
"remind_on_site": "Yalnızca biri oradayken hatırlat",
|
||||
"remind_on_site_hint": "Hatırlatmalar biri bu bölgede olana kadar bekler. Oraya varan kişi yapılacakların listesini içeren bir mesaj alır.",
|
||||
"place_missing": "Bölge bulunamadı: hatırlatmalar evdeki gibi",
|
||||
"place_home": "Ev",
|
||||
"installation_date_optional": "Kurulum tarihi (isteğe bağlı)",
|
||||
"warranty_expiry_optional": "Garanti bitişi (isteğe bağlı)",
|
||||
"warranty": "Garanti",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Sahip",
|
||||
"feat_completion_actions": "Tamamlama eylemleri",
|
||||
"feat_completion_actions_desc": "Görev başına tamamlamada HA eylemi + önceden ayarlı değerlerle hızlı tamamlama QR'ı.",
|
||||
"feat_places": "Yerler",
|
||||
"feat_places_desc": "Başka bir yerde (Home Assistant bölgesi) bakımı yapılan nesneler: hatırlatmalar yalnızca biri oradayken, varışta bir mesaj.",
|
||||
"on_complete_action_title": "Tamamlandığında: HA eylemi tetikle (isteğe bağlı)",
|
||||
"on_complete_action_desc": "Görev tamamlandığında bir HA servisi çağırır — örn. cihazdaki bir sayacı sıfırlar.",
|
||||
"on_complete_action_target": "Hedef varlık",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Kullanılan parça: {name}",
|
||||
"label_filter": "Etiket",
|
||||
"all_labels": "Tüm etiketler",
|
||||
"filter_place": "Yer",
|
||||
"filter_place_all": "Tüm yerler",
|
||||
"settings_notify_scope": "Yalnızca şu görünüm için bildir",
|
||||
"settings_notify_scope_all": "Tüm görevler",
|
||||
"settings_notify_scope_hint": "Yalnızca seçili kayıtlı görünümün etiket/kullanıcı filtreleriyle eşleşen görevler hatırlatma gönderir. Görünümün durum, sıralama ve gruplaması burada dikkate alınmaz.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Поки немає об'єктів.",
|
||||
"action_error": "Дія не вдалась. Спробуйте ще раз.",
|
||||
"area_id_optional": "Зона (необов'язково)",
|
||||
"place_optional": "Місце (зона, необов'язково)",
|
||||
"remind_on_site": "Нагадувати, лише коли там хтось є",
|
||||
"remind_on_site_hint": "Нагадування чекають, поки хтось буде в цій зоні. Хто туди прибуває, отримує повідомлення про те, що потрібно зробити.",
|
||||
"place_missing": "Зону не знайдено: нагадування як удома",
|
||||
"place_home": "Дім",
|
||||
"installation_date_optional": "Дата встановлення (необов'язково)",
|
||||
"warranty_expiry_optional": "Закінчення гарантії (необов'язково)",
|
||||
"warranty": "Гарантія",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Власник",
|
||||
"feat_completion_actions": "Дії при завершенні",
|
||||
"feat_completion_actions_desc": "Дія HA по завданню при завершенні + QR швидкого завершення з попередньо встановленими значеннями.",
|
||||
"feat_places": "Місця",
|
||||
"feat_places_desc": "Об'єкти в іншому місці (зона Home Assistant): нагадування лише тоді, коли там хтось є, і повідомлення після прибуття.",
|
||||
"on_complete_action_title": "При завершенні: викликати HA-дію (опційно)",
|
||||
"on_complete_action_desc": "Викликає HA-сервіс, коли завдання завершено — напр., скинути лічильник на пристрої.",
|
||||
"on_complete_action_target": "Цільова сутність",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Використовує деталь: {name}",
|
||||
"label_filter": "Мітка",
|
||||
"all_labels": "Усі мітки",
|
||||
"filter_place": "Місце",
|
||||
"filter_place_all": "Усі місця",
|
||||
"settings_notify_scope": "Сповіщати лише для подання",
|
||||
"settings_notify_scope_all": "Усі завдання",
|
||||
"settings_notify_scope_hint": "Нагадування надсилають лише завдання, що відповідають фільтрам мітки/користувача обраного подання. Статус, сортування та групування подання тут ігноруються.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "暂无维护项。",
|
||||
"action_error": "操作失败。请重试。",
|
||||
"area_id_optional": "区域 (可选)",
|
||||
"place_optional": "地点(区域,可选)",
|
||||
"remind_on_site": "仅当有人在场时提醒",
|
||||
"remind_on_site_hint": "提醒会等到有人在此区域时再发送。到达那里的人会收到一条列出待办事项的消息。",
|
||||
"place_missing": "未找到区域:按在家处理提醒",
|
||||
"place_home": "家",
|
||||
"installation_date_optional": "安装日期 (可选)",
|
||||
"warranty_expiry_optional": "保修到期 (可选)",
|
||||
"warranty": "保修",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "所有者",
|
||||
"feat_completion_actions": "完成动作",
|
||||
"feat_completion_actions_desc": "为每个任务配置完成时的 HA 动作 + 预设值的快速完成二维码。",
|
||||
"feat_places": "地点",
|
||||
"feat_places_desc": "在其他地点(Home Assistant 区域)维护的对象:仅当有人在场时提醒,并在到达时发送消息。",
|
||||
"on_complete_action_title": "完成时:触发 HA 动作(可选)",
|
||||
"on_complete_action_desc": "任务完成时调用 HA 服务 — 例如重置设备上的物理计数器。",
|
||||
"on_complete_action_target": "目标实体",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "使用配件:{name}",
|
||||
"label_filter": "标签",
|
||||
"all_labels": "所有标签",
|
||||
"filter_place": "地点",
|
||||
"filter_place_all": "所有地点",
|
||||
"settings_notify_scope": "仅为该视图发送通知",
|
||||
"settings_notify_scope_all": "所有任务",
|
||||
"settings_notify_scope_hint": "只有匹配所选视图的标签/用户筛选的任务才会发送提醒。视图的状态、排序和分组在此处被忽略。",
|
||||
|
||||
@@ -131,6 +131,7 @@ import type { PartsCostMode } from "./helpers/parts-cost";
|
||||
import { canWrite } from "./helpers/permissions";
|
||||
import { renderStatusBadge } from "./renderers/status";
|
||||
import { TOAST_MS, ACTION_TOAST_MS } from "./helpers/toast";
|
||||
import { primaryTriggerEntity } from "./helpers/trigger-entities";
|
||||
import { buildHistoryEntryDraft } from "./helpers/history-draft";
|
||||
import { readingSlotDelta } from "./helpers/reading-slots";
|
||||
import { bulkResultMessage, codedFailures, runWs, runWsEach } from "./helpers/ws-run";
|
||||
@@ -236,6 +237,8 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
@state() private _filterStatus = "";
|
||||
@state() private _filterUser: string | null = null;
|
||||
@state() private _filterLabel: string | null = null;
|
||||
// 2026-10 places: "" = all, "home" = objects without a place, else a zone id.
|
||||
@state() private _filterPlace = "";
|
||||
/** #134: only tasks of this priority (low|normal|high); "" = no filter. */
|
||||
@state() private _filterPriority = "";
|
||||
// v2.24: shared saved filter views + the id of the one currently applied ("" =
|
||||
@@ -264,7 +267,7 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
@state() private _groups: Record<string, MaintenanceGroup> = {};
|
||||
@state() private _detailStatsData: Map<string, StatisticsPoint[]> = new Map();
|
||||
@state() private _miniStatsData: Map<string, StatisticsPoint[]> = new Map();
|
||||
@state() private _features: AdvancedFeatures = { adaptive: false, seasonal: false, environmental: false, budget: false, groups: false, checklists: false, schedule_time: false, completion_actions: false };
|
||||
@state() private _features: AdvancedFeatures = { adaptive: false, seasonal: false, environmental: false, budget: false, groups: false, checklists: false, schedule_time: false, completion_actions: false, places: false };
|
||||
// HA user IDs (UUIDs) granted full panel access despite not being HA admins.
|
||||
@state() private _adminPanelUserIds: string[] = [];
|
||||
// v2.8.4: master switch — the allowlist only grants the full panel when this
|
||||
@@ -1087,7 +1090,7 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
const task = this._selectedEntryId && this._selectedTaskId
|
||||
? this._getTask(this._selectedEntryId, this._selectedTaskId)
|
||||
: null;
|
||||
const entityId = task?.trigger_config?.entity_id;
|
||||
const entityId = primaryTriggerEntity(task?.trigger_config);
|
||||
if (entityId) {
|
||||
// Drop the stale-range series so the chart shows its loading state.
|
||||
const updated = new Map(this._detailStatsData);
|
||||
@@ -1111,7 +1114,8 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
const entities: Array<{ entityId: string; isCounter: boolean }> = [];
|
||||
for (const obj of this._objects) {
|
||||
for (const task of obj.tasks) {
|
||||
const entityId = task.trigger_config?.entity_id;
|
||||
// The battery fleet's row shows "N to replace", not a sparkline.
|
||||
const entityId = task.battery_fleet_task ? undefined : primaryTriggerEntity(task.trigger_config);
|
||||
if (!entityId) continue;
|
||||
entities.push({ entityId, isCounter: this._isCounterEntity(task.trigger_config) });
|
||||
}
|
||||
@@ -1217,6 +1221,9 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
// Label filter (v2.26 — also captured by saved views)
|
||||
if (this._filterLabel && !(task.labels || []).includes(this._filterLabel)) continue;
|
||||
|
||||
// Place filter (2026-10): the object's zone, "home" for none.
|
||||
if (this._filterPlace && (obj.object.place || "home") !== this._filterPlace) continue;
|
||||
|
||||
// Priority filter (#134 — also captured by saved views). Tasks
|
||||
// without an explicit priority are "normal", the model default.
|
||||
if (this._filterPriority && (task.priority || "normal") !== this._filterPriority) continue;
|
||||
@@ -1353,8 +1360,9 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
if (s.msp_view === "task" && s.msp_entry && s.msp_task) {
|
||||
this._historyFilter = null;
|
||||
const task = this._getTask(s.msp_entry, s.msp_task);
|
||||
if (task?.trigger_config?.entity_id) {
|
||||
this._fetchDetailStats(task.trigger_config.entity_id, this._isCounterEntity(task.trigger_config));
|
||||
const entityId = primaryTriggerEntity(task?.trigger_config);
|
||||
if (task && entityId) {
|
||||
this._fetchDetailStats(entityId, this._isCounterEntity(task.trigger_config));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1454,6 +1462,16 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
return [...seen].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
/** 2026-10 places: the zones objects are maintained at, for the filter. */
|
||||
private get _allPlaces(): { id: string; name: string }[] {
|
||||
const seen = new Map<string, string>();
|
||||
for (const obj of this._objects) {
|
||||
const o = obj.object;
|
||||
if (o.place && !seen.has(o.place)) seen.set(o.place, o.place_name || o.place);
|
||||
}
|
||||
return [...seen].map(([id, name]) => ({ id, name })).sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** The panel's current task-list filter state, in the shape a view stores. */
|
||||
private get _currentFilters(): SavedViewFilters {
|
||||
return {
|
||||
@@ -1615,8 +1633,9 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
this._resetStickyPane();
|
||||
this._fetchFullHistory(entryId, taskId);
|
||||
const task = this._getTask(entryId, taskId);
|
||||
if (task?.trigger_config?.entity_id) {
|
||||
this._fetchDetailStats(task.trigger_config.entity_id, this._isCounterEntity(task.trigger_config));
|
||||
const entityId = primaryTriggerEntity(task?.trigger_config);
|
||||
if (task && entityId) {
|
||||
this._fetchDetailStats(entityId, this._isCounterEntity(task.trigger_config));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1637,10 +1656,9 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
|
||||
// Lazy-load statistics for the task's trigger entity
|
||||
const task = this._getTask(entryId, taskId);
|
||||
if (task?.trigger_config?.entity_id) {
|
||||
const entityId = task.trigger_config.entity_id;
|
||||
const isCounter = this._isCounterEntity(task.trigger_config);
|
||||
this._fetchDetailStats(entityId, isCounter);
|
||||
const entityId = primaryTriggerEntity(task?.trigger_config);
|
||||
if (task && entityId) {
|
||||
this._fetchDetailStats(entityId, this._isCounterEntity(task.trigger_config));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3196,6 +3214,7 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
<maintenance-object-dialog
|
||||
.hass=${this.hass}
|
||||
.objects=${this._objects}
|
||||
.placesEnabled=${this._features.places}
|
||||
@object-saved=${this._onObjectSaved}
|
||||
@object-replaced=${this._onObjectReplaced}
|
||||
></maintenance-object-dialog>
|
||||
@@ -3543,6 +3562,7 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
(this._filterStatus ? 1 : 0) +
|
||||
(this._filterUser ? 1 : 0) +
|
||||
(this._filterLabel ? 1 : 0) +
|
||||
(this._filterPlace ? 1 : 0) +
|
||||
(this._filterPriority ? 1 : 0) +
|
||||
(this._activeViewId ? 1 : 0);
|
||||
|
||||
@@ -3626,6 +3646,24 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
</select>
|
||||
</label>
|
||||
` : nothing}
|
||||
${this._features.places && this._allPlaces.length > 0 ? html`
|
||||
<label class="filter-field">
|
||||
<span class="filter-label">${t("filter_place", L)}</span>
|
||||
<select
|
||||
.value=${this._filterPlace}
|
||||
@change=${(e: Event) => {
|
||||
this._filterPlace = (e.target as HTMLSelectElement).value;
|
||||
this._activeViewId = "";
|
||||
}}
|
||||
>
|
||||
<option value="">${t("filter_place_all", L)}</option>
|
||||
<option value="home" ?selected=${this._filterPlace === "home"}>${t("place_home", L)}</option>
|
||||
${this._allPlaces.map(
|
||||
(pl) => html`<option value=${pl.id} ?selected=${this._filterPlace === pl.id}>${pl.name}</option>`
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
` : nothing}
|
||||
<label class="filter-field">
|
||||
<span class="filter-label">${t("priority", L)}</span>
|
||||
<select
|
||||
@@ -4743,6 +4781,13 @@ export class MaintenanceSupporterPanel extends LitElement {
|
||||
<a href="#" class="object-area-link" @click=${(e: Event) => { e.preventDefault(); this._showArea(o.area_id!); }}
|
||||
>${areaDisplayName(o.area_id, this.hass?.areas, t("no_area", L))}</a></p>`
|
||||
: nothing}
|
||||
${o.place
|
||||
? html`<p class="meta place-meta">
|
||||
<ha-icon icon="mdi:map-marker-outline"></ha-icon>
|
||||
${t("filter_place", L)}: ${o.place_name || o.place}${o.remind_on_site ? html` · ${t("remind_on_site", L)}` : nothing}
|
||||
${o.place_missing ? html`<span class="place-missing-badge">${t("place_missing", L)}</span>` : nothing}
|
||||
</p>`
|
||||
: nothing}
|
||||
${isSafeHttpUrl(o.documentation_url)
|
||||
? html`<p class="meta">${t("documentation_url_label", L)}:
|
||||
<a href=${o.documentation_url} target="_blank" rel="noopener noreferrer">${o.documentation_url}</a>
|
||||
|
||||
@@ -963,6 +963,14 @@ export const panelStyles = css`
|
||||
color: var(--info-color, #2196f3); font-weight: 500;
|
||||
}
|
||||
.paused-meta ha-icon { --mdc-icon-size: 16px; }
|
||||
/* 2026-10 places: the object's place on its detail page. */
|
||||
.place-meta {
|
||||
display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
|
||||
}
|
||||
.place-meta ha-icon { --mdc-icon-size: 16px; color: var(--secondary-text-color); }
|
||||
.place-missing-badge {
|
||||
font-size: 12px; color: var(--warning-color, #c77700);
|
||||
}
|
||||
.objects-table .oc-notes {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -16,6 +16,7 @@ import { t, formatDate, formatDueDays, formatNumber } from "../styles";
|
||||
import { px } from "./chart-utils";
|
||||
import { daysProgress } from "../helpers/interval";
|
||||
import { stampMs } from "../helpers/ha-time";
|
||||
import { primaryTriggerEntity } from "../helpers/trigger-entities";
|
||||
import type { MaintenanceTask, TaskRow, StatisticsPoint } from "../types";
|
||||
|
||||
const MINI_SPARKLINE_W = 60;
|
||||
@@ -36,7 +37,9 @@ export function computeTrend(
|
||||
miniStatsData: Map<string, StatisticsPoint[]>,
|
||||
): TrendState | null {
|
||||
const tc = row.trigger_config;
|
||||
if (!tc?.entity_id) return null;
|
||||
const entityId = primaryTriggerEntity(tc);
|
||||
// The battery fleet's row tells "N to replace", not one battery's curve.
|
||||
if (!tc || !entityId || row.battery_fleet_task) return null;
|
||||
let toward: 1 | -1;
|
||||
const type = tc.type || "threshold";
|
||||
if (type === "threshold") {
|
||||
@@ -48,7 +51,7 @@ export function computeTrend(
|
||||
} else {
|
||||
return null; // compound: conditions may point both ways
|
||||
}
|
||||
const statsPoints = miniStatsData.get(tc.entity_id) || [];
|
||||
const statsPoints = miniStatsData.get(entityId) || [];
|
||||
// Runtime and state_change accumulate SINCE the last completion — the
|
||||
// history's trigger_value is the count at the previous trigger, a point
|
||||
// from before the reset. Falling back to it read a freshly reset task
|
||||
@@ -235,8 +238,9 @@ export function renderMiniSparkline(
|
||||
miniStatsData: Map<string, StatisticsPoint[]>,
|
||||
lang: string,
|
||||
) {
|
||||
if (!row.trigger_config?.entity_id) return nothing;
|
||||
const entityId = row.trigger_config.entity_id;
|
||||
const entityId = primaryTriggerEntity(row.trigger_config);
|
||||
// The battery fleet's row tells "N to replace", not one battery's curve.
|
||||
if (!entityId || row.battery_fleet_task) return nothing;
|
||||
|
||||
// PRIMARY: HA recorder statistics (daily, last 14 days)
|
||||
const statsPoints = miniStatsData.get(entityId) || [];
|
||||
|
||||
@@ -16,6 +16,7 @@ import { t, fireMoreInfo, formatDueDays } from "../styles";
|
||||
import { fmtNum, fmtVal } from "./chart-utils";
|
||||
import { dueDaysOf } from "./progress";
|
||||
import { stampMs } from "../helpers/ha-time";
|
||||
import { primaryTriggerEntity, triggerEntityIds } from "../helpers/trigger-entities";
|
||||
import "../components/trigger-chart";
|
||||
import type { ChartPoint, ChartEvent } from "../components/trigger-chart";
|
||||
import type { MaintenanceTask, TriggerConfig, StatisticsPoint } from "../types";
|
||||
@@ -156,9 +157,9 @@ export function renderTriggerSection(task: MaintenanceTask, ctx: SparklineContex
|
||||
const L = ctx.lang;
|
||||
const info = task.trigger_entity_info;
|
||||
const infos = task.trigger_entity_infos;
|
||||
const friendlyName = info?.friendly_name || tc.entity_id || "—";
|
||||
const entityId = tc.entity_id || "";
|
||||
const entityIds = tc.entity_ids || (entityId ? [entityId] : []);
|
||||
const entityId = primaryTriggerEntity(tc) || "";
|
||||
const friendlyName = info?.friendly_name || entityId || "—";
|
||||
const entityIds = triggerEntityIds(tc);
|
||||
const unit = info?.unit_of_measurement || "";
|
||||
const currentVal = task.trigger_current_value;
|
||||
const triggerType = tc.type || "threshold";
|
||||
@@ -215,7 +216,7 @@ export function renderTriggerSection(task: MaintenanceTask, ctx: SparklineContex
|
||||
${triggerType === "compound" ? html`
|
||||
<span class="trigger-limit-item"><span class="dot warn" aria-hidden="true"></span> ${t("compound_logic", L)}: ${tc.compound_logic || (tc as any).operator || "AND"}</span>
|
||||
${(tc.conditions || []).map((cond: any, i: number) => html`
|
||||
<span class="trigger-limit-item"><span class="dot range" aria-hidden="true"></span> ${i + 1}. ${t(cond.type === "due_date" ? "trigger_type_due_date" : cond.type || "unknown", L)}: ${cond.entity_id ? html`<span class="entity-link" @click=${(ev: Event) => fireMoreInfo(ev, cond.entity_id)}>${cond.entity_id}</span>` : ""}</span>
|
||||
<span class="trigger-limit-item"><span class="dot range" aria-hidden="true"></span> ${i + 1}. ${t(cond.type === "due_date" ? "trigger_type_due_date" : cond.type || "unknown", L)}: ${triggerEntityIds(cond).map((eid, j) => html`${j > 0 ? ", " : ""}<span class="entity-link" @click=${(ev: Event) => fireMoreInfo(ev, eid)}>${eid}</span>`)}</span>
|
||||
`)}
|
||||
` : nothing}
|
||||
</div>
|
||||
@@ -330,7 +331,7 @@ function rawStatsPoints(task: MaintenanceTask, ctx: SparklineContext): ChartPoin
|
||||
const tc = task.trigger_config;
|
||||
if (!tc) return [];
|
||||
const triggerType = tc.type || "threshold";
|
||||
const entityId = tc.entity_id || "";
|
||||
const entityId = primaryTriggerEntity(tc) || "";
|
||||
// Runtime accumulates hours DERIVED from the entity's on/off time — the
|
||||
// entity's own long-term statistics (an on/off ratio, or an unrelated raw
|
||||
// sensor value) are NOT that accumulation. Plot only the recorded per-cycle
|
||||
@@ -372,7 +373,7 @@ function renderChart(task: MaintenanceTask, unit: string, ctx: SparklineContext)
|
||||
const tc = task.trigger_config;
|
||||
if (!tc) return nothing;
|
||||
const triggerType = tc.type || "threshold";
|
||||
const entityId = tc.entity_id || "";
|
||||
const entityId = primaryTriggerEntity(tc) || "";
|
||||
// A due date only counts down — no curve to tell.
|
||||
if (triggerType === "due_date") return nothing;
|
||||
|
||||
|
||||
@@ -40,6 +40,13 @@ export interface MaintenanceObject {
|
||||
// 2.19: attach to an existing HA device / nest under another object
|
||||
ha_device_id?: string | null;
|
||||
parent_entry_id?: string | null;
|
||||
/** 2026-10 places: an HA zone the object is maintained at (null = home),
|
||||
* its name, whether the zone is gone (then: as at home), and whether the
|
||||
* object's reminders wait until somebody is there. */
|
||||
place?: string | null;
|
||||
place_name?: string | null;
|
||||
place_missing?: boolean;
|
||||
remind_on_site?: boolean;
|
||||
/** v1.4.0 (#43): optional link to PDF manual / vendor page for the object */
|
||||
documentation_url?: string | null;
|
||||
/** v1.4.10 (#46): free-form notes — part numbers, procedures, etc. */
|
||||
@@ -550,6 +557,8 @@ export interface AdvancedFeatures {
|
||||
schedule_time: boolean;
|
||||
/** v1.3.0: gates per-task on_complete_action + quick_complete_defaults UI. */
|
||||
completion_actions: boolean;
|
||||
/** 2026-10: an object's place (an HA zone) and "remind only on site". */
|
||||
places: boolean;
|
||||
}
|
||||
|
||||
/** A single point in a recorder statistics time series. */
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Zatím žádné objekty.",
|
||||
"action_error": "Akce se nezdařila. Zkuste to znovu.",
|
||||
"area_id_optional": "Oblast (volitelná)",
|
||||
"place_optional": "Místo (zóna, volitelné)",
|
||||
"remind_on_site": "Připomínat jen, když tam někdo je",
|
||||
"remind_on_site_hint": "Připomínky čekají, dokud někdo nebude v této zóně. Kdo tam přijede, dostane zprávu s tím, co je potřeba udělat.",
|
||||
"place_missing": "Zóna nenalezena: připomínky jako doma",
|
||||
"place_home": "Domov",
|
||||
"installation_date_optional": "Datum instalace (volitelné)",
|
||||
"warranty_expiry_optional": "Konec záruky (volitelné)",
|
||||
"warranty": "Záruka",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Vlastník",
|
||||
"feat_completion_actions": "Akce při dokončení",
|
||||
"feat_completion_actions_desc": "Akce HA na úlohu při dokončení + QR rychlého dokončení s předvolenými hodnotami.",
|
||||
"feat_places": "Místa",
|
||||
"feat_places_desc": "Objekty udržované na jiném místě (zóna Home Assistantu): připomínky jen když tam někdo je a zpráva při příjezdu.",
|
||||
"on_complete_action_title": "Při dokončení: spustit akci HA (volitelné)",
|
||||
"on_complete_action_desc": "Volá službu HA, když je úloha dokončena — např. resetuje čítač na zařízení.",
|
||||
"on_complete_action_target": "Cílová entita",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Používá díl: {name}",
|
||||
"label_filter": "Štítek",
|
||||
"all_labels": "Všechny štítky",
|
||||
"filter_place": "Místo",
|
||||
"filter_place_all": "Všechna místa",
|
||||
"settings_notify_scope": "Upozorňovat jen pro zobrazení",
|
||||
"settings_notify_scope_all": "Všechny úkoly",
|
||||
"settings_notify_scope_hint": "Připomenutí posílají jen úkoly odpovídající filtrům štítku/uživatele zvoleného zobrazení. Stav, řazení a seskupení zobrazení se zde ignorují.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ingen objekter endnu.",
|
||||
"action_error": "Handlingen mislykkedes. Prøv igen.",
|
||||
"area_id_optional": "Område (valgfrit)",
|
||||
"place_optional": "Sted (zone, valgfrit)",
|
||||
"remind_on_site": "Påmind kun, når nogen er der",
|
||||
"remind_on_site_hint": "Påmindelser venter, til nogen er i denne zone. Den, der ankommer, får en besked med det, der skal gøres.",
|
||||
"place_missing": "Zone ikke fundet: påmindelser som hjemme",
|
||||
"place_home": "Hjemme",
|
||||
"installation_date_optional": "Installationsdato (valgfrit)",
|
||||
"warranty_expiry_optional": "Garantiens udløb (valgfrit)",
|
||||
"warranty": "Garanti",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Ejer",
|
||||
"feat_completion_actions": "Fuldførelseshandlinger",
|
||||
"feat_completion_actions_desc": "HA-handling pr. opgave ved fuldførelse + hurtig-fuldfør-QR med forudindstillede værdier.",
|
||||
"feat_places": "Steder",
|
||||
"feat_places_desc": "Objekter, der vedligeholdes et andet sted (en Home Assistant-zone): påmindelser kun når nogen er der, og en besked ved ankomst.",
|
||||
"on_complete_action_title": "Ved fuldførelse: udløs HA-handling (valgfrit)",
|
||||
"on_complete_action_desc": "Kalder en HA-tjeneste, når opgaven fuldføres — f.eks. nulstil en tæller på enheden.",
|
||||
"on_complete_action_target": "Målenhed",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Bruger reservedel: {name}",
|
||||
"label_filter": "Etiket",
|
||||
"all_labels": "Alle etiketter",
|
||||
"filter_place": "Sted",
|
||||
"filter_place_all": "Alle steder",
|
||||
"settings_notify_scope": "Underret kun for visning",
|
||||
"settings_notify_scope_all": "Alle opgaver",
|
||||
"settings_notify_scope_hint": "Kun opgaver, der matcher den valgte visnings etiket-/brugerfiltre, sender påmindelser. Visningens status, sortering og gruppering ignoreres her.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Keine Objekte vorhanden.",
|
||||
"action_error": "Aktion fehlgeschlagen. Bitte erneut versuchen.",
|
||||
"area_id_optional": "Bereich (optional)",
|
||||
"place_optional": "Ort (Zone, optional)",
|
||||
"remind_on_site": "Nur erinnern, wenn jemand dort ist",
|
||||
"remind_on_site_hint": "Erinnerungen warten, bis jemand in dieser Zone ist. Wer dort ankommt, bekommt eine Nachricht mit dem, was fällig ist.",
|
||||
"place_missing": "Zone nicht gefunden: Erinnerungen wie zuhause",
|
||||
"place_home": "Zuhause",
|
||||
"installation_date_optional": "Installationsdatum (optional)",
|
||||
"warranty_expiry_optional": "Garantie-Ablauf (optional)",
|
||||
"warranty": "Garantie",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Besitzer",
|
||||
"feat_completion_actions": "Completion-Actions",
|
||||
"feat_completion_actions_desc": "Pro Aufgabe HA-Action beim Abschluss konfigurieren + Quick-Complete-QR mit voreingestellten Werten.",
|
||||
"feat_places": "Orte",
|
||||
"feat_places_desc": "Objekte an einem anderen Ort (eine Home-Assistant-Zone): Erinnerungen nur, wenn jemand dort ist, und eine Nachricht bei Ankunft.",
|
||||
"on_complete_action_title": "Beim Abschluss: HA-Action auslösen (optional)",
|
||||
"on_complete_action_desc": "Ruft beim Erledigen der Aufgabe einen HA-Service auf — z. B. einen Zähler am Gerät zurücksetzen.",
|
||||
"on_complete_action_target": "Ziel-Entität",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Nutzt Ersatzteil: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "Alle Labels",
|
||||
"filter_place": "Ort",
|
||||
"filter_place_all": "Alle Orte",
|
||||
"settings_notify_scope": "Nur benachrichtigen für Ansicht",
|
||||
"settings_notify_scope_all": "Alle Aufgaben",
|
||||
"settings_notify_scope_hint": "Nur Aufgaben, die zu den Label-/Nutzer-Filtern der gewählten Ansicht passen, senden Erinnerungen. Status, Sortierung und Gruppierung der Ansicht werden hier ignoriert.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "No objects yet.",
|
||||
"action_error": "Action failed. Please try again.",
|
||||
"area_id_optional": "Area (optional)",
|
||||
"place_optional": "Place (zone, optional)",
|
||||
"remind_on_site": "Remind only while somebody is there",
|
||||
"remind_on_site_hint": "Reminders wait until somebody is in this zone. Whoever arrives there gets a message with what is due.",
|
||||
"place_missing": "Zone not found: reminders as at home",
|
||||
"place_home": "Home",
|
||||
"installation_date_optional": "Installation date (optional)",
|
||||
"warranty_expiry_optional": "Warranty expiry (optional)",
|
||||
"warranty": "Warranty",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Owner",
|
||||
"feat_completion_actions": "Completion actions",
|
||||
"feat_completion_actions_desc": "Per-task HA action on complete + quick-complete QR with pre-set values.",
|
||||
"feat_places": "Places",
|
||||
"feat_places_desc": "Objects maintained at another place (a Home Assistant zone): reminders only while somebody is there, and a message on arrival.",
|
||||
"on_complete_action_title": "On complete: trigger HA action (optional)",
|
||||
"on_complete_action_desc": "Calls an HA service when the task is completed — e.g. reset a counter on the device.",
|
||||
"on_complete_action_target": "Target entity",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Uses part: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "All labels",
|
||||
"filter_place": "Place",
|
||||
"filter_place_all": "All places",
|
||||
"settings_notify_scope": "Notify only for view",
|
||||
"settings_notify_scope_all": "All tasks",
|
||||
"settings_notify_scope_hint": "Only tasks matching the selected saved view's label/user filters send reminders. Status, sorting and grouping of the view are ignored here.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Aún no hay objetos.",
|
||||
"action_error": "Acción fallida. Inténtelo de nuevo.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Lugar (zona, opcional)",
|
||||
"remind_on_site": "Recordar solo cuando alguien esté allí",
|
||||
"remind_on_site_hint": "Los recordatorios esperan a que alguien esté en esta zona. Quien llega allí recibe un mensaje con lo pendiente.",
|
||||
"place_missing": "Zona no encontrada: recordatorios como en casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Fecha de instalación (opcional)",
|
||||
"warranty_expiry_optional": "Vencimiento de garantía (opcional)",
|
||||
"warranty": "Garantía",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Propietario",
|
||||
"feat_completion_actions": "Acciones de finalización",
|
||||
"feat_completion_actions_desc": "Acción HA por tarea al completar + QR de finalización rápida con valores prefijados.",
|
||||
"feat_places": "Lugares",
|
||||
"feat_places_desc": "Objetos mantenidos en otro lugar (una zona de Home Assistant): recordatorios solo cuando alguien está allí y un mensaje al llegar.",
|
||||
"on_complete_action_title": "Al completar: ejecutar acción HA (opcional)",
|
||||
"on_complete_action_desc": "Llama un servicio HA cuando se completa la tarea — p. ej. reiniciar un contador del dispositivo.",
|
||||
"on_complete_action_target": "Entidad objetivo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa la pieza: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas las etiquetas",
|
||||
"filter_place": "Lugar",
|
||||
"filter_place_all": "Todos los lugares",
|
||||
"settings_notify_scope": "Notificar solo para la vista",
|
||||
"settings_notify_scope_all": "Todas las tareas",
|
||||
"settings_notify_scope_hint": "Solo las tareas que coinciden con los filtros de etiqueta/usuario de la vista seleccionada envían recordatorios. El estado, el orden y la agrupación de la vista se ignoran aquí.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ei vielä kohteita.",
|
||||
"action_error": "Toiminto epäonnistui. Yritä uudelleen.",
|
||||
"area_id_optional": "Alue (valinnainen)",
|
||||
"place_optional": "Paikka (vyöhyke, valinnainen)",
|
||||
"remind_on_site": "Muistuta vain, kun joku on paikalla",
|
||||
"remind_on_site_hint": "Muistutukset odottavat, kunnes joku on tällä vyöhykkeellä. Sinne saapuva saa viestin tehtävistä asioista.",
|
||||
"place_missing": "Vyöhykettä ei löydy: muistutukset kuin kotona",
|
||||
"place_home": "Koti",
|
||||
"installation_date_optional": "Asennuspäivä (valinnainen)",
|
||||
"warranty_expiry_optional": "Takuun päättyminen (valinnainen)",
|
||||
"warranty": "Takuu",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Omistaja",
|
||||
"feat_completion_actions": "Suoritustoiminnot",
|
||||
"feat_completion_actions_desc": "Tehtäväkohtainen HA-toiminto suorituksen yhteydessä + pikasuoritus-QR esiasetetuilla arvoilla.",
|
||||
"feat_places": "Paikat",
|
||||
"feat_places_desc": "Toisessa paikassa (Home Assistant -vyöhyke) huollettavat kohteet: muistutukset vain, kun joku on paikalla, ja viesti saavuttaessa.",
|
||||
"on_complete_action_title": "Suorituksen yhteydessä: laukaise HA-toiminto (valinnainen)",
|
||||
"on_complete_action_desc": "Kutsuu HA-palvelua, kun tehtävä suoritetaan — esim. nollaa laitteen laskuri.",
|
||||
"on_complete_action_target": "Kohde-entiteetti",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Käyttää varaosaa: {name}",
|
||||
"label_filter": "Tunniste",
|
||||
"all_labels": "Kaikki tunnisteet",
|
||||
"filter_place": "Paikka",
|
||||
"filter_place_all": "Kaikki paikat",
|
||||
"settings_notify_scope": "Ilmoita vain näkymälle",
|
||||
"settings_notify_scope_all": "Kaikki tehtävät",
|
||||
"settings_notify_scope_hint": "Vain valitun näkymän tunniste-/käyttäjäsuodattimiin osuvat tehtävät lähettävät muistutuksia. Näkymän tila, lajittelu ja ryhmittely ohitetaan tässä.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Aucun objet pour l'instant.",
|
||||
"action_error": "Action échouée. Veuillez réessayer.",
|
||||
"area_id_optional": "Zone (optionnel)",
|
||||
"place_optional": "Lieu (zone, facultatif)",
|
||||
"remind_on_site": "Rappeler seulement quand quelqu'un y est",
|
||||
"remind_on_site_hint": "Les rappels attendent que quelqu'un soit dans cette zone. Qui y arrive reçoit un message avec ce qui est à faire.",
|
||||
"place_missing": "Zone introuvable : rappels comme à la maison",
|
||||
"place_home": "Domicile",
|
||||
"installation_date_optional": "Date d'installation (optionnel)",
|
||||
"warranty_expiry_optional": "Fin de garantie (optionnel)",
|
||||
"warranty": "Garantie",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Propriétaire",
|
||||
"feat_completion_actions": "Actions de finalisation",
|
||||
"feat_completion_actions_desc": "Action HA par tâche lors de la finalisation + QR de finalisation rapide avec valeurs pré-définies.",
|
||||
"feat_places": "Lieux",
|
||||
"feat_places_desc": "Objets entretenus à un autre endroit (une zone Home Assistant) : rappels seulement quand quelqu'un y est, et un message à l'arrivée.",
|
||||
"on_complete_action_title": "À la finalisation : déclencher une action HA (optionnel)",
|
||||
"on_complete_action_desc": "Appelle un service HA quand la tâche est terminée — p. ex. réinitialiser un compteur sur l'appareil.",
|
||||
"on_complete_action_target": "Entité cible",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Utilise la pièce : {name}",
|
||||
"label_filter": "Étiquette",
|
||||
"all_labels": "Toutes les étiquettes",
|
||||
"filter_place": "Lieu",
|
||||
"filter_place_all": "Tous les lieux",
|
||||
"settings_notify_scope": "Notifier uniquement pour la vue",
|
||||
"settings_notify_scope_all": "Toutes les tâches",
|
||||
"settings_notify_scope_hint": "Seules les tâches correspondant aux filtres étiquette/utilisateur de la vue choisie envoient des rappels. Le statut, le tri et le regroupement de la vue sont ignorés ici.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "अभी कोई वस्तु नहीं।",
|
||||
"action_error": "क्रिया विफल। कृपया पुनः प्रयास करें।",
|
||||
"area_id_optional": "क्षेत्र (वैकल्पिक)",
|
||||
"place_optional": "स्थान (ज़ोन, वैकल्पिक)",
|
||||
"remind_on_site": "केवल तब याद दिलाएँ जब कोई वहाँ हो",
|
||||
"remind_on_site_hint": "रिमाइंडर तब तक रुकते हैं जब तक कोई इस ज़ोन में न हो। वहाँ पहुँचने वाले को बाकी कामों का संदेश मिलता है।",
|
||||
"place_missing": "ज़ोन नहीं मिला: रिमाइंडर घर जैसे",
|
||||
"place_home": "घर",
|
||||
"installation_date_optional": "स्थापना तिथि (वैकल्पिक)",
|
||||
"warranty_expiry_optional": "वारंटी समाप्ति (वैकल्पिक)",
|
||||
"warranty": "वारंटी",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "स्वामी",
|
||||
"feat_completion_actions": "पूर्णता क्रियाएँ",
|
||||
"feat_completion_actions_desc": "पूर्ण होने पर प्रति-कार्य HA क्रिया + पूर्व-निर्धारित मानों के साथ त्वरित-पूर्ण QR।",
|
||||
"feat_places": "स्थान",
|
||||
"feat_places_desc": "किसी दूसरी जगह (Home Assistant ज़ोन) पर रखरखाव वाले ऑब्जेक्ट: रिमाइंडर तभी जब कोई वहाँ हो, और पहुँचने पर एक संदेश।",
|
||||
"on_complete_action_title": "पूर्ण होने पर: HA क्रिया ट्रिगर करें (वैकल्पिक)",
|
||||
"on_complete_action_desc": "कार्य पूर्ण होने पर एक HA सेवा कॉल करता है — उदा. डिवाइस पर काउंटर रीसेट करना।",
|
||||
"on_complete_action_target": "लक्ष्य एंटिटी",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "पुर्ज़ा उपयोग करता है: {name}",
|
||||
"label_filter": "लेबल",
|
||||
"all_labels": "सभी लेबल",
|
||||
"filter_place": "स्थान",
|
||||
"filter_place_all": "सभी स्थान",
|
||||
"settings_notify_scope": "केवल इस व्यू के लिए सूचित करें",
|
||||
"settings_notify_scope_all": "सभी कार्य",
|
||||
"settings_notify_scope_hint": "केवल वे कार्य अनुस्मारक भेजते हैं जो चुने गए व्यू के लेबल/उपयोगकर्ता फ़िल्टर से मेल खाते हैं। व्यू की स्थिति, क्रम और समूहन यहाँ अनदेखे रहते हैं।",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Még nincsenek objektumok.",
|
||||
"action_error": "A művelet nem sikerült. Próbálja újra.",
|
||||
"area_id_optional": "Terület (opcionális)",
|
||||
"place_optional": "Helyszín (zóna, opcionális)",
|
||||
"remind_on_site": "Csak akkor emlékeztessen, ha valaki ott van",
|
||||
"remind_on_site_hint": "Az emlékeztetők megvárják, amíg valaki ebben a zónában lesz. Aki odaér, üzenetet kap az esedékes teendőkről.",
|
||||
"place_missing": "A zóna nem található: emlékeztetők, mint otthon",
|
||||
"place_home": "Otthon",
|
||||
"installation_date_optional": "Telepítés dátuma (opcionális)",
|
||||
"warranty_expiry_optional": "Garancia lejárta (opcionális)",
|
||||
"warranty": "Garancia",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Tulajdonos",
|
||||
"feat_completion_actions": "Elvégzési műveletek",
|
||||
"feat_completion_actions_desc": "Feladatonkénti HA művelet elvégzéskor + gyorselvégző QR előre beállított értékekkel.",
|
||||
"feat_places": "Helyszínek",
|
||||
"feat_places_desc": "Másik helyszínen (Home Assistant-zóna) karbantartott objektumok: emlékeztető csak akkor, ha valaki ott van, és üzenet érkezéskor.",
|
||||
"on_complete_action_title": "Elvégzéskor: HA művelet indítása (opcionális)",
|
||||
"on_complete_action_desc": "HA szolgáltatást hív meg a feladat elvégzésekor — pl. számláló nullázása az eszközön.",
|
||||
"on_complete_action_target": "Cél entitás",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Alkatrészt használ: {name}",
|
||||
"label_filter": "Címke",
|
||||
"all_labels": "Minden címke",
|
||||
"filter_place": "Helyszín",
|
||||
"filter_place_all": "Minden helyszín",
|
||||
"settings_notify_scope": "Értesítés csak erre a nézetre",
|
||||
"settings_notify_scope_all": "Minden feladat",
|
||||
"settings_notify_scope_hint": "Csak a kiválasztott mentett nézet címke-/felhasználószűrőinek megfelelő feladatok küldenek emlékeztetőt. A nézet állapot-, rendezési és csoportosítási beállításait itt figyelmen kívül hagyjuk.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Nessun oggetto ancora.",
|
||||
"action_error": "Azione fallita. Riprova.",
|
||||
"area_id_optional": "Area (opzionale)",
|
||||
"place_optional": "Luogo (zona, facoltativo)",
|
||||
"remind_on_site": "Ricorda solo quando qualcuno è lì",
|
||||
"remind_on_site_hint": "I promemoria aspettano che qualcuno sia in questa zona. Chi arriva lì riceve un messaggio con ciò che è da fare.",
|
||||
"place_missing": "Zona non trovata: promemoria come a casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data di installazione (opzionale)",
|
||||
"warranty_expiry_optional": "Scadenza garanzia (opzionale)",
|
||||
"warranty": "Garanzia",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Proprietario",
|
||||
"feat_completion_actions": "Azioni di completamento",
|
||||
"feat_completion_actions_desc": "Azione HA per attività al completamento + QR completamento rapido con valori predefiniti.",
|
||||
"feat_places": "Luoghi",
|
||||
"feat_places_desc": "Oggetti curati in un altro luogo (una zona di Home Assistant): promemoria solo quando qualcuno è lì e un messaggio all'arrivo.",
|
||||
"on_complete_action_title": "Al completamento: attiva azione HA (opzionale)",
|
||||
"on_complete_action_desc": "Chiama un servizio HA quando l'attività viene completata — es. azzerare un contatore sul dispositivo.",
|
||||
"on_complete_action_target": "Entità target",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa il ricambio: {name}",
|
||||
"label_filter": "Etichetta",
|
||||
"all_labels": "Tutte le etichette",
|
||||
"filter_place": "Luogo",
|
||||
"filter_place_all": "Tutti i luoghi",
|
||||
"settings_notify_scope": "Notifica solo per la vista",
|
||||
"settings_notify_scope_all": "Tutte le attività",
|
||||
"settings_notify_scope_hint": "Solo le attività che corrispondono ai filtri etichetta/utente della vista scelta inviano promemoria. Stato, ordinamento e raggruppamento della vista qui vengono ignorati.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "対象がまだありません。",
|
||||
"action_error": "操作に失敗しました。もう一度お試しください。",
|
||||
"area_id_optional": "エリア(任意)",
|
||||
"place_optional": "場所(ゾーン、任意)",
|
||||
"remind_on_site": "誰かがいるときだけリマインド",
|
||||
"remind_on_site_hint": "リマインドは誰かがこのゾーンにいるまで待機します。到着した人には、やるべきことをまとめたメッセージが届きます。",
|
||||
"place_missing": "ゾーンが見つかりません:自宅と同じようにリマインドします",
|
||||
"place_home": "自宅",
|
||||
"installation_date_optional": "設置日(任意)",
|
||||
"warranty_expiry_optional": "保証期限(任意)",
|
||||
"warranty": "保証",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "オーナー",
|
||||
"feat_completion_actions": "完了時アクション",
|
||||
"feat_completion_actions_desc": "タスクごとの完了時HAアクション+事前設定値付きのクイック完了QR。",
|
||||
"feat_places": "場所",
|
||||
"feat_places_desc": "別の場所(Home Assistant のゾーン)で管理するオブジェクト:誰かがその場にいるときだけリマインドし、到着時に通知します。",
|
||||
"on_complete_action_title": "完了時: HAアクションを実行(任意)",
|
||||
"on_complete_action_desc": "タスク完了時にHAサービスを呼び出します — 例: デバイスのカウンターをリセット。",
|
||||
"on_complete_action_target": "対象エンティティ",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "使用する部品: {name}",
|
||||
"label_filter": "ラベル",
|
||||
"all_labels": "すべてのラベル",
|
||||
"filter_place": "場所",
|
||||
"filter_place_all": "すべての場所",
|
||||
"settings_notify_scope": "このビューのみ通知",
|
||||
"settings_notify_scope_all": "すべてのタスク",
|
||||
"settings_notify_scope_hint": "選択した保存済みビューのラベル/ユーザーフィルターに一致するタスクのみがリマインダーを送信します。ビューのステータス・並び順・グループ化はここでは無視されます。",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "아직 객체가 없습니다.",
|
||||
"action_error": "동작에 실패했습니다. 다시 시도해 주세요.",
|
||||
"area_id_optional": "구역 (선택)",
|
||||
"place_optional": "장소 (구역, 선택 사항)",
|
||||
"remind_on_site": "누군가 있을 때만 알림",
|
||||
"remind_on_site_hint": "누군가 이 구역에 있을 때까지 알림이 대기합니다. 그곳에 도착한 사람은 해야 할 일을 담은 메시지를 받습니다.",
|
||||
"place_missing": "구역을 찾을 수 없음: 집과 같이 알림",
|
||||
"place_home": "집",
|
||||
"installation_date_optional": "설치일 (선택)",
|
||||
"warranty_expiry_optional": "보증 만료일 (선택)",
|
||||
"warranty": "보증",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "소유자",
|
||||
"feat_completion_actions": "완료 동작",
|
||||
"feat_completion_actions_desc": "완료 시 작업별 HA 동작 실행 + 사전 설정값이 있는 빠른 완료 QR.",
|
||||
"feat_places": "장소",
|
||||
"feat_places_desc": "다른 장소(Home Assistant 구역)에서 관리하는 개체: 누군가 그곳에 있을 때만 알림을 보내고, 도착하면 메시지를 보냅니다.",
|
||||
"on_complete_action_title": "완료 시: HA 동작 실행 (선택)",
|
||||
"on_complete_action_desc": "작업이 완료되면 HA 서비스를 호출합니다 — 예: 기기의 카운터 초기화.",
|
||||
"on_complete_action_target": "대상 엔티티",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "사용 부품: {name}",
|
||||
"label_filter": "라벨",
|
||||
"all_labels": "모든 라벨",
|
||||
"filter_place": "장소",
|
||||
"filter_place_all": "모든 장소",
|
||||
"settings_notify_scope": "특정 보기만 알림",
|
||||
"settings_notify_scope_all": "모든 작업",
|
||||
"settings_notify_scope_hint": "선택한 저장된 보기의 라벨/사용자 필터와 일치하는 작업만 알림을 보냅니다. 보기의 상태·정렬·그룹화는 여기서 무시됩니다.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ingen objekter ennå.",
|
||||
"action_error": "Handlingen mislyktes. Prøv igjen.",
|
||||
"area_id_optional": "Område (valgfritt)",
|
||||
"place_optional": "Sted (sone, valgfritt)",
|
||||
"remind_on_site": "Påminn bare når noen er der",
|
||||
"remind_on_site_hint": "Påminnelser venter til noen er i denne sonen. Den som kommer dit, får en melding med det som skal gjøres.",
|
||||
"place_missing": "Fant ikke sonen: påminnelser som hjemme",
|
||||
"place_home": "Hjemme",
|
||||
"installation_date_optional": "Installasjonsdato (valgfritt)",
|
||||
"warranty_expiry_optional": "Garanti utløper (valgfritt)",
|
||||
"warranty": "Garanti",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "Eier",
|
||||
"feat_completion_actions": "Fullføringshandlinger",
|
||||
"feat_completion_actions_desc": "HA-handling per oppgave ved fullføring + hurtigfullføring med QR og forhåndsinnstilte verdier.",
|
||||
"feat_places": "Steder",
|
||||
"feat_places_desc": "Objekter som vedlikeholdes et annet sted (en Home Assistant-sone): påminnelser bare når noen er der, og en melding ved ankomst.",
|
||||
"on_complete_action_title": "Ved fullføring: utløs HA-handling (valgfritt)",
|
||||
"on_complete_action_desc": "Kaller en HA-tjeneste når oppgaven fullføres — f.eks. tilbakestille en teller på enheten.",
|
||||
"on_complete_action_target": "Målentitet",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Bruker del: {name}",
|
||||
"label_filter": "Etikett",
|
||||
"all_labels": "Alle etiketter",
|
||||
"filter_place": "Sted",
|
||||
"filter_place_all": "Alle steder",
|
||||
"settings_notify_scope": "Varsle kun for visning",
|
||||
"settings_notify_scope_all": "Alle oppgaver",
|
||||
"settings_notify_scope_hint": "Bare oppgaver som matcher etikett-/brukerfiltrene til valgt visning sender påminnelser. Visningens status, sortering og gruppering ignoreres her.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Nog geen objecten.",
|
||||
"action_error": "Actie mislukt. Probeer het opnieuw.",
|
||||
"area_id_optional": "Gebied (optioneel)",
|
||||
"place_optional": "Locatie (zone, optioneel)",
|
||||
"remind_on_site": "Alleen herinneren als er iemand is",
|
||||
"remind_on_site_hint": "Herinneringen wachten tot iemand in deze zone is. Wie daar aankomt, krijgt een bericht met wat er te doen is.",
|
||||
"place_missing": "Zone niet gevonden: herinneringen zoals thuis",
|
||||
"place_home": "Thuis",
|
||||
"installation_date_optional": "Installatiedatum (optioneel)",
|
||||
"warranty_expiry_optional": "Garantie verloopt (optioneel)",
|
||||
"warranty": "Garantie",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Eigenaar",
|
||||
"feat_completion_actions": "Voltooiings-acties",
|
||||
"feat_completion_actions_desc": "Per taak HA-actie bij voltooien + snel-voltooien-QR met vooraf ingestelde waarden.",
|
||||
"feat_places": "Locaties",
|
||||
"feat_places_desc": "Objecten op een andere locatie (een Home Assistant-zone): herinneringen alleen als er iemand is, en een bericht bij aankomst.",
|
||||
"on_complete_action_title": "Bij voltooien: HA-actie uitvoeren (optioneel)",
|
||||
"on_complete_action_desc": "Roept een HA-service aan wanneer de taak is voltooid — bv. een teller op het apparaat resetten.",
|
||||
"on_complete_action_target": "Doel-entiteit",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Gebruikt onderdeel: {name}",
|
||||
"label_filter": "Label",
|
||||
"all_labels": "Alle labels",
|
||||
"filter_place": "Locatie",
|
||||
"filter_place_all": "Alle locaties",
|
||||
"settings_notify_scope": "Alleen melden voor weergave",
|
||||
"settings_notify_scope_all": "Alle taken",
|
||||
"settings_notify_scope_hint": "Alleen taken die overeenkomen met de label-/gebruikersfilters van de gekozen weergave sturen herinneringen. Status, sortering en groepering van de weergave worden hier genegeerd.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Brak obiektów.",
|
||||
"action_error": "Akcja nie powiodła się. Spróbuj ponownie.",
|
||||
"area_id_optional": "Obszar (opcjonalny)",
|
||||
"place_optional": "Miejsce (strefa, opcjonalnie)",
|
||||
"remind_on_site": "Przypominaj tylko, gdy ktoś tam jest",
|
||||
"remind_on_site_hint": "Przypomnienia czekają, aż ktoś będzie w tej strefie. Kto tam przyjedzie, dostaje wiadomość z tym, co jest do zrobienia.",
|
||||
"place_missing": "Nie znaleziono strefy: przypomnienia jak w domu",
|
||||
"place_home": "Dom",
|
||||
"installation_date_optional": "Data instalacji (opcjonalna)",
|
||||
"warranty_expiry_optional": "Wygaśnięcie gwarancji (opcjonalnie)",
|
||||
"warranty": "Gwarancja",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Właściciel",
|
||||
"feat_completion_actions": "Akcje po zakończeniu",
|
||||
"feat_completion_actions_desc": "Akcja HA per zadanie po zakończeniu + QR szybkiego zakończenia z predefiniowanymi wartościami.",
|
||||
"feat_places": "Miejsca",
|
||||
"feat_places_desc": "Obiekty w innym miejscu (strefa Home Assistant): przypomnienia tylko wtedy, gdy ktoś tam jest, i wiadomość po przybyciu.",
|
||||
"on_complete_action_title": "Po zakończeniu: wywołaj akcję HA (opcjonalnie)",
|
||||
"on_complete_action_desc": "Wywołuje usługę HA po zakończeniu zadania — np. zresetuj licznik urządzenia.",
|
||||
"on_complete_action_target": "Encja docelowa",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Używa części: {name}",
|
||||
"label_filter": "Etykieta",
|
||||
"all_labels": "Wszystkie etykiety",
|
||||
"filter_place": "Miejsce",
|
||||
"filter_place_all": "Wszystkie miejsca",
|
||||
"settings_notify_scope": "Powiadamiaj tylko dla widoku",
|
||||
"settings_notify_scope_all": "Wszystkie zadania",
|
||||
"settings_notify_scope_hint": "Przypomnienia wysyłają tylko zadania pasujące do filtrów etykiety/użytkownika wybranego widoku. Status, sortowanie i grupowanie widoku są tu ignorowane.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Ainda não há objetos.",
|
||||
"action_error": "A ação falhou. Tente novamente.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Local (zona, opcional)",
|
||||
"remind_on_site": "Lembrar só quando alguém estiver lá",
|
||||
"remind_on_site_hint": "Os lembretes esperam até alguém estar nesta zona. Quem chega lá recebe uma mensagem com o que está pendente.",
|
||||
"place_missing": "Zona não encontrada: lembretes como em casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data de instalação (opcional)",
|
||||
"warranty_expiry_optional": "Fim da garantia (opcional)",
|
||||
"warranty": "Garantia",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Proprietário",
|
||||
"feat_completion_actions": "Ações de conclusão",
|
||||
"feat_completion_actions_desc": "Ação do HA por tarefa ao concluir + QR de conclusão rápida com valores predefinidos.",
|
||||
"feat_places": "Locais",
|
||||
"feat_places_desc": "Objetos mantidos em outro local (uma zona do Home Assistant): lembretes só quando alguém está lá e uma mensagem na chegada.",
|
||||
"on_complete_action_title": "Ao concluir: acionar ação do HA (opcional)",
|
||||
"on_complete_action_desc": "Chama um serviço do HA quando a tarefa é concluída — ex.: zerar um contador no dispositivo.",
|
||||
"on_complete_action_target": "Entidade alvo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa a peça: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas as etiquetas",
|
||||
"filter_place": "Local",
|
||||
"filter_place_all": "Todos os locais",
|
||||
"settings_notify_scope": "Notificar apenas para a visualização",
|
||||
"settings_notify_scope_all": "Todas as tarefas",
|
||||
"settings_notify_scope_hint": "Apenas tarefas que correspondem aos filtros de etiqueta/usuário da visualização salva selecionada enviam lembretes. Status, ordenação e agrupamento da visualização são ignorados aqui.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Ainda sem objetos.",
|
||||
"action_error": "Ação falhada. Tente novamente.",
|
||||
"area_id_optional": "Área (opcional)",
|
||||
"place_optional": "Local (zona, opcional)",
|
||||
"remind_on_site": "Lembrar só quando alguém lá estiver",
|
||||
"remind_on_site_hint": "Os lembretes esperam até alguém estar nesta zona. Quem lá chega recebe uma mensagem com o que está pendente.",
|
||||
"place_missing": "Zona não encontrada: lembretes como em casa",
|
||||
"place_home": "Casa",
|
||||
"installation_date_optional": "Data de instalação (opcional)",
|
||||
"warranty_expiry_optional": "Validade da garantia (opcional)",
|
||||
"warranty": "Garantia",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Proprietário",
|
||||
"feat_completion_actions": "Ações de conclusão",
|
||||
"feat_completion_actions_desc": "Ação HA por tarefa ao concluir + QR de conclusão rápida com valores predefinidos.",
|
||||
"feat_places": "Locais",
|
||||
"feat_places_desc": "Objetos mantidos noutro local (uma zona do Home Assistant): lembretes só quando alguém lá está e uma mensagem à chegada.",
|
||||
"on_complete_action_title": "Na conclusão: acionar ação HA (opcional)",
|
||||
"on_complete_action_desc": "Chama um serviço HA quando a tarefa é concluída — p. ex. reiniciar um contador no dispositivo.",
|
||||
"on_complete_action_target": "Entidade alvo",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Usa a peça: {name}",
|
||||
"label_filter": "Etiqueta",
|
||||
"all_labels": "Todas as etiquetas",
|
||||
"filter_place": "Local",
|
||||
"filter_place_all": "Todos os locais",
|
||||
"settings_notify_scope": "Notificar apenas para a vista",
|
||||
"settings_notify_scope_all": "Todas as tarefas",
|
||||
"settings_notify_scope_hint": "Apenas as tarefas que correspondem aos filtros de etiqueta/utilizador da vista escolhida enviam lembretes. O estado, a ordenação e o agrupamento da vista são ignorados aqui.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Пока нет объектов.",
|
||||
"action_error": "Не удалось выполнить действие. Попробуйте ещё раз.",
|
||||
"area_id_optional": "Зона (опционально)",
|
||||
"place_optional": "Место (зона, необязательно)",
|
||||
"remind_on_site": "Напоминать, только когда там кто-то есть",
|
||||
"remind_on_site_hint": "Напоминания ждут, пока кто-нибудь окажется в этой зоне. Кто туда приезжает, получает сообщение о том, что нужно сделать.",
|
||||
"place_missing": "Зона не найдена: напоминания как дома",
|
||||
"place_home": "Дом",
|
||||
"installation_date_optional": "Дата установки (опционально)",
|
||||
"warranty_expiry_optional": "Окончание гарантии (опционально)",
|
||||
"warranty": "Гарантия",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Владелец",
|
||||
"feat_completion_actions": "Действия при завершении",
|
||||
"feat_completion_actions_desc": "HA-действие по задаче при завершении + QR быстрого завершения с предустановленными значениями.",
|
||||
"feat_places": "Места",
|
||||
"feat_places_desc": "Объекты в другом месте (зона Home Assistant): напоминания только когда там кто-то есть, и сообщение по прибытии.",
|
||||
"on_complete_action_title": "При завершении: запустить HA-действие (опционально)",
|
||||
"on_complete_action_desc": "Вызывает HA-сервис при завершении задачи — напр., сбросить счётчик на устройстве.",
|
||||
"on_complete_action_target": "Целевая сущность",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Использует деталь: {name}",
|
||||
"label_filter": "Метка",
|
||||
"all_labels": "Все метки",
|
||||
"filter_place": "Место",
|
||||
"filter_place_all": "Все места",
|
||||
"settings_notify_scope": "Уведомлять только для представления",
|
||||
"settings_notify_scope_all": "Все задачи",
|
||||
"settings_notify_scope_hint": "Напоминания отправляют только задачи, совпадающие с фильтрами метки/пользователя выбранного представления. Статус, сортировка и группировка представления здесь игнорируются.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Inga objekt än.",
|
||||
"action_error": "Åtgärden misslyckades. Försök igen.",
|
||||
"area_id_optional": "Område (valfritt)",
|
||||
"place_optional": "Plats (zon, valfritt)",
|
||||
"remind_on_site": "Påminn bara när någon är där",
|
||||
"remind_on_site_hint": "Påminnelser väntar tills någon är i den här zonen. Den som kommer dit får ett meddelande med det som ska göras.",
|
||||
"place_missing": "Zonen hittades inte: påminnelser som hemma",
|
||||
"place_home": "Hemma",
|
||||
"installation_date_optional": "Installationsdatum (valfritt)",
|
||||
"warranty_expiry_optional": "Garantins utgång (valfritt)",
|
||||
"warranty": "Garanti",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Ägare",
|
||||
"feat_completion_actions": "Slutförande-åtgärder",
|
||||
"feat_completion_actions_desc": "HA-åtgärd per uppgift vid slutförande + snabb-slutför-QR med förinställda värden.",
|
||||
"feat_places": "Platser",
|
||||
"feat_places_desc": "Objekt som sköts på en annan plats (en Home Assistant-zon): påminnelser bara när någon är där, och ett meddelande vid ankomst.",
|
||||
"on_complete_action_title": "Vid slutförande: utlös HA-åtgärd (valfritt)",
|
||||
"on_complete_action_desc": "Anropar en HA-tjänst när uppgiften slutförs — t.ex. återställ en räknare på enheten.",
|
||||
"on_complete_action_target": "Målentitet",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Använder reservdel: {name}",
|
||||
"label_filter": "Etikett",
|
||||
"all_labels": "Alla etiketter",
|
||||
"filter_place": "Plats",
|
||||
"filter_place_all": "Alla platser",
|
||||
"settings_notify_scope": "Avisera endast för vy",
|
||||
"settings_notify_scope_all": "Alla uppgifter",
|
||||
"settings_notify_scope_hint": "Endast uppgifter som matchar den valda vyns etikett-/användarfilter skickar påminnelser. Vyns status, sortering och gruppering ignoreras här.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "Henüz nesne yok.",
|
||||
"action_error": "Eylem başarısız oldu. Lütfen tekrar deneyin.",
|
||||
"area_id_optional": "Alan (isteğe bağlı)",
|
||||
"place_optional": "Yer (bölge, isteğe bağlı)",
|
||||
"remind_on_site": "Yalnızca biri oradayken hatırlat",
|
||||
"remind_on_site_hint": "Hatırlatmalar biri bu bölgede olana kadar bekler. Oraya varan kişi yapılacakların listesini içeren bir mesaj alır.",
|
||||
"place_missing": "Bölge bulunamadı: hatırlatmalar evdeki gibi",
|
||||
"place_home": "Ev",
|
||||
"installation_date_optional": "Kurulum tarihi (isteğe bağlı)",
|
||||
"warranty_expiry_optional": "Garanti bitişi (isteğe bağlı)",
|
||||
"warranty": "Garanti",
|
||||
@@ -813,6 +818,8 @@
|
||||
"owner_label": "Sahip",
|
||||
"feat_completion_actions": "Tamamlama eylemleri",
|
||||
"feat_completion_actions_desc": "Görev başına tamamlamada HA eylemi + önceden ayarlı değerlerle hızlı tamamlama QR'ı.",
|
||||
"feat_places": "Yerler",
|
||||
"feat_places_desc": "Başka bir yerde (Home Assistant bölgesi) bakımı yapılan nesneler: hatırlatmalar yalnızca biri oradayken, varışta bir mesaj.",
|
||||
"on_complete_action_title": "Tamamlandığında: HA eylemi tetikle (isteğe bağlı)",
|
||||
"on_complete_action_desc": "Görev tamamlandığında bir HA servisi çağırır — örn. cihazdaki bir sayacı sıfırlar.",
|
||||
"on_complete_action_target": "Hedef varlık",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Kullanılan parça: {name}",
|
||||
"label_filter": "Etiket",
|
||||
"all_labels": "Tüm etiketler",
|
||||
"filter_place": "Yer",
|
||||
"filter_place_all": "Tüm yerler",
|
||||
"settings_notify_scope": "Yalnızca şu görünüm için bildir",
|
||||
"settings_notify_scope_all": "Tüm görevler",
|
||||
"settings_notify_scope_hint": "Yalnızca seçili kayıtlı görünümün etiket/kullanıcı filtreleriyle eşleşen görevler hatırlatma gönderir. Görünümün durum, sıralama ve gruplaması burada dikkate alınmaz.",
|
||||
|
||||
@@ -545,6 +545,11 @@
|
||||
"no_objects": "Поки немає об'єктів.",
|
||||
"action_error": "Дія не вдалась. Спробуйте ще раз.",
|
||||
"area_id_optional": "Зона (необов'язково)",
|
||||
"place_optional": "Місце (зона, необов'язково)",
|
||||
"remind_on_site": "Нагадувати, лише коли там хтось є",
|
||||
"remind_on_site_hint": "Нагадування чекають, поки хтось буде в цій зоні. Хто туди прибуває, отримує повідомлення про те, що потрібно зробити.",
|
||||
"place_missing": "Зону не знайдено: нагадування як удома",
|
||||
"place_home": "Дім",
|
||||
"installation_date_optional": "Дата встановлення (необов'язково)",
|
||||
"warranty_expiry_optional": "Закінчення гарантії (необов'язково)",
|
||||
"warranty": "Гарантія",
|
||||
@@ -781,6 +786,8 @@
|
||||
"owner_label": "Власник",
|
||||
"feat_completion_actions": "Дії при завершенні",
|
||||
"feat_completion_actions_desc": "Дія HA по завданню при завершенні + QR швидкого завершення з попередньо встановленими значеннями.",
|
||||
"feat_places": "Місця",
|
||||
"feat_places_desc": "Об'єкти в іншому місці (зона Home Assistant): нагадування лише тоді, коли там хтось є, і повідомлення після прибуття.",
|
||||
"on_complete_action_title": "При завершенні: викликати HA-дію (опційно)",
|
||||
"on_complete_action_desc": "Викликає HA-сервіс, коли завдання завершено — напр., скинути лічильник на пристрої.",
|
||||
"on_complete_action_target": "Цільова сутність",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "Використовує деталь: {name}",
|
||||
"label_filter": "Мітка",
|
||||
"all_labels": "Усі мітки",
|
||||
"filter_place": "Місце",
|
||||
"filter_place_all": "Усі місця",
|
||||
"settings_notify_scope": "Сповіщати лише для подання",
|
||||
"settings_notify_scope_all": "Усі завдання",
|
||||
"settings_notify_scope_hint": "Нагадування надсилають лише завдання, що відповідають фільтрам мітки/користувача обраного подання. Статус, сортування та групування подання тут ігноруються.",
|
||||
|
||||
@@ -547,6 +547,11 @@
|
||||
"no_objects": "暂无维护项。",
|
||||
"action_error": "操作失败。请重试。",
|
||||
"area_id_optional": "区域 (可选)",
|
||||
"place_optional": "地点(区域,可选)",
|
||||
"remind_on_site": "仅当有人在场时提醒",
|
||||
"remind_on_site_hint": "提醒会等到有人在此区域时再发送。到达那里的人会收到一条列出待办事项的消息。",
|
||||
"place_missing": "未找到区域:按在家处理提醒",
|
||||
"place_home": "家",
|
||||
"installation_date_optional": "安装日期 (可选)",
|
||||
"warranty_expiry_optional": "保修到期 (可选)",
|
||||
"warranty": "保修",
|
||||
@@ -806,6 +811,8 @@
|
||||
"owner_label": "所有者",
|
||||
"feat_completion_actions": "完成动作",
|
||||
"feat_completion_actions_desc": "为每个任务配置完成时的 HA 动作 + 预设值的快速完成二维码。",
|
||||
"feat_places": "地点",
|
||||
"feat_places_desc": "在其他地点(Home Assistant 区域)维护的对象:仅当有人在场时提醒,并在到达时发送消息。",
|
||||
"on_complete_action_title": "完成时:触发 HA 动作(可选)",
|
||||
"on_complete_action_desc": "任务完成时调用 HA 服务 — 例如重置设备上的物理计数器。",
|
||||
"on_complete_action_target": "目标实体",
|
||||
@@ -1125,6 +1132,8 @@
|
||||
"adopt_problem_part": "使用配件:{name}",
|
||||
"label_filter": "标签",
|
||||
"all_labels": "所有标签",
|
||||
"filter_place": "地点",
|
||||
"filter_place_all": "所有地点",
|
||||
"settings_notify_scope": "仅为该视图发送通知",
|
||||
"settings_notify_scope_all": "所有任务",
|
||||
"settings_notify_scope_hint": "只有匹配所选视图的标签/用户筛选的任务才会发送提醒。视图的状态、排序和分组在此处被忽略。",
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+301
@@ -0,0 +1,301 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{e as y}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-PCR5FRSH.js";import{d as m}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-RHKFQ4Q2.js";import{a as h}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-GM2CHGSG.js";import{H as b,a as o,b as u,c as n,f as l,h as v,l as g,m as d,s as r,u as f}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";var a=class extends v{constructor(){super(...arguments);this._open=!1;this._loading=!1;this._adopting=!1;this._error="";this._sensors=[];this._selected=new Set;this._objectNames={};this._objects=[];this._covered={};this._users=[];this._responsible="";this._forMinutes="0";this._localeReady=!1;this._userService=null;this._toggle=t=>{let i=new Set(this._selected);i.has(t)?i.delete(t):i.add(t),this._selected=i};this._toggleAll=()=>{this._selected.size===this._sensors.length?this._selected=new Set:this._selected=new Set(this._sensors.map(t=>t.entity_id))};this._adopt=async()=>{if(this._selected.size===0||this._adopting)return;this._error="";let t=this._sensors.filter(e=>this._selected.has(e.entity_id)).map(e=>({entity_id:e.entity_id,name:e.name,entry_id:this._existingEntryFor(e)??void 0,object_name:this._effectiveName(e),device_id:e.device_id??void 0,part_id:e.suggested_part_id??void 0,responsible_user_id:this._responsible||void 0,for_minutes:parseInt(this._forMinutes,10)>0?parseInt(this._forMinutes,10):void 0})),i=await h(this,{type:"maintenance_supporter/problem_sensors/adopt",selections:t},{busy:e=>{this._adopting=e},onError:e=>{this._error=e}});i!==void 0&&(this.dispatchEvent(new CustomEvent("problem-sensors-adopted",{bubbles:!0,composed:!0,detail:i})),this._open=!1)}}get _lang(){return b(this.hass)}updated(t){t.has("hass")&&this.hass&&!this._localeReady&&(this._localeReady=!0,f(this._lang).then(()=>this.requestUpdate()))}async open(){this._open=!0,this._loading=!0,this._error="",this._sensors=[],this._selected=new Set,this._objectNames={},this._responsible="",this._forMinutes="0",this._userService?this._userService.updateHass(this.hass):this._userService=new y(this.hass);let[t,i,e]=await Promise.all([h(this,{type:"maintenance_supporter/problem_sensors/discover"},{onError:s=>{this._error=s}}),this._userService.getUsers().catch(()=>[]),this.hass.connection.sendMessagePromise({type:"maintenance_supporter/objects"}).catch(()=>({objects:[]}))]);this._loading=!1,t!==void 0&&(this._objects=(e?.objects||[]).filter(s=>!s.object.archived_at).map(s=>({entry_id:s.entry_id,name:s.object.name,tasks:(s.tasks||[]).length})),this._sensors=t?.sensors||[],this._covered=Object.fromEntries(this._sensors.map(s=>[s.entity_id,s.covered_by??null])),this._selected=new Set(this._sensors.filter(s=>!s.covered_by).map(s=>s.entity_id)),this._users=i)}_defaultName(t){return t.suggested_entry_id?t.suggested_object_name:t.candidate?.name??t.suggested_object_name}_effectiveName(t){return(this._objectNames[t.entity_id]??"").trim()||this._defaultName(t)}_existingEntryFor(t){let i=this._effectiveName(t),e=t.suggested_entry_id||t.target_entry_id||null;if(i===this._defaultName(t)&&e)return e;let s=this._objects.find(c=>c.name.trim().toLowerCase()===i.toLowerCase());return s?s.entry_id:null}_schedulePreview(){clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._preview()},350)}async _preview(){let t=this._sensors.map(e=>({entity_id:e.entity_id,name:e.name,entry_id:this._existingEntryFor(e)})),i=await h(this,{type:"maintenance_supporter/problem_sensors/preview",selections:t},{onError:()=>{}});i?.covered&&(this._covered={...this._covered,...i.covered})}_summary(t){let i=new Map;for(let e of this._sensors){if(!this._selected.has(e.entity_id))continue;let s=this._existingEntryFor(e),c=this._effectiveName(e),_=s??`new:${c.toLowerCase()}`,p=i.get(_)??{name:c,entry:s,adding:0};p.adding+=1,i.set(_,p)}return i.size===0?l:n`
|
||||
<div class="summary">
|
||||
<div class="summary-title">${r("adopt_summary_title",t)}</div>
|
||||
${[...i.values()].map(e=>{if(!e.entry)return n`<div class="summary-line new">
|
||||
${r("setups_new_object_count",t).replace("{name}",e.name).replace("{count}",String(e.adding))}
|
||||
</div>`;let s=this._objects.find(c=>c.entry_id===e.entry)?.tasks??0;return n`<div class="summary-line">
|
||||
${r("adopt_summary_existing",t).replace("{name}",e.name).replace("{before}",String(s)).replace("{after}",String(s+e.adding))}
|
||||
</div>`})}
|
||||
</div>
|
||||
`}_close(){clearTimeout(this._previewTimer),this._open=!1}_targetLabel(t,i){if(t.candidate&&this._existingEntryFor(t)===t.candidate.entry_id){let e=t.candidate.reasons.map(s=>r(`setups_reason_${s}`,i)).join(", ");return r("setups_target_match",i).replace("{name}",t.candidate.name).replace("{reasons}",e)}return this._effectiveName(t)}render(){if(!this._open)return n``;let t=this._lang,i=this._sensors.length>0&&this._selected.size===this._sensors.length;return n`
|
||||
<div class="overlay" @click=${this._close}>
|
||||
<div class="card" @click=${e=>e.stopPropagation()}>
|
||||
<div class="title">${r("adopt_problem_title",t)}</div>
|
||||
<div class="hint">${r("adopt_problem_hint",t)}</div>
|
||||
${this._error?n`<div class="error">${this._error}</div>`:l}
|
||||
|
||||
${this._loading?n`<div class="loading">…</div>`:this._sensors.length===0?n`<div class="empty">${r("adopt_problem_none",t)}</div>`:n`
|
||||
<label class="select-all">
|
||||
<input
|
||||
type="checkbox"
|
||||
.checked=${i}
|
||||
@change=${this._toggleAll}
|
||||
/>
|
||||
<span>${r("selected",t)}: ${this._selected.size} / ${this._sensors.length}</span>
|
||||
</label>
|
||||
<div class="row-sub adopt-object-hint">${r("adopt_object_hint",t)}</div>
|
||||
<datalist id="adopt-object-names">
|
||||
${this._objects.map(e=>n`<option value=${e.name}></option>`)}
|
||||
</datalist>
|
||||
<div class="list">
|
||||
${this._sensors.map(e=>{let s=this._selected.has(e.entity_id),c=e.state==="on",_=[e.device_name,e.area_name].filter(Boolean).join(" \xB7 ");return n`
|
||||
<label class="row">
|
||||
<input
|
||||
type="checkbox"
|
||||
.checked=${s}
|
||||
@change=${()=>this._toggle(e.entity_id)}
|
||||
/>
|
||||
<div class="row-main">
|
||||
<div class="row-top">
|
||||
<span class="row-name">${e.name}</span>
|
||||
<span class="chip ${c?"chip-active":"chip-ok"}">
|
||||
${c?r("adopt_problem_active",t):r("adopt_problem_ok",t)}
|
||||
</span>
|
||||
</div>
|
||||
${_?n`<div class="row-sub">${_}</div>`:l}
|
||||
${s?n`<div class="row-object" @click=${p=>p.stopPropagation()}>
|
||||
<input
|
||||
class="adopt-object"
|
||||
list="adopt-object-names"
|
||||
aria-label=${r("object",t)}
|
||||
placeholder=${this._defaultName(e)}
|
||||
.value=${this._objectNames[e.entity_id]??this._defaultName(e)}
|
||||
@input=${p=>{this._objectNames={...this._objectNames,[e.entity_id]:p.target.value},this._schedulePreview()}}
|
||||
/>
|
||||
</div>`:l}
|
||||
<div class="row-target">
|
||||
→ ${this._targetLabel(e,t)}${this._existingEntryFor(e)?l:n` <span class="new-tag">${r("adopt_problem_new_object",t)}</span>`}
|
||||
</div>
|
||||
${this._covered[e.entity_id]?n`<div class="maybe">
|
||||
${r("setups_maybe_covered",t).replace("{name}",this._covered[e.entity_id].name)}
|
||||
</div>`:l}
|
||||
${e.suggested_part_name?n`<div class="row-part">
|
||||
<ha-icon icon="mdi:package-variant-closed"></ha-icon>
|
||||
${r("adopt_problem_part",t).replace("{name}",e.suggested_part_name)}
|
||||
</div>`:l}
|
||||
</div>
|
||||
</label>
|
||||
`})}
|
||||
</div>
|
||||
`}
|
||||
|
||||
${!this._loading&&this._sensors.length>0?this._summary(t):l}
|
||||
|
||||
${!this._loading&&this._sensors.length>0?n`
|
||||
<label class="responsible">
|
||||
<span>${r("for_at_least_minutes",t)}</span>
|
||||
<input
|
||||
class="for-input"
|
||||
type="number"
|
||||
min=${m[0]}
|
||||
max=${m[1]}
|
||||
.value=${this._forMinutes}
|
||||
@input=${e=>this._forMinutes=e.target.value}
|
||||
/>
|
||||
</label>
|
||||
<div class="for-hint">${r("adopt_for_minutes_hint",t)}</div>
|
||||
`:l}
|
||||
|
||||
${!this._loading&&this._sensors.length>0&&this._users.length>0?n`
|
||||
<label class="responsible">
|
||||
<span>${r("adopt_problem_responsible",t)}</span>
|
||||
<select
|
||||
.value=${this._responsible}
|
||||
@change=${e=>{this._responsible=e.target.value}}
|
||||
>
|
||||
<option value="" ?selected=${!this._responsible}>${r("no_user_assigned",t)}</option>
|
||||
${this._users.map(e=>n`<option value=${e.id} ?selected=${e.id===this._responsible}>${e.name}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
`:l}
|
||||
|
||||
<div class="actions">
|
||||
<ha-button appearance="plain" @click=${this._close}>
|
||||
${r("cancel",t)}
|
||||
</ha-button>
|
||||
<ha-button
|
||||
@click=${this._adopt}
|
||||
.disabled=${this._selected.size===0||this._adopting}
|
||||
>
|
||||
${r("adopt_problem_adopt",t)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`}};a.styles=u`
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
.card {
|
||||
background: var(--card-background-color, #fff);
|
||||
color: var(--primary-text-color);
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
min-width: min(360px, calc(100vw - 24px));
|
||||
max-width: 560px;
|
||||
width: 90vw;
|
||||
max-height: 80vh;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
.title {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.hint {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
.error {
|
||||
color: var(--error-color, #f44336);
|
||||
font-size: 13px;
|
||||
}
|
||||
.loading,
|
||||
.empty {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: 14px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
.select-all {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--secondary-text-color);
|
||||
cursor: pointer;
|
||||
}
|
||||
.select-all input {
|
||||
cursor: pointer;
|
||||
}
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
overflow-y: auto;
|
||||
max-height: 50vh;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--divider-color);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.row input {
|
||||
margin-top: 2px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.row-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
.row-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.row-name {
|
||||
font-weight: 500;
|
||||
font-size: 13px;
|
||||
}
|
||||
.row-sub {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: 12px;
|
||||
}
|
||||
.row-object { margin-top: 6px; }
|
||||
.row-object input {
|
||||
width: 100%; box-sizing: border-box; padding: 6px 8px; font: inherit;
|
||||
border: 1px solid var(--divider-color); border-radius: 6px;
|
||||
background: var(--card-background-color); color: var(--primary-text-color);
|
||||
}
|
||||
.adopt-object-hint { margin: 0 0 8px; }
|
||||
.row-target {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: 12px;
|
||||
}
|
||||
.row-part {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.row-part ha-icon {
|
||||
--mdc-icon-size: 14px;
|
||||
}
|
||||
.new-tag {
|
||||
font-style: italic;
|
||||
}
|
||||
.maybe {
|
||||
font-size: 11px;
|
||||
color: var(--warning-color, #ff9800);
|
||||
}
|
||||
.summary {
|
||||
font-size: 12px;
|
||||
border-top: 1px dashed var(--divider-color);
|
||||
padding-top: 6px;
|
||||
}
|
||||
.summary-title {
|
||||
font-weight: 500;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.summary-line {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
.chip {
|
||||
font-size: 11px;
|
||||
padding: 1px 8px;
|
||||
border-radius: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.chip-active {
|
||||
background: var(--error-color, #f44336);
|
||||
color: #fff;
|
||||
}
|
||||
.chip-ok {
|
||||
background: var(--divider-color);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
.responsible {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--secondary-text-color);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.for-input {
|
||||
width: 70px;
|
||||
background: var(--card-background-color);
|
||||
color: var(--primary-text-color);
|
||||
border: 1px solid var(--divider-color);
|
||||
border-radius: 4px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
.for-hint {
|
||||
font-size: 11px;
|
||||
color: var(--secondary-text-color);
|
||||
margin: -4px 0 2px;
|
||||
}
|
||||
.responsible select {
|
||||
flex: 1;
|
||||
min-width: 140px;
|
||||
padding: 4px 6px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--divider-color);
|
||||
background: var(--card-background-color, #fff);
|
||||
color: var(--primary-text-color);
|
||||
font-size: 13px;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding-top: 8px;
|
||||
}
|
||||
`,o([g({attribute:!1})],a.prototype,"hass",2),o([d()],a.prototype,"_open",2),o([d()],a.prototype,"_loading",2),o([d()],a.prototype,"_adopting",2),o([d()],a.prototype,"_error",2),o([d()],a.prototype,"_sensors",2),o([d()],a.prototype,"_selected",2),o([d()],a.prototype,"_objectNames",2),o([d()],a.prototype,"_objects",2),o([d()],a.prototype,"_covered",2),o([d()],a.prototype,"_users",2),o([d()],a.prototype,"_responsible",2),o([d()],a.prototype,"_forMinutes",2);customElements.get("maintenance-adopt-problem-sensors-dialog")||customElements.define("maintenance-adopt-problem-sensors-dialog",a);export{a as MaintenanceAdoptProblemSensorsDialog};
|
||||
@@ -0,0 +1,279 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{a as X}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-MQRW7LAF.js";import{a as o}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-5MYBEQC2.js";import{f as E,g as M,h as z,i as Q,j as U,k as Y,l as q,m as G,n as R,o as A,p as W}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-MGSZZ3YF.js";import{a as B}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-EKN6HBJN.js";import{e as P,f as K}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-DRT62KZF.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-SYPCMUXO.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-55ND3GKE.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-RUYEMIDM.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-JQXHX4U4.js";import{B as S,H as F,K as g,L as v,O as N,P as I,T as w,V as T,a as $,c as p,f as y,h as H,l as k,m as j,n as C,q as D,s as a,u as L,y as O}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";function J(b,i,t,s){let l=b.entries.filter(e=>e.type==="completed").sort((e,n)=>e.ts-n.ts),d=`${b.from?t.date(b.from):"\u2026"} \u2013 ${b.to?t.date(b.to):"\u2026"}`,r=b.totals,h=[[i.completions,t.number(r.completions)],[i.totalCost,t.cost(r.totalCost)],[i.avgCost,r.avgCost!=null?t.cost(r.avgCost):i.none],[i.totalTime,r.totalDuration?t.duration(r.totalDuration):i.none]].map(([e,n])=>`<div class="kpi"><div class="k">${o(e)}</div><div class="v">${o(n)}</div></div>`).join(""),u=b.byObject.map(e=>`<tr>
|
||||
<td>${o(e.objectName)}</td>
|
||||
<td class="num">${o(t.number(e.completions))}</td>
|
||||
<td class="num">${o(t.cost(e.cost))}</td>
|
||||
<td class="num">${o(t.share(e.share))}</td>
|
||||
</tr>`).join(""),f=b.buckets.buckets.reduce((e,n)=>Math.max(e,n.cost),0),c=b.buckets.buckets.map(e=>{let n=f>0?Math.round(e.cost/f*100):0;return`<tr>
|
||||
<td class="nowrap">${o(t.bucket(e))}</td>
|
||||
<td class="num">${o(t.number(e.completions))}</td>
|
||||
<td class="bar-cell">${n>0?`<span class="bar" style="width:${n}%"></span>`:""}</td>
|
||||
<td class="num">${o(t.cost(e.cost))}</td>
|
||||
</tr>`}).join(""),m=l.map(e=>{let n=[e.notes,e.completedBy?`${i.completedBy}: ${e.completedBy}`:null].filter(Boolean).join(" \xB7 "),x=e.phaseName?`${e.taskName} \xB7 ${e.phaseName}`:e.taskName;return`<tr>
|
||||
<td class="nowrap">${o(t.date(e.timestamp))}</td>
|
||||
<td>${o(e.objectName)}</td>
|
||||
<td>${o(x)}</td>
|
||||
<td class="num">${e.cost!=null?o(t.cost(e.cost)):o(i.none)}</td>
|
||||
<td class="num">${e.duration!=null?o(t.duration(e.duration)):o(i.none)}</td>
|
||||
<td class="notes">${o(n)||o(i.none)}</td>
|
||||
</tr>`}).join(`
|
||||
`);return`<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>${o(i.title)} \u2014 ${o(b.areaName)}</title>
|
||||
<style>
|
||||
/* Printable sheet: it opens as a blob in whatever viewer the OS supplies
|
||||
(Companion = WebView, dark phones paint a dark default canvas), so the
|
||||
document states its own light scheme and paints its background. */
|
||||
:root { color-scheme: light; }
|
||||
* { box-sizing: border-box; }
|
||||
body { font: 13px/1.5 -apple-system, Segoe UI, Roboto, sans-serif; color: #1a1a1a; background: #fff; margin: 32px; }
|
||||
h1 { font-size: 22px; margin: 0 0 2px; }
|
||||
h2 { font-size: 15px; margin: 24px 0 8px; }
|
||||
.sub { color: #666; margin: 0 0 16px; }
|
||||
.kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 0 0 8px; }
|
||||
.kpi { border: 1px solid #ddd; border-radius: 6px; padding: 8px 10px; }
|
||||
.kpi .k { color: #777; font-size: 10.5px; text-transform: uppercase; letter-spacing: .04em; }
|
||||
.kpi .v { font-size: 16px; font-weight: 600; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: #666; border-bottom: 2px solid #ccc; padding: 6px 8px; }
|
||||
td { border-bottom: 1px solid #e5e5e5; padding: 6px 8px; vertical-align: top; }
|
||||
td.num, th.num { text-align: right; white-space: nowrap; }
|
||||
td.nowrap { white-space: nowrap; }
|
||||
td.notes { color: #444; white-space: pre-wrap; }
|
||||
td.bar-cell { width: 40%; vertical-align: middle; }
|
||||
.bar { display: block; height: 10px; background: #9aa7b8; border-radius: 0 3px 3px 0;
|
||||
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
||||
tfoot td { border-bottom: none; border-top: 2px solid #ccc; font-weight: 600; }
|
||||
tr { break-inside: avoid; }
|
||||
.cap-note { margin-top: 14px; color: #888; font-size: 11px; }
|
||||
@media print { body { margin: 12mm; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>${o(i.title)} \u2014 ${o(b.areaName)}</h1>
|
||||
<p class="sub">${o(i.period)}: ${o(d)} \xB7 ${o(i.generated)} ${o(t.date(s))}</p>
|
||||
<div class="kpis">${h}</div>
|
||||
|
||||
<h2>${o(i.costPerObject)}</h2>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th>${o(i.colObject)}</th><th class="num">${o(i.completions)}</th>
|
||||
<th class="num">${o(i.colCost)}</th><th class="num">${o(i.share)}</th>
|
||||
</tr></thead>
|
||||
<tbody>${u||`<tr><td colspan="4">${o(i.none)}</td></tr>`}</tbody>
|
||||
<tfoot><tr>
|
||||
<td>${o(i.totalCost)}</td><td class="num">${o(t.number(r.completions))}</td>
|
||||
<td class="num">${o(t.cost(r.totalCost))}</td><td></td>
|
||||
</tr></tfoot>
|
||||
</table>
|
||||
|
||||
<h2>${o(i.costPerBucket)}</h2>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th>${o(i.period)}</th><th class="num">${o(i.completions)}</th>
|
||||
<th></th><th class="num">${o(i.colCost)}</th>
|
||||
</tr></thead>
|
||||
<tbody>${c||`<tr><td colspan="4">${o(i.none)}</td></tr>`}</tbody>
|
||||
</table>
|
||||
|
||||
<h2>${o(i.historyHeading)} (${o(t.number(l.length))})</h2>
|
||||
<table>
|
||||
<thead><tr>
|
||||
<th>${o(i.colDate)}</th><th>${o(i.colObject)}</th><th>${o(i.colTask)}</th>
|
||||
<th class="num">${o(i.colCost)}</th><th class="num">${o(i.colDuration)}</th><th>${o(i.colNotes)}</th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
${m||`<tr><td colspan="6">${o(i.none)}</td></tr>`}
|
||||
</tbody>
|
||||
<tfoot><tr>
|
||||
<td colspan="3">${o(i.totalCost)}</td>
|
||||
<td class="num">${o(t.cost(r.totalCost))}</td>
|
||||
<td class="num">${r.totalDuration?o(t.duration(r.totalDuration)):""}</td><td></td>
|
||||
</tr></tfoot>
|
||||
</table>
|
||||
${b.capped?`<p class="cap-note">${o(i.capNote)}</p>`:""}
|
||||
</body>
|
||||
</html>`}var Z=25,V=5,tt={completed:C.ok,missed:C.overdue,reset:C.paused,skipped:"var(--secondary-text-color)"},_=class extends H{constructor(){super(...arguments);this.areaKey="";this.objects=[];this.showArchived=!1;this.currencySymbol="";this.userName=()=>null;this._from="";this._to="";this._entryFilter="";this._taskQuery="";this._expanded=!1;this._printing=!1;this._histories=new X(this);this._localeReady=!1;this._filtersFor=null;this._memo=null}createRenderRoot(){return this}get _lang(){return F(this.hass)}willUpdate(t){if(super.willUpdate(t),t.has("areaKey")&&this._filtersFor!==this.areaKey){this._filtersFor=this.areaKey;let s=R();this._from=s.from,this._to=s.to,this._entryFilter="",this._taskQuery="",this._expanded=!1}if(t.has("objects")||t.has("areaKey")||t.has("showArchived")||t.has("hass")&&t.get("hass")===void 0){let s=this._areaObjects().flatMap(l=>l.tasks.map(d=>({entryId:l.entry_id,task:d})));this._histories.sync(this.hass,s)}}updated(t){super.updated(t),!this._localeReady&&this.hass&&(this._localeReady=!0,L(this._lang).then(()=>this.requestUpdate()))}_areaObjects(){return z(this.objects,this.areaKey,this.showArchived).sort((t,s)=>t.object.name.localeCompare(s.object.name))}_entries(t){let s=[this.objects,this.areaKey,this.showArchived,this._histories.version];if(this._memo&&this._memo.deps.every((d,r)=>d===s[r]))return this._memo.entries;let l=Q(t,(d,r)=>this._histories.historyOf(d,r));return this._memo={deps:s,entries:l},l}_figures(){let t=this._areaObjects(),s=this._entries(t),l={from:this._from||null,to:this._to||null},d=U(s,{...l,entryId:this._entryFilter||null,taskQuery:this._taskQuery}),r=this._entryFilter?t.filter(h=>h.entry_id===this._entryFilter):t;return{objects:t,entries:s,filtered:d,totals:Y(d),buckets:G(d,l),byObject:q(d,r)}}_setRange(t){this._from=t.from,this._to=t.to,this._expanded=!1}_openObject(t){this.dispatchEvent(new CustomEvent("open-object",{detail:{entryId:t},bubbles:!0,composed:!0}))}_openTask(t,s){this.dispatchEvent(new CustomEvent("open-task",{detail:{entryId:t,taskId:s},bubbles:!0,composed:!0}))}_bucketLabel(t,s){return t.month==null?String(t.year):`${T(t.month,this._lang,s)} ${t.year}`}_countText(t,s,l){let d=this._lang;return l===1?a(s,d):a(t,d).replace("{n}",g(l,d))}async _print(){if(this._printing)return;let t=K();this._printing=!0;try{await this._histories.settled()}finally{this._printing=!1}let s=this._lang,l=this.currencySymbol,{filtered:d,totals:r,buckets:h,byObject:u}=this._figures(),f={title:a("area_report_title",s),generated:a("report_generated",s),period:a("area_report_period",s),completions:a("area_kpi_completions",s),totalCost:a("total_cost",s),avgCost:a("avg_cost",s),totalTime:a("area_kpi_total_time",s),costPerObject:a("area_cost_per_object",s),costPerBucket:h.unit==="month"?a("area_cost_per_month",s):a("area_cost_per_year",s),share:a("area_cost_share",s),historyHeading:a("area_history_section",s),colDate:a("date",s),colObject:a("object",s),colTask:a("task_name",s),colCost:a("cost",s),colDuration:a("duration",s),colNotes:a("notes_label",s),completedBy:a("completed_by",s),capNote:a("object_history_cap_note",s),none:"\u2014"},c=d.filter(n=>n.type==="completed"),m=d.map(n=>({...n,completedBy:n.completedBy?this.userName(n.completedBy):null,notes:n.notes?B(n.notes,s):null})),e=J({areaName:E(this.areaKey,this.hass?.areas,a("no_area",s)),from:this._from||S(c[c.length-1]?.timestamp)||null,to:this._to||O(),totals:r,byObject:u,buckets:h,entries:m,capped:this._histories.capped},f,{date:n=>N(n,s),cost:n=>v(n,l,s),duration:n=>w(n,s),bucket:n=>this._bucketLabel(n,"long"),share:n=>`${g(n*100,s,0)} %`,number:n=>g(n,s)},new Date().toISOString());P(e,t)}_renderRangeChips(t){let s=this._lang,l=O(),d=R(l),r=u=>this._from===u.from&&this._to===u.to,h=W(t,Number(l.slice(0,4))).slice(0,V);return p`
|
||||
<div class="filter-chips area-range-chips">
|
||||
<button class="filter-chip ${r(d)?"active":""}" @click=${()=>this._setRange(R())}>
|
||||
${a("area_range_12m",s)}
|
||||
</button>
|
||||
${h.map(u=>p`
|
||||
<button class="filter-chip ${r(A(u))?"active":""}" @click=${()=>this._setRange(A(u))}>${u}</button>
|
||||
`)}
|
||||
<button class="filter-chip ${!this._from&&!this._to?"active":""}" @click=${()=>this._setRange({from:"",to:""})}>
|
||||
${a("area_range_all",s)}
|
||||
</button>
|
||||
</div>
|
||||
`}_renderChart(t){let s=this._lang,l=this.currencySymbol,d=t.reduce((c,m)=>Math.max(c,m.cost),0),r=t.reduce((c,m)=>Math.min(c,m.cost),0);if(d<=0&&r>=0)return p`<p class="area-empty">${a("area_no_costs",s)}</p>`;let h=c=>Math.round(c/(d-r)*1e3)/10,u=Math.max(1,Math.ceil(t.length/12)),f=t.map((c,m)=>({b:c,i:m})).filter(({i:c})=>c%u===0);return p`
|
||||
<div class="area-chart">
|
||||
<div class="area-chart-max">${v(d,l,s)}</div>
|
||||
<div class="area-chart-bars">
|
||||
${r<0?p`<div class="area-chart-zero" style="bottom: ${h(-r)}%"></div>`:y}
|
||||
${t.map(c=>{let m=`${this._bucketLabel(c,"long")}: ${v(c.cost,l,s)} \xB7 ${a("area_kpi_completions",s)}: ${g(c.completions,s)}`,e=c.cost<0?h(c.cost-r):h(-r);return p`<div class="area-bar" title=${m} aria-label=${m}>
|
||||
${c.cost!==0?p`<div class="area-bar-fill ${c.cost<0?"credit":""}" style="height: ${h(Math.abs(c.cost))}%${e?`; bottom: ${e}%`:""}"></div>`:y}
|
||||
</div>`})}
|
||||
</div>
|
||||
${r<0?p`<div class="area-chart-min">${v(r,l,s)}</div>`:y}
|
||||
<div class="area-chart-axis ${u>1?"grouped":""}">
|
||||
${f.map(({b:c,i:m})=>p`<span class="area-bar-label" style="flex-grow: ${Math.min(u,t.length-m)}">${c.month==null?String(c.year):p`${T(c.month,s,"short")}${c.month===0||m===0?p`<br />${c.year}`:y}`}</span>`)}
|
||||
</div>
|
||||
</div>
|
||||
`}render(){if(!this.hass||!this.areaKey)return y;let t=this._lang,s=this.currencySymbol,{objects:l,entries:d,filtered:r,totals:h,buckets:u,byObject:f}=this._figures(),c=l.reduce((e,n)=>e+n.tasks.filter(x=>this.showArchived||!x.archived).length,0),m=this._expanded?r:r.slice(0,Z);return p`
|
||||
<div class="detail-section area-view">
|
||||
<div class="detail-header">
|
||||
<h2 class="area-title">
|
||||
<ha-icon .icon=${M(this.areaKey,this.hass.areas)}></ha-icon>
|
||||
${E(this.areaKey,this.hass.areas,a("no_area",t))}
|
||||
</h2>
|
||||
<div class="action-buttons">
|
||||
<ha-button appearance="plain" class="area-print" .disabled=${this._printing} @click=${()=>this._print()}>
|
||||
<ha-icon icon="mdi:printer-outline"></ha-icon>
|
||||
${this._printing?a("loading",t):a("area_report_print",t)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="meta">
|
||||
${this._countText("area_object_count","area_object_count_one",l.length)} ·
|
||||
${this._countText("templates_task_count","templates_task_count_one",c)}
|
||||
${this._histories.loading?p` · <span class="area-loading">${a("loading",t)}</span>`:y}
|
||||
</p>
|
||||
|
||||
${this._renderRangeChips(d)}
|
||||
<div class="filter-bar area-filters">
|
||||
<ms-date-field
|
||||
kind="date"
|
||||
clearable
|
||||
.hass=${this.hass}
|
||||
.lang=${t}
|
||||
.label=${a("date_from",t)}
|
||||
.value=${this._from}
|
||||
@value-changed=${e=>{this._from=e.detail.value}}
|
||||
></ms-date-field>
|
||||
<ms-date-field
|
||||
kind="date"
|
||||
clearable
|
||||
.hass=${this.hass}
|
||||
.lang=${t}
|
||||
.label=${a("date_to",t)}
|
||||
.value=${this._to}
|
||||
@value-changed=${e=>{this._to=e.detail.value}}
|
||||
></ms-date-field>
|
||||
<label class="filter-field">
|
||||
<span class="filter-label">${a("object",t)}</span>
|
||||
<select class="area-object-filter" .value=${this._entryFilter}
|
||||
@change=${e=>{this._entryFilter=e.target.value}}>
|
||||
<option value="" ?selected=${!this._entryFilter}>${a("all_objects",t)}</option>
|
||||
${l.map(e=>p`<option value=${e.entry_id} ?selected=${e.entry_id===this._entryFilter}>${e.object.name}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
<input
|
||||
type="search"
|
||||
class="search-input area-task-filter"
|
||||
aria-label=${a("area_task_filter",t)}
|
||||
placeholder=${a("area_task_filter",t)}
|
||||
.value=${this._taskQuery}
|
||||
@input=${e=>{this._taskQuery=e.target.value}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="kpi-bar area-kpis">
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">${a("area_kpi_completions",t)}</div>
|
||||
<div class="kpi-value-large area-kpi-completions">${g(h.completions,t)}</div>
|
||||
</div>
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">${a("total_cost",t)}</div>
|
||||
<div class="kpi-value-large area-kpi-cost">${v(h.totalCost,s,t)}</div>
|
||||
</div>
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">${a("avg_cost",t)}</div>
|
||||
<div class="kpi-value-large">${h.avgCost!=null?v(h.avgCost,s,t):"\u2014"}</div>
|
||||
</div>
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">${a("area_kpi_total_time",t)}</div>
|
||||
<div class="kpi-value-large">${h.totalDuration?w(h.totalDuration,t):"\u2014"}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3>${u.unit==="month"?a("area_cost_per_month",t):a("area_cost_per_year",t)}</h3>
|
||||
${this._renderChart(u.buckets)}
|
||||
|
||||
<h3>${a("area_cost_per_object",t)}</h3>
|
||||
<div class="objects-table-wrap">
|
||||
<table class="objects-table area-object-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>${a("object",t)}</th>
|
||||
<th class="num">${a("area_kpi_completions",t)}</th>
|
||||
<th class="num">${a("cost",t)}</th>
|
||||
<th class="num">${a("area_cost_share",t)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${f.map(e=>p`
|
||||
<tr class="objects-table-row" @click=${()=>this._openObject(e.entryId)}>
|
||||
<td><span class="objects-table-name">${e.objectName}</span></td>
|
||||
<td class="num">${g(e.completions,t)}</td>
|
||||
<td class="num">${v(e.cost,s,t)}</td>
|
||||
<td class="num">
|
||||
<span class="area-share"><span class="area-share-fill" style="width: ${Math.round(e.share*100)}%"></span></span>
|
||||
${g(e.share*100,t,0)} %
|
||||
</td>
|
||||
</tr>
|
||||
`)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<h3>
|
||||
${a("area_history_section",t)}
|
||||
<span class="area-count">${g(r.length,t)}</span>
|
||||
</h3>
|
||||
${r.length===0?p`<p class="area-empty">${a("object_history_empty",t)}</p>`:p`
|
||||
<div class="objects-table-wrap">
|
||||
<table class="objects-table area-history-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>${a("date",t)}</th>
|
||||
<th></th>
|
||||
<th>${a("object",t)}</th>
|
||||
<th>${a("task_name",t)}</th>
|
||||
<th class="num">${a("cost",t)}</th>
|
||||
<th class="num">${a("duration",t)}</th>
|
||||
<th>${a("notes_label",t)}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${m.map(e=>{let n=e.notes?B(e.notes,t):"";return p`
|
||||
<tr class="objects-table-row area-history-row" @click=${()=>this._openTask(e.entryId,e.taskId)}>
|
||||
<td title=${I(e.timestamp,t)}>${N(e.timestamp,t)}</td>
|
||||
<td>
|
||||
<span class="area-entry-type" style="color: ${tt[e.type]??"inherit"}">
|
||||
<ha-icon .icon=${D[e.type]||"mdi:circle"}></ha-icon>${a(e.type,t)}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<button class="area-object-link" @click=${x=>{x.stopPropagation(),this._openObject(e.entryId)}}>
|
||||
${e.objectName}
|
||||
</button>
|
||||
</td>
|
||||
<td><button class="area-task-link">${e.taskName}${e.phaseName?` \xB7 ${e.phaseName}`:""}</button></td>
|
||||
<td class="num">${e.cost!=null?v(e.cost,s,t):"\u2014"}</td>
|
||||
<td class="num">${e.duration!=null?w(e.duration,t):"\u2014"}</td>
|
||||
<td class="oc-notes" title=${n}>${n||"\u2014"}</td>
|
||||
</tr>
|
||||
`})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
${r.length>m.length?p`<ha-button appearance="plain" class="area-more" @click=${()=>{this._expanded=!0}}>
|
||||
${a("show_all",t)} (${g(r.length,t)})
|
||||
</ha-button>`:y}
|
||||
`}
|
||||
${this._histories.capped?p`<p class="area-cap-note">${a("object_history_cap_note",t)}</p>`:y}
|
||||
</div>
|
||||
`}};$([k({attribute:!1})],_.prototype,"hass",2),$([k()],_.prototype,"areaKey",2),$([k({attribute:!1})],_.prototype,"objects",2),$([k({type:Boolean})],_.prototype,"showArchived",2),$([k()],_.prototype,"currencySymbol",2),$([k({attribute:!1})],_.prototype,"userName",2),$([j()],_.prototype,"_from",2),$([j()],_.prototype,"_to",2),$([j()],_.prototype,"_entryFilter",2),$([j()],_.prototype,"_taskQuery",2),$([j()],_.prototype,"_expanded",2),$([j()],_.prototype,"_printing",2);customElements.get("maintenance-area-view")||customElements.define("maintenance-area-view",_);export{_ as MaintenanceAreaView};
|
||||
@@ -0,0 +1,54 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{a as O}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-MQRW7LAF.js";import{q as j,r as E,s as L,t as R,u as C}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-MGSZZ3YF.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-SYPCMUXO.js";import{a as _,b as S,c as A}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-HFZZVTW7.js";import"/maintenance_supporter_panelfiles/panel-chunks/chunk-55ND3GKE.js";import{H as g,K as k,L as v,O as w,a as l,c as a,f as m,h as y,l as p,m as b,s as r,u as $,y as f}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";var q=[{key:"name",label:"area",num:!1},{key:"objects",label:"objects",num:!0},{key:"tasks",label:"tasks",num:!0},{key:"overdue",label:"overdue",num:!0},{key:"due_soon",label:"due_soon",num:!0},{key:"cost_year",label:"area_cost_year",num:!0},{key:"cost_total",label:"total_cost",num:!0},{key:"last",label:"last_performed",num:!1}],i=class extends y{constructor(){super(...arguments);this.objects=[];this.showArchived=!1;this.currencySymbol="";this._query="";this._sort=E(S(_.areaSort));this._histories=new O(this);this._localeReady=!1;this._memo=null}createRenderRoot(){return this}get _lang(){return g(this.hass)}willUpdate(t){if(super.willUpdate(t),t.has("objects")||t.has("showArchived")||t.has("hass")&&t.get("hass")===void 0){let o=this.objects.filter(s=>this.showArchived||!s.object.archived).flatMap(s=>s.tasks.map(n=>({entryId:s.entry_id,task:n})));this._histories.sync(this.hass,o)}}updated(t){super.updated(t),!this._localeReady&&this.hass&&(this._localeReady=!0,$(this._lang).then(()=>this.requestUpdate()))}_rows(t){let o=this._lang,s=[this.objects,this.showArchived,this._histories.version,this.hass?.areas,o,t];if(this._memo&&this._memo.deps.every((c,h)=>c===s[h]))return this._memo.rows;let n=j(this.objects,{showArchived:this.showArchived,areas:this.hass?.areas,noAreaLabel:r("no_area",o),year:t,historyOf:(c,h)=>this._histories.historyOf(c,h)});return this._memo={deps:s,rows:n},n}_setSort(t){this._sort=L(this._sort,t),A(_.areaSort,`${this._sort.key}:${this._sort.dir}`)}_open(t){this.dispatchEvent(new CustomEvent("open-area",{detail:{areaKey:t},bubbles:!0,composed:!0}))}_toggleArchived(){this.dispatchEvent(new CustomEvent("archived-toggle",{bubbles:!0,composed:!0}))}_headerLabel(t,o,s){return t==="area_cost_year"?r("area_cost_year",s).replace("{year}",String(o)):r(t,s)}render(){if(!this.hass)return m;let t=this._lang,o=Number(f().slice(0,4)),s=this.currencySymbol,n=this._rows(o),c=R(C(n,this._query),this._sort),h=this.objects.filter(e=>e.object.archived).length,d=e=>k(e,t);return a`
|
||||
<div class="filter-bar area-filter-bar">
|
||||
<input
|
||||
type="search"
|
||||
class="search-input"
|
||||
aria-label=${r("areas_filter",t)}
|
||||
placeholder=${r("areas_filter",t)}
|
||||
.value=${this._query}
|
||||
@input=${e=>{this._query=e.target.value}}
|
||||
/>
|
||||
${this._histories.loading?a`<span class="area-loading">${r("loading",t)}</span>`:m}
|
||||
${h>0?a`<ha-button class="archived-toggle ${this.showArchived?"active":""}" @click=${()=>this._toggleArchived()}>
|
||||
<ha-icon icon="mdi:archive-outline"></ha-icon>
|
||||
${this.showArchived?r("hide_archived",t):`${r("show_archived",t)} (${h})`}
|
||||
</ha-button>`:m}
|
||||
</div>
|
||||
${n.length===0?a`<div class="empty-state">${r("no_objects",t)}</div>`:c.length===0?a`<div class="empty-state">${r("areas_filter_none",t)}</div>`:a`
|
||||
<div class="objects-table-wrap">
|
||||
<table class="objects-table areas-table">
|
||||
<thead>
|
||||
<tr>
|
||||
${q.map(e=>{let u=this._sort.key===e.key;return a`<th class=${e.num?"num":""}
|
||||
aria-sort=${u?this._sort.dir==="asc"?"ascending":"descending":"none"}>
|
||||
<button class="area-sort ${u?"active":""}" title=${r("sort_label",t)} @click=${()=>this._setSort(e.key)}>
|
||||
${this._headerLabel(e.label,o,t)}
|
||||
${u?a`<ha-icon icon=${this._sort.dir==="asc"?"mdi:arrow-up":"mdi:arrow-down"}></ha-icon>`:m}
|
||||
</button>
|
||||
</th>`})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${c.map(e=>a`
|
||||
<tr class="objects-table-row" tabindex="0"
|
||||
@click=${()=>this._open(e.key)}
|
||||
@keydown=${u=>{u.key==="Enter"&&this._open(e.key)}}>
|
||||
<td>
|
||||
<ha-icon class="area-row-icon" .icon=${e.icon}></ha-icon>
|
||||
<span class="objects-table-name">${e.name}</span>
|
||||
</td>
|
||||
<td class="num">${d(e.objects)}</td>
|
||||
<td class="num">${d(e.tasks)}</td>
|
||||
<td class="num">${e.overdue?a`<span class="area-count overdue">${d(e.overdue)}</span>`:d(0)}</td>
|
||||
<td class="num">${e.dueSoon?a`<span class="area-count due-soon">${d(e.dueSoon)}</span>`:d(0)}</td>
|
||||
<td class="num">${v(e.costYear,s,t)}</td>
|
||||
<td class="num">${v(e.costTotal,s,t)}</td>
|
||||
<td>${e.lastCompletion?w(e.lastCompletion,t):"\u2014"}</td>
|
||||
</tr>
|
||||
`)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`}
|
||||
`}};l([p({attribute:!1})],i.prototype,"hass",2),l([p({attribute:!1})],i.prototype,"objects",2),l([p({type:Boolean})],i.prototype,"showArchived",2),l([p()],i.prototype,"currencySymbol",2),l([b()],i.prototype,"_query",2),l([b()],i.prototype,"_sort",2);customElements.get("maintenance-areas-view")||customElements.define("maintenance-areas-view",i);export{i as MaintenanceAreasView};
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import"/maintenance_supporter_panelfiles/panel-chunks/chunk-TX2GMEMJ.js";import{H as u,a as n,b as _,c as o,f as p,h as c,l as g,m as a,s}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";var d=["round_robin","least_completed","random"],v=["low","normal","high"],m=365,i=class extends c{constructor(){super(...arguments);this._open=!1;this._mode="assign";this._count=0;this._users=[];this._present=[];this._assignKind="one";this._person="";this._pool=new Set;this._rotation=d[0];this._addText="";this._remove=new Set;this._setWarning=!1;this._warning=7;this._setPriority=!1;this._priority="normal";this._setMute=!1;this._mute=!1;this._resolve=null}get _lang(){return u(this.hass)}open(t,e,r){return this._resolve?.(null),this._mode=t,this._count=e.length,this._users=[...r].sort((l,h)=>l.name.localeCompare(h.name)),this._present=[...new Set(e.flatMap(l=>l.labels||[]))].sort((l,h)=>l.localeCompare(h)),this._assignKind="one",this._person="",this._pool=new Set,this._rotation=d[0],this._addText="",this._remove=new Set,this._setWarning=!1,this._warning=7,this._setPriority=!1,this._priority="normal",this._setMute=!1,this._mute=!1,this._open=!0,new Promise(l=>{this._resolve=l})}_finish(t){this._open=!1;let e=this._resolve;this._resolve=null,e?.(t)}changes(){if(this._mode==="assign"){if(this._assignKind==="one")return{responsible_user_id:this._person||null,assignee_pool:null,rotation_strategy:null};let e=this._users.map(r=>r.id).filter(r=>this._pool.has(r));return e.length<2?null:{assignee_pool:e,rotation_strategy:this._rotation,responsible_user_id:null}}if(this._mode==="labels"){let e=[...new Set(this._addText.split(",").map(l=>l.trim()).filter(Boolean))],r=[...this._remove];return e.length||r.length?{labels_add:e,labels_remove:r}:null}let t={};return this._setWarning&&(t.warning_days=this._warning),this._setPriority&&(t.priority=this._priority),this._setMute&&(t.notify_enabled=!this._mute),Object.keys(t).length?t:null}_toggle(t,e){let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r}_renderAssign(t){return o`
|
||||
<div class="hint">${s("bulk_assign_hint",t)}</div>
|
||||
<label class="choice">
|
||||
<input type="radio" name="kind" .checked=${this._assignKind==="one"} @change=${()=>this._assignKind="one"} />
|
||||
${s("bulk_assign_one",t)}
|
||||
</label>
|
||||
${this._assignKind==="one"?o`<select class="person" .value=${this._person} @change=${e=>this._person=e.target.value}>
|
||||
<option value="" ?selected=${!this._person}>${s("unassigned",t)}</option>
|
||||
${this._users.map(e=>o`<option value=${e.id} ?selected=${this._person===e.id}>${e.name}</option>`)}
|
||||
</select>`:p}
|
||||
<label class="choice">
|
||||
<input type="radio" name="kind" .checked=${this._assignKind==="rotate"} @change=${()=>this._assignKind="rotate"} />
|
||||
${s("bulk_assign_rotate",t)}
|
||||
</label>
|
||||
${this._assignKind==="rotate"?o`<div class="pool">
|
||||
${this._users.map(e=>o`<label class="row">
|
||||
<input type="checkbox" .checked=${this._pool.has(e.id)} @change=${()=>this._pool=this._toggle(this._pool,e.id)} />
|
||||
${e.name}
|
||||
</label>`)}
|
||||
</div>
|
||||
<label class="field">
|
||||
<span>${s("rotation_strategy",t)}</span>
|
||||
<select class="rotation" .value=${this._rotation} @change=${e=>this._rotation=e.target.value}>
|
||||
${d.map(e=>o`<option value=${e} ?selected=${this._rotation===e}>${s(`rotation_${e}`,t)}</option>`)}
|
||||
</select>
|
||||
</label>
|
||||
${this._pool.size<2?o`<div class="hint">${s("bulk_rotation_min_two",t)}</div>`:p}`:p}
|
||||
`}_renderLabels(t){return o`
|
||||
<ms-textfield
|
||||
class="labels-add"
|
||||
label=${s("bulk_labels_add",t)}
|
||||
.helper=${s("labels_help",t)}
|
||||
.value=${this._addText}
|
||||
@input=${e=>this._addText=e.target.value}
|
||||
></ms-textfield>
|
||||
${this._present.length?o`<div class="section-title">${s("bulk_labels_remove",t)}</div>
|
||||
<div class="pool">
|
||||
${this._present.map(e=>o`<label class="row">
|
||||
<input type="checkbox" .checked=${this._remove.has(e)} @change=${()=>this._remove=this._toggle(this._remove,e)} />
|
||||
${e}
|
||||
</label>`)}
|
||||
</div>`:p}
|
||||
`}_renderEdit(t){return o`
|
||||
<div class="hint">${s("bulk_edit_hint",t)}</div>
|
||||
<div class="row edit-row">
|
||||
<input type="checkbox" class="set-warning" .checked=${this._setWarning} @change=${e=>this._setWarning=e.target.checked} />
|
||||
<span class="grow">${s("warning_days",t)}</span>
|
||||
<input type="number" class="warning" min="0" max=${m} .value=${String(this._warning)} ?disabled=${!this._setWarning}
|
||||
@change=${e=>{let r=parseInt(e.target.value,10);this._warning=Number.isInteger(r)?Math.min(Math.max(r,0),m):this._warning}} />
|
||||
</div>
|
||||
<div class="row edit-row">
|
||||
<input type="checkbox" class="set-priority" .checked=${this._setPriority} @change=${e=>this._setPriority=e.target.checked} />
|
||||
<span class="grow">${s("priority",t)}</span>
|
||||
<select class="priority" .value=${this._priority} ?disabled=${!this._setPriority} @change=${e=>this._priority=e.target.value}>
|
||||
${v.map(e=>o`<option value=${e} ?selected=${this._priority===e}>${s(`priority_${e}`,t)}</option>`)}
|
||||
</select>
|
||||
</div>
|
||||
<div class="row edit-row">
|
||||
<input type="checkbox" class="set-mute" .checked=${this._setMute} @change=${e=>this._setMute=e.target.checked} />
|
||||
<span class="grow">${s("bulk_no_notifications",t)}</span>
|
||||
<input type="checkbox" class="mute" .checked=${this._mute} ?disabled=${!this._setMute} @change=${e=>this._mute=e.target.checked} />
|
||||
</div>
|
||||
`}render(){if(!this._open)return o``;let t=this._lang,e=this._mode==="assign"?s("bulk_assign",t):this._mode==="labels"?s("labels",t):s("edit",t),r=this.changes()!==null;return o`
|
||||
<ha-dialog open @closed=${()=>this._finish(null)}>
|
||||
<div class="dialog-title">${e}</div>
|
||||
<div class="content">
|
||||
<div class="count">${s("bulk_n_selected",t).replace("{n}",String(this._count))}</div>
|
||||
${this._mode==="assign"?this._renderAssign(t):this._mode==="labels"?this._renderLabels(t):this._renderEdit(t)}
|
||||
</div>
|
||||
<div class="dialog-actions">
|
||||
<ha-button appearance="plain" @click=${()=>this._finish(null)}>${s("cancel",t)}</ha-button>
|
||||
<ha-button class="apply" .disabled=${!r} @click=${()=>this._finish(this.changes())}>${s("save",t)}</ha-button>
|
||||
</div>
|
||||
</ha-dialog>
|
||||
`}};i.styles=_`
|
||||
.dialog-title { font-size: 18px; font-weight: 500; padding-bottom: 12px; }
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-width: min(360px, calc(100vw - 24px));
|
||||
max-width: 520px;
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.content { min-width: 0; max-width: none; max-height: none; }
|
||||
}
|
||||
.count, .hint { color: var(--secondary-text-color); font-size: 13px; }
|
||||
.section-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
padding-bottom: 4px;
|
||||
border-bottom: 1px solid var(--divider-color);
|
||||
}
|
||||
.choice, .row { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
|
||||
.pool { display: flex; flex-direction: column; gap: 4px; padding-left: 26px; }
|
||||
.field { display: flex; align-items: center; gap: 8px; justify-content: space-between; font-size: 14px; }
|
||||
.grow { flex: 1; min-width: 0; }
|
||||
select, input[type="number"] {
|
||||
font: inherit;
|
||||
padding: 4px 6px;
|
||||
border: 1px solid var(--divider-color);
|
||||
border-radius: 4px;
|
||||
background: var(--card-background-color, #fff);
|
||||
color: var(--primary-text-color);
|
||||
max-width: 100%;
|
||||
}
|
||||
input[type="number"] { width: 72px; }
|
||||
select.person { margin-left: 26px; }
|
||||
.dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 16px; }
|
||||
`,n([g({attribute:!1})],i.prototype,"hass",2),n([a()],i.prototype,"_open",2),n([a()],i.prototype,"_mode",2),n([a()],i.prototype,"_count",2),n([a()],i.prototype,"_users",2),n([a()],i.prototype,"_present",2),n([a()],i.prototype,"_assignKind",2),n([a()],i.prototype,"_person",2),n([a()],i.prototype,"_pool",2),n([a()],i.prototype,"_rotation",2),n([a()],i.prototype,"_addText",2),n([a()],i.prototype,"_remove",2),n([a()],i.prototype,"_setWarning",2),n([a()],i.prototype,"_warning",2),n([a()],i.prototype,"_setPriority",2),n([a()],i.prototype,"_priority",2),n([a()],i.prototype,"_setMute",2),n([a()],i.prototype,"_mute",2);customElements.get("maintenance-bulk-edit-dialog")||customElements.define("maintenance-bulk-edit-dialog",i);export{i as MaintenanceBulkEditDialog};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{s as a}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";var _=[{key:"name",labelKey:"name",required:!0},{key:"ref_no",labelKey:"ref_number"},{key:"manufacturer",labelKey:"manufacturer"},{key:"model",labelKey:"model"},{key:"serial_number",labelKey:"serial_number_label"},{key:"installation_date",labelKey:"installed"},{key:"warranty_expiry",labelKey:"warranty"},{key:"area_id",labelKey:"area"},{key:"documentation_url",labelKey:"documentation_url_label"},{key:"notes",labelKey:"object_notes_label"},{key:"task_count",labelKey:"tasks"},{key:"actions",labelKey:"actions"}],u=_.map(e=>e.key),i=["name","manufacturer","model","serial_number","installation_date","warranty_expiry","area_id","task_count","actions"];function g(e){if(!Array.isArray(e))return[...i];let n=new Set,r=[];for(let t of e)typeof t=="string"&&u.includes(t)&&!n.has(t)&&(n.add(t),r.push(t));return r.length?(r.includes("name")||r.unshift("name"),r):[...i]}function f(e,n){return a(`home_dwelling_${e==="house"||e==="apartment"?e:"unknown"}`,n)}function m(e,n){if(!e)return"";try{return new Intl.DisplayNames([n],{type:"region"}).of(e)||e}catch{return e}}var l={floors:"home_reason_floors",basement_floor:"home_reason_basement",area_basement:"home_reason_basement",area_garden:"home_reason_garden",area_shed:"home_reason_shed",area_driveway:"home_reason_driveway",area_garage:"home_reason_garage",entity_garage:"home_reason_garage",area_attic:"home_reason_attic",entity_lawn_mower:"home_reason_lawn_mower",entity_gate:"home_reason_gate",area_balcony:"home_reason_balcony",small_home:"home_reason_small_home"},c={ups:"home_reason_ups"};function d(e,n){let r=[];for(let t of e){let o=l[t];if(!o)continue;let s=a(o,n);r.includes(s)||r.push(s)}return r.join(", ")}function b(e,n,r){if(e==="starter")return a("home_reason_starter",n);if(e==="country")return a("home_reason_country",n).replace("{country}",m(r,n));if(e.startsWith("feature_")){let t=e.slice(8),o=l[`area_${t}`]??c[t];return a("home_reason_feature",n).replace("{feature}",o?a(o,n):e)}return a(`home_trait_${e}`,n)}export{_ as a,i as b,g as c,f as d,m as e,d as f,b as g};
|
||||
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
function c(n){return n==="use"?"use":"purchase"}var s=n=>typeof n=="number"&&Number.isFinite(n)?n:null;function a(n){let t=s(n?.cost);if(t===null)return null;let o=s(n?.package_size);return o&&o>0?t/o:t}function p(n,t){let o=s(t)&&t>0?t:s(n.restock_quantity)||1,e=s(n.package_size);return Math.round(o*(e&&e>0?e:1)*100)/100}function l(n){let t=s(n.cost);if(n.cost_basis!=="use")return t;let o=s(n.parts_cost),e=n.purchase?null:t;return e===null&&o===null?null:(e??0)+(o??0)}function _(n){if(!n)return[];let t=[],o=n.photo_doc_id;typeof o=="string"&&t.push(o);let e=n.photo_doc_ids;Array.isArray(e)&&t.push(...e);let r=[];for(let u of t){if(typeof u!="string")continue;let i=u.trim();if(!(!i||r.includes(i))&&(r.push(i),r.length>=10))break}return r}export{_ as a,c as b,a as c,p as d,l as e};
|
||||
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
function r(t){return String(t??"").replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n])}export{r as a};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{b as s}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-JQXHX4U4.js";async function a(o,n,t=300){return(await o.connection.sendMessagePromise({type:"auth/sign_path",path:n,expires:t})).path}async function r(o,n,t=300){return a(o,`/api/maintenance_supporter/document/${n}`,t)}async function p(o,n,t=""){let e=window.open("about:blank","_blank");try{let i=await r(o,n);e&&(e.location.href=new URL(i+t,window.location.origin).href)}catch(i){throw e&&e.close(),i}}async function l(o,n,t){s(await r(o,n,30),t)}function m(o,n=null){let t=URL.createObjectURL(new Blob([o],{type:"text/html"}));n&&!n.closed?n.location.href=t:window.open(t,"_blank"),setTimeout(()=>URL.revokeObjectURL(t),6e4)}function u(){return window.open("about:blank","_blank")}export{a,r as b,p as c,l as d,m as e,u as f};
|
||||
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{O as n,s as o}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-3FGYBPXY.js";var l={"Completed from dashboard button":"hist_note_button","Completed from the To-do list":"hist_note_todo","Completed by voice":"hist_note_voice","Completed from the notification":"hist_note_notification","Completed via NFC tag":"hist_note_nfc","Completed from the shopping list":"hist_note_shopping_list","Completed from a mirrored to-do list":"hist_note_todo_mirror","Skipped from notification":"hist_note_skipped_notification","Skipped from dashboard button":"hist_note_skipped_button","Sensor trigger activated":"hist_note_sensor_triggered","Initial value set during task creation":"hist_note_initial"},m=[[/^Auto-completed: sensor recovered \((.+)\)$/,"hist_note_auto_recovered",t=>({value:t[1]})],[/^Reset to (\d{4}-\d{2}-\d{2})$/,"hist_note_reset",(t,e)=>({date:n(t[1],e)})],[/^Trigger entity replaced: (.+) → (.+)$/,"hist_note_trigger_replaced",t=>({old:t[1],new:t[2]})],[/^Sensor trigger removed \(entity was: (.+)\)\. Schedule converted to (\w+)\.$/,"hist_note_trigger_removed",(t,e)=>({entity:t[1],schedule:o(t[2],e)})],[/^Entity (.+) removed from compound trigger; (\d+) conditions remain\.$/,"hist_note_compound_removed",t=>({entity:t[1],count:t[2]})]];function h(t,e){if(!t)return"";let i=l[t.trim()];if(i)return o(i,e);for(let[s,d,_]of m){let r=t.trim().match(s);if(r){let c=_(r,e);return o(d,e).replace(/\{(\w+)\}/g,(a,g)=>c[g]??a)}}return t}export{h as a};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
import{b as i}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-55ND3GKE.js";import{a as l}from"/maintenance_supporter_panelfiles/panel-chunks/chunk-RHKFQ4Q2.js";var a={operatorWriteEnabled:!1,operatorIds:[]};function m(e,t=a){return e?e.is_admin?!0:t.operatorWriteEnabled&&t.operatorIds.includes(e.id):!1}var _=["buttons_compact","buttons","icons"];function p(e){let[t,n]=l.default_warning_days,s=e?.general?.default_warning_days,r=e?.general?.row_action_style;return{features:{...o.features,...e?.features??{}},defaultWarningDays:typeof s=="number"&&Number.isFinite(s)&&s>=t&&s<=n?s:o.defaultWarningDays,rowActionStyle:_.includes(r??"")?r:o.rowActionStyle,access:{operatorWriteEnabled:e?.operator_write_enabled===!0,operatorIds:Array.isArray(e?.admin_panel_user_ids)?e.admin_panel_user_ids.filter(d=>typeof d=="string"):[]},budget:e?.budget??null,rowActionNoticePending:e?.general?.row_action_notice_pending===!0,refsInLists:e?.general?.ref_numbers_in_lists===!0,objectsTableColumns:Array.isArray(e?.objects_table_columns)?e.objects_table_columns:void 0,partsCostMode:i(e?.budget?.parts_cost_mode)}}var o={features:{adaptive:!1,seasonal:!1,environmental:!1,budget:!1,groups:!1,checklists:!1,schedule_time:!1,completion_actions:!1,places:!1},defaultWarningDays:7,rowActionStyle:"buttons_compact",access:a,budget:null,rowActionNoticePending:!1,refsInLists:!1,objectsTableColumns:void 0,partsCostMode:"purchase"};function c(){let e=window;return e.__msSettingsCache??={promise:null}}function S(e){let t=c();if(t.promise)return t.promise;let n=e.connection.sendMessagePromise({type:"maintenance_supporter/settings"}).then(s=>p(s)).catch(()=>(t.promise===n&&(t.promise=null),o));return t.promise=n,n}function y(){c().promise=null}var u=class{constructor(){this._handle=null}schedule(t,n=4e3){this.clear(),this._handle=setTimeout(()=>{this._handle=null,t()},n)}clear(){this._handle!==null&&(clearTimeout(this._handle),this._handle=null)}get pending(){return this._handle!==null}};export{a,m as b,_ as c,p as d,S as e,y as f,u as g};
|
||||
@@ -0,0 +1,2 @@
|
||||
/*! maintenance_supporter frontend 2.99.0 */
|
||||
var r={objectSections:"msp-object-sections",printOptions:"msp-print-options",batteryRosterOpen:"msp-bf-roster-open",docSort:"msp-doc-sort",cameraLabel:"msp-camera-label",overviewTab:"msp-overview-tab",collapsedSections:"msp-collapsed-sections",chartRange:"msp-chart-range",chartHideOutliers:"msp-chart-hide-outliers",taskSort:"maintenance_supporter_sort",objectSort:"maintenance_supporter_object_sort",groupBy:"maintenance_supporter_groupby",objectView:"maintenance_supporter_object_view",objectsCache:"msp-objects-cache",gettingStartedDismissed:"msp-gs-dismissed",batteryRosterSort:"ms_bf_roster_sort",areaSort:"msp-area-sort"};function s(t){try{return localStorage.getItem(t)}catch{return null}}function o(t,e){try{localStorage.setItem(t,e)}catch{}}export{r as a,s as b,o as c};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user