From bf886c9347fc45a7a650294bd6b5f8f6b69c5232 Mon Sep 17 00:00:00 2001 From: Home Assistant Version Control Date: Tue, 6 Oct 2026 17:11:43 +0000 Subject: [PATCH] 361 files --- .ha_run.lock | 2 +- .storage/lovelace_resources | 4 +- custom_components/album_slideshow/__init__.py | 10 + custom_components/album_slideshow/camera.py | 107 +- .../album_slideshow/config_flow.py | 547 ++- custom_components/album_slideshow/const.py | 14 + .../album_slideshow/coordinator.py | 361 +- .../album_slideshow/google_scraper.py | 150 +- .../album_slideshow/image_processing.py | 339 +- custom_components/album_slideshow/immich.py | 207 + .../album_slideshow/manifest.json | 4 +- custom_components/album_slideshow/number.py | 64 +- custom_components/album_slideshow/playlist.py | 46 +- custom_components/album_slideshow/sensor.py | 6 +- custom_components/album_slideshow/store.py | 7 + .../album_slideshow/strings.json | 40 +- custom_components/album_slideshow/switch.py | 46 +- .../album_slideshow/translations/en.json | 40 +- .../www/album-slideshow-card.js | 812 +++- .../maintenance_supporter/__init__.py | 23 + .../maintenance_supporter/calendar.py | 9 + .../config_flow_options_global.py | 5 + .../config_flow_options_task_trigger.py | 15 +- .../maintenance_supporter/const.py | 13 + .../maintenance_supporter/coordinator.py | 21 + .../entity/triggers/__init__.py | 22 + .../maintenance_supporter/export.py | 7 + .../frontend-src/__tests__/_test-utils.ts | 3 +- .../__tests__/task-detail-renderer.test.ts | 4 +- .../__tests__/task-detail-view.test.ts | 2 +- .../frontend-src/components/object-dialog.ts | 60 + .../frontend-src/components/settings-view.ts | 1 + .../frontend-src/components/task-dialog.ts | 7 +- .../components/task-quick-actions-dialog.ts | 2 +- .../frontend-src/dialog-mount.ts | 11 + .../frontend-src/locales/cs.json | 9 + .../frontend-src/locales/da.json | 9 + .../frontend-src/locales/de.json | 9 + .../frontend-src/locales/en.json | 9 + .../frontend-src/locales/es.json | 9 + .../frontend-src/locales/fi.json | 9 + .../frontend-src/locales/fr.json | 9 + .../frontend-src/locales/hi.json | 9 + .../frontend-src/locales/hu.json | 9 + .../frontend-src/locales/it.json | 9 + .../frontend-src/locales/ja.json | 9 + .../frontend-src/locales/ko.json | 9 + .../frontend-src/locales/nb.json | 9 + .../frontend-src/locales/nl.json | 9 + .../frontend-src/locales/pl.json | 9 + .../frontend-src/locales/pt-br.json | 9 + .../frontend-src/locales/pt.json | 9 + .../frontend-src/locales/ru.json | 9 + .../frontend-src/locales/sv.json | 9 + .../frontend-src/locales/tr.json | 9 + .../frontend-src/locales/uk.json | 9 + .../frontend-src/locales/zh.json | 9 + .../frontend-src/maintenance-panel.ts | 67 +- .../frontend-src/panel-styles.ts | 8 + .../frontend-src/renderers/progress.ts | 12 +- .../frontend-src/renderers/sparkline.ts | 13 +- .../frontend-src/types.ts | 9 + .../frontend/locales/cs.json | 9 + .../frontend/locales/da.json | 9 + .../frontend/locales/de.json | 9 + .../frontend/locales/en.json | 9 + .../frontend/locales/es.json | 9 + .../frontend/locales/fi.json | 9 + .../frontend/locales/fr.json | 9 + .../frontend/locales/hi.json | 9 + .../frontend/locales/hu.json | 9 + .../frontend/locales/it.json | 9 + .../frontend/locales/ja.json | 9 + .../frontend/locales/ko.json | 9 + .../frontend/locales/nb.json | 9 + .../frontend/locales/nl.json | 9 + .../frontend/locales/pl.json | 9 + .../frontend/locales/pt-br.json | 9 + .../frontend/locales/pt.json | 9 + .../frontend/locales/ru.json | 9 + .../frontend/locales/sv.json | 9 + .../frontend/locales/tr.json | 9 + .../frontend/locales/uk.json | 9 + .../frontend/locales/zh.json | 9 + .../frontend/maintenance-calendar-card.js | 285 +- .../frontend/maintenance-card.js | 337 +- .../frontend/maintenance-panel.js | 527 +-- .../frontend/maintenance-strategy-shim.js | 4 +- .../adopt-problem-sensors-dialog-YNUL6UYR.js | 301 ++ .../panel-chunks/area-view-XTWD5MTD.js | 279 ++ .../panel-chunks/areas-view-UDLGVZLY.js | 54 + .../panel-chunks/bulk-edit-dialog-A7JSPXFS.js | 113 + .../frontend/panel-chunks/chunk-3FGYBPXY.js | 1314 +++++++ .../frontend/panel-chunks/chunk-4APLU3YR.js | 2 + .../frontend/panel-chunks/chunk-55ND3GKE.js | 2 + .../frontend/panel-chunks/chunk-5MYBEQC2.js | 2 + .../frontend/panel-chunks/chunk-6BKNHM6I.js | 488 +++ .../frontend/panel-chunks/chunk-DRT62KZF.js | 2 + .../frontend/panel-chunks/chunk-EKN6HBJN.js | 2 + .../frontend/panel-chunks/chunk-GM2CHGSG.js | 2 + .../frontend/panel-chunks/chunk-GWAP5R2S.js | 2 + .../frontend/panel-chunks/chunk-HFZZVTW7.js | 2 + .../frontend/panel-chunks/chunk-JQXHX4U4.js | 2 + .../frontend/panel-chunks/chunk-MGSZZ3YF.js | 2 + .../frontend/panel-chunks/chunk-MNPRUCF5.js | 37 + .../frontend/panel-chunks/chunk-MQRW7LAF.js | 2 + .../frontend/panel-chunks/chunk-PCR5FRSH.js | 2 + .../frontend/panel-chunks/chunk-PL7JXZOW.js | 1490 +++++++ .../frontend/panel-chunks/chunk-RHKFQ4Q2.js | 2 + .../frontend/panel-chunks/chunk-RUYEMIDM.js | 88 + .../frontend/panel-chunks/chunk-SUOGXDNI.js | 234 ++ .../frontend/panel-chunks/chunk-SYPCMUXO.js | 2 + .../frontend/panel-chunks/chunk-TX2GMEMJ.js | 79 + .../frontend/panel-chunks/chunk-WACUKJSI.js | 2 + .../frontend/panel-chunks/chunk-XTTCEGMX.js | 1013 +++++ .../frontend/panel-chunks/chunk-ZHMFEWT2.js | 256 ++ .../panel-chunks/complete-dialog-HB2GK5Z3.js | 2 + .../panel-chunks/dialog-mount-ZEP3U4T7.js | 2 + .../panel-chunks/object-dialog-GZK3VG7E.js | 2 + .../panel-chunks/qr-dialog-2SMLHEDB.js | 2 + .../panel-chunks/settings-view-S7OONH2A.js | 1467 +++++++ .../suggested-setups-dialog-F54DZZLX.js | 184 + .../panel-chunks/task-dialog-4KQRUMA6.js | 2 + .../chunks/budget-section-card-GGFM4NWQ.js | 127 + .../strategy/chunks/chunk-47YHJMQQ.js | 66 + .../strategy/chunks/chunk-GVWULYYT.js | 2 + .../strategy/chunks/chunk-KWXSFMBP.js | 1314 +++++++ .../strategy/chunks/chunk-P2ZDMNV3.js | 2 + .../strategy/chunks/chunk-QZSR3CS5.js | 88 + .../strategy/chunks/chunk-SZ5OZQBM.js | 2 + .../strategy/chunks/chunk-ZT3EJK22.js | 60 + .../strategy/chunks/dialog-mount-COO4BKJS.js | 3502 +++++++++++++++++ .../chunks/groups-section-card-E26J7GJC.js | 137 + .../chunks/vacation-section-card-RQOCUOWP.js | 134 + .../maintenance-dashboard-strategy.js | 6 +- .../helpers/entity_rename.py | 8 +- .../helpers/notification_manager.py | 122 + .../helpers/problem_sensors.py | 6 +- .../maintenance_supporter/helpers/sanitize.py | 18 + .../helpers/settings_registry.py | 2 + .../helpers/trigger_fallback.py | 69 +- .../maintenance_supporter/manifest.json | 2 +- .../models/maintenance_object.py | 10 + .../maintenance_supporter/strings.json | 6 +- .../translations/cs.json | 6 +- .../translations/da.json | 6 +- .../translations/de.json | 6 +- .../translations/en.json | 6 +- .../translations/es.json | 6 +- .../translations/fi.json | 6 +- .../translations/fr.json | 6 +- .../translations/hi.json | 6 +- .../translations/hu.json | 6 +- .../translations/it.json | 6 +- .../translations/ja.json | 6 +- .../translations/ko.json | 6 +- .../translations/nb.json | 6 +- .../translations/nl.json | 6 +- .../translations/pl.json | 6 +- .../translations/pt-BR.json | 6 +- .../translations/pt.json | 6 +- .../translations/ru.json | 6 +- .../translations/sv.json | 6 +- .../translations/tr.json | 6 +- .../translations/uk.json | 6 +- .../translations/zh-Hans.json | 6 +- .../websocket/__init__.py | 22 +- .../websocket/dashboard.py | 2 + .../maintenance_supporter/websocket/io.py | 3 + .../websocket/objects.py | 17 + .../websocket/tasks_crud.py | 13 +- custom_components/spook/__init__.py | 33 +- .../ectoplasms/automation/repairs/__init__.py | 69 + .../repairs/unknown_area_references.py | 4 +- .../repairs/unknown_device_references.py | 4 +- .../repairs/unknown_entity_references.py | 39 +- .../repairs/unknown_floor_references.py | 4 +- .../repairs/unknown_label_references.py | 4 +- .../repairs/unknown_service_references.py | 8 +- .../group/repairs/unknown_members.py | 13 +- .../homeassistant/services/restart.py | 9 +- .../repairs/unknown_entity_references.py | 31 +- .../ectoplasms/number/services/__init__.py | 29 +- .../ectoplasms/number/services/decrement.py | 6 +- .../ectoplasms/number/services/increment.py | 6 +- .../repairs/unknown_ignored_zones.py | 2 +- .../repairs/unknown_tracked_entities.py | 2 +- .../repairs/unknown_entity_references.py | 7 +- .../ectoplasms/timer/services/set_duration.py | 4 + custom_components/spook/icons.json | 12 + .../spook_calibration/manifest.json | 14 + .../spook_calibration/translations/af.json | 1 + .../spook_calibration/translations/ar.json | 1 + .../spook_calibration/translations/be.json | 1 + .../spook_calibration/translations/bg.json | 1 + .../spook_calibration/translations/bn.json | 1 + .../spook_calibration/translations/bs.json | 1 + .../spook_calibration/translations/ca.json | 1 + .../spook_calibration/translations/cs.json | 1 + .../spook_calibration/translations/cy.json | 1 + .../spook_calibration/translations/da.json | 1 + .../spook_calibration/translations/de.json | 37 + .../spook_calibration/translations/el.json | 1 + .../spook_calibration/translations/en.json | 37 + .../spook_calibration/translations/en_GB.json | 1 + .../spook_calibration/translations/eo.json | 1 + .../spook_calibration/translations/es.json | 37 + .../translations/es_419.json | 1 + .../spook_calibration/translations/et.json | 1 + .../spook_calibration/translations/eu.json | 1 + .../spook_calibration/translations/fa.json | 1 + .../spook_calibration/translations/fi.json | 1 + .../spook_calibration/translations/fr.json | 37 + .../spook_calibration/translations/fy.json | 1 + .../spook_calibration/translations/ga.json | 1 + .../spook_calibration/translations/gl.json | 1 + .../spook_calibration/translations/gsw.json | 1 + .../spook_calibration/translations/he.json | 1 + .../spook_calibration/translations/hi.json | 1 + .../spook_calibration/translations/hr.json | 1 + .../spook_calibration/translations/hu.json | 1 + .../spook_calibration/translations/hy.json | 1 + .../spook_calibration/translations/id.json | 1 + .../spook_calibration/translations/is.json | 1 + .../spook_calibration/translations/it.json | 1 + .../spook_calibration/translations/ja.json | 1 + .../spook_calibration/translations/ka.json | 1 + .../spook_calibration/translations/ko.json | 1 + .../spook_calibration/translations/lb.json | 1 + .../spook_calibration/translations/lt.json | 1 + .../spook_calibration/translations/lv.json | 1 + .../spook_calibration/translations/mk.json | 1 + .../spook_calibration/translations/ml.json | 1 + .../spook_calibration/translations/mt.json | 1 + .../spook_calibration/translations/nb.json | 1 + .../spook_calibration/translations/nl.json | 37 + .../spook_calibration/translations/nn.json | 1 + .../spook_calibration/translations/pl.json | 1 + .../spook_calibration/translations/pt.json | 1 + .../spook_calibration/translations/pt_BR.json | 1 + .../spook_calibration/translations/ro.json | 1 + .../spook_calibration/translations/ru.json | 1 + .../spook_calibration/translations/sk.json | 1 + .../spook_calibration/translations/sl.json | 1 + .../spook_calibration/translations/sq.json | 1 + .../spook_calibration/translations/sr.json | 37 + .../translations/sr_Latn.json | 37 + .../spook_calibration/translations/sv.json | 1 + .../spook_calibration/translations/ta.json | 1 + .../spook_calibration/translations/te.json | 1 + .../spook_calibration/translations/th.json | 1 + .../spook_calibration/translations/tr.json | 1 + .../spook_calibration/translations/uk.json | 1 + .../spook_calibration/translations/ur.json | 1 + .../spook_calibration/translations/vi.json | 1 + .../translations/zh_Hans.json | 1 + .../translations/zh_Hant.json | 1 + .../integrations/spook_inverse/__init__.py | 100 +- .../spook_inverse/binary_sensor.py | 9 +- .../integrations/spook_inverse/config_flow.py | 72 +- .../spook/integrations/spook_inverse/const.py | 13 +- .../integrations/spook_inverse/entity.py | 46 +- .../integrations/spook_inverse/manifest.json | 2 +- .../integrations/spook_inverse/switch.py | 24 +- .../spook_inverse/translations/en.json | 42 +- .../spook_inverse/translations/sr.json | 44 +- .../spook_inverse/translations/sr_Latn.json | 44 +- .../spook_time_in_state/manifest.json | 14 + .../spook_time_in_state/translations/af.json | 1 + .../spook_time_in_state/translations/ar.json | 1 + .../spook_time_in_state/translations/be.json | 1 + .../spook_time_in_state/translations/bg.json | 1 + .../spook_time_in_state/translations/bn.json | 1 + .../spook_time_in_state/translations/bs.json | 1 + .../spook_time_in_state/translations/ca.json | 1 + .../spook_time_in_state/translations/cs.json | 1 + .../spook_time_in_state/translations/cy.json | 1 + .../spook_time_in_state/translations/da.json | 1 + .../spook_time_in_state/translations/de.json | 33 + .../spook_time_in_state/translations/el.json | 1 + .../spook_time_in_state/translations/en.json | 33 + .../translations/en_GB.json | 1 + .../spook_time_in_state/translations/eo.json | 1 + .../spook_time_in_state/translations/es.json | 33 + .../translations/es_419.json | 1 + .../spook_time_in_state/translations/et.json | 1 + .../spook_time_in_state/translations/eu.json | 1 + .../spook_time_in_state/translations/fa.json | 1 + .../spook_time_in_state/translations/fi.json | 1 + .../spook_time_in_state/translations/fr.json | 33 + .../spook_time_in_state/translations/fy.json | 1 + .../spook_time_in_state/translations/ga.json | 1 + .../spook_time_in_state/translations/gl.json | 1 + .../spook_time_in_state/translations/gsw.json | 1 + .../spook_time_in_state/translations/he.json | 1 + .../spook_time_in_state/translations/hi.json | 1 + .../spook_time_in_state/translations/hr.json | 1 + .../spook_time_in_state/translations/hu.json | 1 + .../spook_time_in_state/translations/hy.json | 1 + .../spook_time_in_state/translations/id.json | 1 + .../spook_time_in_state/translations/is.json | 1 + .../spook_time_in_state/translations/it.json | 1 + .../spook_time_in_state/translations/ja.json | 1 + .../spook_time_in_state/translations/ka.json | 1 + .../spook_time_in_state/translations/ko.json | 1 + .../spook_time_in_state/translations/lb.json | 1 + .../spook_time_in_state/translations/lt.json | 1 + .../spook_time_in_state/translations/lv.json | 1 + .../spook_time_in_state/translations/mk.json | 1 + .../spook_time_in_state/translations/ml.json | 1 + .../spook_time_in_state/translations/mt.json | 1 + .../spook_time_in_state/translations/nb.json | 1 + .../spook_time_in_state/translations/nl.json | 33 + .../spook_time_in_state/translations/nn.json | 1 + .../spook_time_in_state/translations/pl.json | 1 + .../spook_time_in_state/translations/pt.json | 1 + .../translations/pt_BR.json | 1 + .../spook_time_in_state/translations/ro.json | 1 + .../spook_time_in_state/translations/ru.json | 1 + .../spook_time_in_state/translations/sk.json | 1 + .../spook_time_in_state/translations/sl.json | 1 + .../spook_time_in_state/translations/sq.json | 1 + .../spook_time_in_state/translations/sr.json | 33 + .../translations/sr_Latn.json | 33 + .../spook_time_in_state/translations/sv.json | 1 + .../spook_time_in_state/translations/ta.json | 1 + .../spook_time_in_state/translations/te.json | 1 + .../spook_time_in_state/translations/th.json | 1 + .../spook_time_in_state/translations/tr.json | 1 + .../spook_time_in_state/translations/uk.json | 1 + .../spook_time_in_state/translations/ur.json | 1 + .../spook_time_in_state/translations/vi.json | 1 + .../translations/zh_Hans.json | 1 + .../translations/zh_Hant.json | 1 + custom_components/spook/manifest.json | 12 +- custom_components/spook/repairs.py | 299 +- custom_components/spook/services.py | 294 +- custom_components/spook/services.yaml | 378 ++ custom_components/spook/translations/de.json | 28 + .../spook/translations/en-GB.json | 28 + custom_components/spook/translations/en.json | 271 +- .../spook/translations/es-419.json | 28 + custom_components/spook/translations/es.json | 28 + custom_components/spook/translations/fi.json | 28 + custom_components/spook/translations/fr.json | 28 + custom_components/spook/translations/it.json | 28 + custom_components/spook/translations/nl.json | 619 ++- .../spook/translations/pt-BR.json | 28 + custom_components/spook/translations/pt.json | 28 + .../spook/translations/sr-Latn.json | 593 ++- custom_components/spook/translations/sr.json | 591 ++- custom_components/spook/translations/sv.json | 108 +- .../spook/translations/zh-Hans.json | 28 + .../spook/translations/zh-Hant.json | 28 + custom_components/spook/triggers.yaml | 4 + .../statistics-graph-chart-card.js | 2 +- .../statistics-graph-chart-card.js.gz | Bin 343878 -> 352310 bytes .../translations.js | 542 ++- .../translations.js.gz | Bin 637166 -> 683037 bytes .../multiple-entity-row.js | 2 +- .../multiple-entity-row.js.gz | Bin 27566 -> 27616 bytes zigbee2mqtt/state.json | 26 +- 362 files changed, 22060 insertions(+), 1285 deletions(-) create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/adopt-problem-sensors-dialog-YNUL6UYR.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/area-view-XTWD5MTD.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/areas-view-UDLGVZLY.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/bulk-edit-dialog-A7JSPXFS.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-3FGYBPXY.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-4APLU3YR.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-55ND3GKE.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-5MYBEQC2.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-6BKNHM6I.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-DRT62KZF.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-EKN6HBJN.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-GM2CHGSG.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-GWAP5R2S.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-HFZZVTW7.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-JQXHX4U4.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-MGSZZ3YF.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-MNPRUCF5.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-MQRW7LAF.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-PCR5FRSH.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-PL7JXZOW.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-RHKFQ4Q2.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-RUYEMIDM.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-SUOGXDNI.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-SYPCMUXO.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-TX2GMEMJ.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-WACUKJSI.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-XTTCEGMX.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/chunk-ZHMFEWT2.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/complete-dialog-HB2GK5Z3.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/dialog-mount-ZEP3U4T7.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/object-dialog-GZK3VG7E.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/qr-dialog-2SMLHEDB.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/settings-view-S7OONH2A.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/suggested-setups-dialog-F54DZZLX.js create mode 100644 custom_components/maintenance_supporter/frontend/panel-chunks/task-dialog-4KQRUMA6.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/budget-section-card-GGFM4NWQ.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-47YHJMQQ.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-GVWULYYT.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-KWXSFMBP.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-P2ZDMNV3.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-QZSR3CS5.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-SZ5OZQBM.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/chunk-ZT3EJK22.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/dialog-mount-COO4BKJS.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/groups-section-card-E26J7GJC.js create mode 100644 custom_components/maintenance_supporter/frontend/strategy/chunks/vacation-section-card-RQOCUOWP.js create mode 100644 custom_components/spook/integrations/spook_calibration/manifest.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/af.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ar.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/be.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/bg.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/bn.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/bs.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ca.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/cs.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/cy.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/da.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/de.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/el.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/en.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/en_GB.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/eo.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/es.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/es_419.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/et.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/eu.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/fa.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/fi.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/fr.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/fy.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ga.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/gl.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/gsw.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/he.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/hi.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/hr.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/hu.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/hy.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/id.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/is.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/it.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ja.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ka.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ko.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/lb.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/lt.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/lv.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/mk.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ml.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/mt.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/nb.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/nl.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/nn.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/pl.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/pt.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/pt_BR.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ro.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ru.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sk.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sl.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sq.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sr.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sr_Latn.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/sv.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ta.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/te.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/th.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/tr.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/uk.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/ur.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/vi.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/zh_Hans.json create mode 100644 custom_components/spook/integrations/spook_calibration/translations/zh_Hant.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/manifest.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/af.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ar.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/be.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/bg.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/bn.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/bs.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ca.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/cs.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/cy.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/da.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/de.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/el.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/en.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/en_GB.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/eo.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/es.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/es_419.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/et.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/eu.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/fa.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/fi.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/fr.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/fy.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ga.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/gl.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/gsw.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/he.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/hi.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/hr.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/hu.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/hy.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/id.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/is.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/it.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ja.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ka.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ko.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/lb.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/lt.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/lv.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/mk.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ml.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/mt.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/nb.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/nl.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/nn.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/pl.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/pt.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/pt_BR.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ro.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ru.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sk.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sl.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sq.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sr.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sr_Latn.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/sv.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ta.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/te.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/th.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/tr.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/uk.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/ur.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/vi.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/zh_Hans.json create mode 100644 custom_components/spook/integrations/spook_time_in_state/translations/zh_Hant.json diff --git a/.ha_run.lock b/.ha_run.lock index 1b983953..b47b8295 100644 --- a/.ha_run.lock +++ b/.ha_run.lock @@ -1 +1 @@ -{"pid": 71, "version": 1, "ha_version": "2026.9.4", "start_ts": 1791146884.4391842} \ No newline at end of file +{"pid": 70, "version": 1, "ha_version": "2026.9.4", "start_ts": 1791306689.7190704} \ No newline at end of file diff --git a/.storage/lovelace_resources b/.storage/lovelace_resources index 99b5160a..4e62130d 100644 --- a/.storage/lovelace_resources +++ b/.storage/lovelace_resources @@ -196,7 +196,7 @@ }, { "id": "e92ef0caff41454e9f49ea966ed99e41", - "url": "/hacsfiles/lovelace-multiple-entity-row/multiple-entity-row.js?hacstag=1789210374120", + "url": "/hacsfiles/lovelace-multiple-entity-row/multiple-entity-row.js?hacstag=1789210374130", "type": "module" }, { @@ -256,7 +256,7 @@ }, { "id": "8713ea9c008e4270bb28085eed5be959", - "url": "/hacsfiles/Statistics-Graph-Chart-Card/statistics-graph-chart-card.js?hacstag=1034932856404", + "url": "/hacsfiles/Statistics-Graph-Chart-Card/statistics-graph-chart-card.js?hacstag=1034932856405", "type": "module" }, { diff --git a/custom_components/album_slideshow/__init__.py b/custom_components/album_slideshow/__init__.py index f68e4310..30b6bb3b 100644 --- a/custom_components/album_slideshow/__init__.py +++ b/custom_components/album_slideshow/__init__.py @@ -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. diff --git a/custom_components/album_slideshow/camera.py b/custom_components/album_slideshow/camera.py index 6f82e7da..c1bb6f36 100644 --- a/custom_components/album_slideshow/camera.py +++ b/custom_components/album_slideshow/camera.py @@ -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] diff --git a/custom_components/album_slideshow/config_flow.py b/custom_components/album_slideshow/config_flow.py index b7690c69..636a3ba8 100644 --- a/custom_components/album_slideshow/config_flow.py +++ b/custom_components/album_slideshow/config_flow.py @@ -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.""" diff --git a/custom_components/album_slideshow/const.py b/custom_components/album_slideshow/const.py index df331c01..2cf3b306 100644 --- a/custom_components/album_slideshow/const.py +++ b/custom_components/album_slideshow/const.py @@ -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" diff --git a/custom_components/album_slideshow/coordinator.py b/custom_components/album_slideshow/coordinator.py index fd33e07f..edddff6e 100644 --- a/custom_components/album_slideshow/coordinator.py +++ b/custom_components/album_slideshow/coordinator.py @@ -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 diff --git a/custom_components/album_slideshow/google_scraper.py b/custom_components/album_slideshow/google_scraper.py index e635cf24..6e692b43 100644 --- a/custom_components/album_slideshow/google_scraper.py +++ b/custom_components/album_slideshow/google_scraper.py @@ -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) ------ diff --git a/custom_components/album_slideshow/image_processing.py b/custom_components/album_slideshow/image_processing.py index 81be9bdc..097c4621 100644 --- a/custom_components/album_slideshow/image_processing.py +++ b/custom_components/album_slideshow/image_processing.py @@ -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 - diff --git a/custom_components/album_slideshow/immich.py b/custom_components/album_slideshow/immich.py index 64ab3b0d..fe0072d2 100644 --- a/custom_components/album_slideshow/immich.py +++ b/custom_components/album_slideshow/immich.py @@ -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"] diff --git a/custom_components/album_slideshow/manifest.json b/custom_components/album_slideshow/manifest.json index 91303dca..b6f78d50 100644 --- a/custom_components/album_slideshow/manifest.json +++ b/custom_components/album_slideshow/manifest.json @@ -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" } diff --git a/custom_components/album_slideshow/number.py b/custom_components/album_slideshow/number.py index cdd245ef..14526732 100644 --- a/custom_components/album_slideshow/number.py +++ b/custom_components/album_slideshow/number.py @@ -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 diff --git a/custom_components/album_slideshow/playlist.py b/custom_components/album_slideshow/playlist.py index 1eca176f..ba3d8866 100644 --- a/custom_components/album_slideshow/playlist.py +++ b/custom_components/album_slideshow/playlist.py @@ -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 diff --git a/custom_components/album_slideshow/sensor.py b/custom_components/album_slideshow/sensor.py index 7ff8d847..97fc217b 100644 --- a/custom_components/album_slideshow/sensor.py +++ b/custom_components/album_slideshow/sensor.py @@ -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. diff --git a/custom_components/album_slideshow/store.py b/custom_components/album_slideshow/store.py index 9180c8d4..682428dc 100644 --- a/custom_components/album_slideshow/store.py +++ b/custom_components/album_slideshow/store.py @@ -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 diff --git a/custom_components/album_slideshow/strings.json b/custom_components/album_slideshow/strings.json index 4f7b1f61..1a2ff808 100644 --- a/custom_components/album_slideshow/strings.json +++ b/custom_components/album_slideshow/strings.json @@ -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." } } } diff --git a/custom_components/album_slideshow/switch.py b/custom_components/album_slideshow/switch.py index c801c5df..072c9058 100644 --- a/custom_components/album_slideshow/switch.py +++ b/custom_components/album_slideshow/switch.py @@ -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() diff --git a/custom_components/album_slideshow/translations/en.json b/custom_components/album_slideshow/translations/en.json index 4f7b1f61..1a2ff808 100644 --- a/custom_components/album_slideshow/translations/en.json +++ b/custom_components/album_slideshow/translations/en.json @@ -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." } } } diff --git a/custom_components/album_slideshow/www/album-slideshow-card.js b/custom_components/album_slideshow/www/album-slideshow-card.js index c698c9b7..11b2d74a 100644 --- a/custom_components/album_slideshow/www/album-slideshow-card.js +++ b/custom_components/album_slideshow/www/album-slideshow-card.js @@ -26,7 +26,7 @@ * tap_action: none # none | more-info */ -const VERSION = "1.11.0"; +const VERSION = "1.13.0"; const ANIMATED_TRANSITIONS = [ "fade", @@ -62,7 +62,12 @@ function normalizePhotoControls(value) { // Caption overlay (date / location / description). ``show`` is an ordered // subset of these fields; ``position`` is one of a 3x3 anchor grid; // ``date_format`` is one of the named presets below or a custom token string. -const CAPTION_FIELDS = ["date", "location", "description"]; +const CAMERA_CAPTION_FIELDS = [ + "camera_make", "camera_model", "focal_length_mm", "aperture_f_number", + "iso", "exposure_time_seconds", +]; +const CAPTION_FIELDS = ["date", "location", "description", "camera", ...CAMERA_CAPTION_FIELDS, "current_date", "current_time", "weather"]; +const LIVE_CAPTION_FIELDS = new Set(["current_date", "current_time", "weather"]); const CAPTION_POSITIONS = new Set([ "top-left", "top-center", @@ -604,6 +609,11 @@ function createAlbumSlideshowCardClass(Base) { if (!FIT_MODES.has(fit)) { throw new Error(`album-slideshow-card: unknown fit '${fit}'`); } + if (config.captions != null && !Array.isArray(config.captions)) { + throw new Error("album-slideshow-card: 'captions' must be a list"); + } + const captions = (config.captions ?? [config.caption]) + .map((caption) => this._normalizeCaption(caption)).filter(Boolean); this._config = { ...config, transition, @@ -622,8 +632,8 @@ function createAlbumSlideshowCardClass(Base) { config.tap_pause_seconds === 0 ? 0 : Number(config.tap_pause_seconds ?? 8), - // Caption overlay (date / location). ``null`` when disabled. - caption: this._normalizeCaption(config.caption), + caption: captions[0] || null, + captions, }; if (this._rendered) { // Config edited live; rebuild styles + reset state. @@ -643,6 +653,7 @@ function createAlbumSlideshowCardClass(Base) { if (raw == null || raw === false) return null; if (raw === true) raw = {}; if (typeof raw !== "object") return null; + if (raw.enabled === false) return null; let show = raw.show; if (typeof show === "string") show = show.split(/[,\s]+/); if (!Array.isArray(show)) show = ["date", "location"]; @@ -668,6 +679,11 @@ function createAlbumSlideshowCardClass(Base) { position, per_image: raw.per_image !== false, date_format: raw.date_format != null ? String(raw.date_format) : "medium", + current_date_format: String(raw.current_date_format ?? raw.date_format ?? "medium"), + time_format: ["auto", "12h", "24h"].includes(raw.time_format) ? raw.time_format : "auto", + time_seconds: raw.time_seconds === true, + weather_entity: typeof raw.weather_entity === "string" && /^(weather|sensor)\.[a-z0-9_]+$/.test(raw.weather_entity.trim()) + ? raw.weather_entity.trim() : null, color, font_size: fontSize, font_weight: fontWeight, @@ -686,10 +702,15 @@ function createAlbumSlideshowCardClass(Base) { } else { this._setupPhotoControlsReveal(); } + this._captionResizeObserver ??= new ResizeObserver(() => this._fitCaptions()); + this._captionResizeObserver.observe(this); this._maybeSwap(); } disconnectedCallback() { + this._captionResizeObserver?.disconnect(); + clearTimeout(this._captionClockTimer); + this._captionClockTimer = null; this._cancelControlNavigation(); this._controlsReveal?.dispose(); this._controlsReveal = null; @@ -701,9 +722,14 @@ function createAlbumSlideshowCardClass(Base) { } set hass(hass) { + const previous = this._hass; this._hass = hass; if (!this._rendered) return; this._maybeSwap(); + if (this._captionData && this._captionConfigs().some((cap) => cap.show.includes("weather") && cap.weather_entity && + (previous?.states?.[cap.weather_entity] !== hass.states?.[cap.weather_entity] || previous?.locale !== hass.locale))) { + this._renderCaptions(this._captionData, false); + } } _resolvedFit(attrs) { @@ -722,6 +748,9 @@ function createAlbumSlideshowCardClass(Base) { _renderShell() { const c = this._config; + clearTimeout(this._captionClockTimer); + this._captionClockTimer = null; + this._captionData = null; this._cancelControlNavigation(); this._controlsReveal?.dispose(); this._controlsReveal = null; @@ -813,15 +842,26 @@ function createAlbumSlideshowCardClass(Base) { display: flex; padding: 3.5% 4%; box-sizing: border-box; + min-width: 0; + overflow: hidden; } .cap-box { display: flex; flex-direction: column; - max-width: 92%; + flex-shrink: 0; + max-width: 100%; + max-height: 100%; + min-width: 0; + overflow: hidden; + overflow-wrap: anywhere; line-height: 1.25; font-family: var(--paper-font-body1_-_font-family, sans-serif); } - .cap-line { font-weight: inherit; } + .cap-stack { + display: flex; flex-direction: column; gap: 4px; + max-width: 100%; max-height: 100%; min-width: 0; overflow: hidden; + } + .cap-line { font-weight: inherit; flex-shrink: 0; font-variant-numeric: tabular-nums; } #photo-controls { position: absolute; right: 8px; max-width: calc(100% - 16px); ${c.caption?.position.startsWith("top") ? "bottom" : "top"}: 8px; z-index: 3; } .cap-box.cap-shadow { text-shadow: @@ -1033,6 +1073,7 @@ function createAlbumSlideshowCardClass(Base) { latitude: attrs.latitude, longitude: attrs.longitude, description: attrs.description, + ...Object.fromEntries(CAMERA_CAPTION_FIELDS.map((field) => [field, attrs[field]])), } : null; const photoData = { @@ -1047,6 +1088,9 @@ function createAlbumSlideshowCardClass(Base) { } _clearDisplayedPhotos() { + clearTimeout(this._captionClockTimer); + this._captionClockTimer = null; + this._captionData = null; this._loadGeneration += 1; this._displayedPhotoIds = []; this._displayedFrameId = null; @@ -1195,26 +1239,31 @@ function createAlbumSlideshowCardClass(Base) { } _renderCaptions(captionData, fade) { - const cap = this._config.caption; + clearTimeout(this._captionClockTimer); + this._captionClockTimer = null; + this._captionData = captionData; + const captions = this._captionConfigs(); const container = this.shadowRoot && this.shadowRoot.getElementById("captions"); if (!container) return; container.innerHTML = ""; - if (!cap || !captionData) return; + if (!captions.length || !captionData) return; const frames = this._buildCaptionFrames(captionData); const orientation = captionData.pair_orientation; - const isPair = - cap.per_image && - frames.length >= 2 && - (orientation === "horizontal" || orientation === "vertical"); - - if (isPair) { - this._addCaptionRegion(container, frames[0], cap, orientation, 0); - this._addCaptionRegion(container, frames[1], cap, orientation, 1); - } else { - this._addCaptionRegion(container, frames[0], cap, null, 0); + for (const cap of captions) { + const isPair = cap.per_image && cap.show.some((field) => !LIVE_CAPTION_FIELDS.has(field)) && frames.length >= 2 && + (orientation === "horizontal" || orientation === "vertical"); + if (isPair) { + this._addCaptionRegion(container, frames[0], cap, orientation, 0); + this._addCaptionRegion(container, frames[1], cap, orientation, 1); + } else { + this._addCaptionRegion(container, frames[0], cap, null, 0); + } } + this._layoutCaptionRegions(container); + this._fitCaptions(); + this._scheduleCaptionClock(); // Fade the new caption in alongside the image cross-fade. On the very // first frame (fade=false) just show it immediately. @@ -1231,6 +1280,79 @@ function createAlbumSlideshowCardClass(Base) { } } + _captionConfigs() { + return this._config?.captions ?? (this._config?.caption ? [this._config.caption] : []); + } + + _scheduleCaptionClock() { + clearTimeout(this._captionClockTimer); + this._captionClockTimer = null; + const clocks = this._captionConfigs().filter((cap) => + cap.show.some((field) => field === "current_date" || field === "current_time")); + if (!this.isConnected || !this._captionData || !clocks.length) return; + const interval = clocks.some((cap) => cap.show.includes("current_time") && cap.time_seconds) ? 1000 : 60000; + this._captionClockTimer = setTimeout(() => { + this._captionClockTimer = null; + if (this.isConnected && this._captionData) this._renderCaptions(this._captionData, false); + }, interval - (Date.now() % interval) + 20); + } + + _fitCaptions() { + if (!this._captionConfigs().length || !this.shadowRoot) return; + for (const stack of this.shadowRoot.querySelectorAll(".cap-stack")) { + const boxes = [...stack.querySelectorAll(".cap-box")]; + for (const box of boxes) box.style.fontSize = box._captionFontSize; + if (!stack.clientWidth || !stack.clientHeight) continue; + const sizes = boxes.map((box) => Number.parseFloat(getComputedStyle(box).fontSize)); + for (let attempt = 0; attempt < 3; attempt += 1) { + const scale = Math.min(stack.clientWidth / stack.scrollWidth, stack.clientHeight / stack.scrollHeight); + if (scale >= 1) break; + boxes.forEach((box, index) => { + sizes[index] = Math.max(1, sizes[index] * scale * 0.98); + box.style.fontSize = `${sizes[index]}px`; + }); + } + } + } + + _layoutCaptionRegions(container) { + const placements = [...container.children].map((region) => { + const width = region._captionOrientation === "horizontal" ? 0.5 : 1; + const height = region._captionOrientation === "vertical" ? 0.5 : 1; + const left = width === 0.5 ? region._captionHalf * width : 0; + const top = height === 0.5 ? region._captionHalf * height : 0; + return { region, left, right: left + width, top, bottom: top + height, + anchorX: left + region._captionColumn * width / 2, + anchorY: top + region._captionRow * height / 2 }; + }); + const space = (start, end, anchor, neighbors, centered) => { + let lower = start; + let upper = end; + for (const other of neighbors) { + if (other < anchor) lower = Math.max(lower, (other + anchor) / 2); + if (other > anchor) upper = Math.min(upper, (other + anchor) / 2); + } + if (centered) { + const radius = Math.min(anchor - lower, upper - anchor); + return [anchor - radius, anchor + radius]; + } + return [lower, upper]; + }; + for (const current of placements) { + const neighbors = placements.filter((other) => other.left < current.right && other.right > current.left && + other.top < current.bottom && other.bottom > current.top); + const [left, right] = space(current.left, current.right, current.anchorX, + neighbors.filter((other) => other.anchorY === current.anchorY).map((other) => other.anchorX), + current.region._captionColumn === 1); + const [top, bottom] = space(current.top, current.bottom, current.anchorY, + neighbors.map((other) => other.anchorY), current.region._captionRow === 1); + current.region.style.left = `${100 * left}%`; + current.region.style.right = `${100 * (1 - right)}%`; + current.region.style.top = `${100 * top}%`; + current.region.style.bottom = `${100 * (1 - bottom)}%`; + } + } + /** Per-image caption metadata. Prefers the integration's structured * ``caption_frames`` (one entry per image, two for a pair); falls back to * the flat attributes for older integration versions. */ @@ -1250,25 +1372,69 @@ function createAlbumSlideshowCardClass(Base) { latitude: data.latitude ?? null, longitude: data.longitude ?? null, description: data.description ?? null, + ...Object.fromEntries(CAMERA_CAPTION_FIELDS.map((field) => [field, data[field] ?? null])), }, ]; } - _captionLines(frame, cap) { + _captionLines(frame, cap, now = new Date()) { const lines = []; for (const field of cap.show) { if (field === "date") { const txt = this._formatDate(frame.captured_at, cap.date_format); if (txt) lines.push(txt); + } else if (field === "current_date") { + lines.push(this._formatDate(now.toISOString(), cap.current_date_format ?? cap.date_format, this._hass?.config?.time_zone)); + } else if (field === "current_time") { + lines.push(this._formatCurrentTime(now, cap)); + } else if (field === "weather") { + const weather = this._weatherCaption(cap); + if (weather) lines.push(weather); } else if (field === "location") { if (frame.location) lines.push(String(frame.location)); } else if (field === "description") { if (frame.description) lines.push(String(frame.description)); + } else if (field === "camera") { + const make = typeof frame.camera_make === "string" ? frame.camera_make.trim() : ""; + const model = typeof frame.camera_model === "string" ? frame.camera_model.trim() : ""; + const camera = make && model.toLowerCase().startsWith(make.toLowerCase()) + ? model : [make, model].filter(Boolean).join(" "); + if (camera) lines.push(camera); + } else if (field === "camera_make" || field === "camera_model") { + if (typeof frame[field] === "string" && frame[field].trim()) lines.push(frame[field].trim()); + } else if (CAMERA_CAPTION_FIELDS.includes(field)) { + const value = frame[field]; + if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) continue; + const formatted = new Intl.NumberFormat(this._locale(), { maximumFractionDigits: 3 }).format(value); + if (field === "focal_length_mm") lines.push(`${formatted} mm`); + else if (field === "aperture_f_number") lines.push(`f/${formatted}`); + else if (field === "iso") lines.push(`ISO ${Math.round(value)}`); + else if (field === "exposure_time_seconds") { + lines.push(value <= 0.5 ? `1/${Math.round(1 / value)} s` : `${formatted} s`); + } } } return lines; } + _weatherCaption(cap) { + if (typeof cap.weather_entity !== "string" || !/^(weather|sensor)\.[a-z0-9_]+$/.test(cap.weather_entity)) return ""; + const entity = this._hass?.states?.[cap.weather_entity]; + if (!entity || !entity.state || ["unknown", "unavailable"].includes(entity.state)) return ""; + const attributes = entity.attributes || {}; + const isWeather = cap.weather_entity.startsWith("weather."); + const state = this._hass.formatEntityState + ? this._hass.formatEntityState(entity) + : isWeather ? humanizeOption(entity.state.replace("partlycloudy", "partly cloudy")) + : [entity.state, attributes.unit_of_measurement].filter(Boolean).join(" "); + if (!isWeather || typeof attributes.temperature !== "number" || !Number.isFinite(attributes.temperature)) return state; + const temperature = this._hass.formatEntityAttributeValue + ? this._hass.formatEntityAttributeValue(entity, "temperature") + : [new Intl.NumberFormat(this._locale(), { maximumFractionDigits: 1 }).format(attributes.temperature), + attributes.temperature_unit || this._hass.config?.unit_system?.temperature].filter(Boolean).join(" "); + return `${state}, ${temperature}`; + } + /** Build one positioned caption block. ``orientation`` is ``null`` for a * full-frame caption, or ``horizontal`` / ``vertical`` to anchor the block * inside the left/right or top/bottom half of a pair (``half`` 0 or 1). */ @@ -1276,26 +1442,6 @@ function createAlbumSlideshowCardClass(Base) { const lines = this._captionLines(frame, cap); if (lines.length === 0) return; - const region = document.createElement("div"); - region.className = "cap-region"; - - // Region geometry: full frame, or one half of a pair. - let top = "0"; - let right = "0"; - let bottom = "0"; - let left = "0"; - if (orientation === "horizontal") { - if (half === 0) right = "50%"; - else left = "50%"; - } else if (orientation === "vertical") { - if (half === 0) bottom = "50%"; - else top = "50%"; - } - region.style.top = top; - region.style.right = right; - region.style.bottom = bottom; - region.style.left = left; - // Anchor within the region from the 3x3 position grid. const pos = cap.position; const parts = pos === "center" ? ["center", "center"] : pos.split("-"); @@ -1303,14 +1449,48 @@ function createAlbumSlideshowCardClass(Base) { const h = parts[1] || "center"; const justify = { left: "flex-start", center: "center", right: "flex-end" }; const align = { top: "flex-start", center: "center", bottom: "flex-end" }; - region.style.justifyContent = justify[h] || "flex-start"; - region.style.alignItems = align[v] || "flex-end"; + const row = { top: 0, center: 1, bottom: 2 }[v]; + const column = { left: 0, center: 1, right: 2 }[h]; + const anchorX = orientation === "horizontal" ? half / 2 + column / 4 : column / 2; + const anchorY = orientation === "vertical" ? half / 2 + row / 4 : row / 2; + let region = [...container.children].find((element) => element._captionAnchorX === anchorX && + element._captionAnchorY === anchorY && (!orientation || !element._captionOrientation || + (element._captionOrientation === orientation && element._captionHalf === half))); + if (!region) { + region = document.createElement("div"); + region.className = "cap-region"; + region._captionPosition = pos; + region._captionOrientation = orientation; + region._captionHalf = half; + region._captionRow = row; + region._captionColumn = column; + region._captionAnchorX = anchorX; + region._captionAnchorY = anchorY; + region.style.justifyContent = justify[h] || "flex-start"; + region.style.alignItems = align[v] || "flex-end"; + const stack = document.createElement("div"); + stack.className = "cap-stack"; + stack.style.alignItems = justify[h] || "flex-start"; + region._captionStack = stack; + region.appendChild(stack); + container.appendChild(region); + } + if (!region._captionOrientation && orientation) { + region._captionOrientation = orientation; + region._captionHalf = half; + region._captionRow = row; + region._captionColumn = column; + region.style.justifyContent = justify[h]; + region.style.alignItems = align[v]; + region._captionStack.style.alignItems = justify[h]; + } const box = document.createElement("div"); box.className = "cap-box"; if (cap.shadow) box.classList.add("cap-shadow"); box.style.color = cap.color; box.style.fontSize = cap.font_size; + box._captionFontSize = cap.font_size; box.style.fontWeight = CAPTION_WEIGHT_MAP[cap.font_weight] || 500; box.style.textAlign = h === "center" ? "center" : h; @@ -1320,8 +1500,7 @@ function createAlbumSlideshowCardClass(Base) { el.textContent = line; box.appendChild(el); } - region.appendChild(box); - container.appendChild(region); + region._captionStack.appendChild(box); } _locale() { @@ -1332,7 +1511,23 @@ function createAlbumSlideshowCardClass(Base) { ); } - _formatDate(iso, fmt) { + _formatCurrentTime(now, cap) { + const format = cap.time_format === "auto" || !cap.time_format + ? this._hass?.locale?.time_format : cap.time_format; + const options = { hour: "numeric", minute: "2-digit", timeZone: this._hass?.config?.time_zone }; + if (["12h", "am_pm"].includes(format)) options.hourCycle = "h12"; + if (["24h", "24"].includes(format)) { options.hourCycle = "h23"; options.hour = "2-digit"; } + if (cap.time_seconds) options.second = "2-digit"; + const locale = format === "system" && typeof navigator !== "undefined" ? navigator.language : this._locale(); + try { + return new Intl.DateTimeFormat(locale, options).format(now); + } catch (_) { + delete options.timeZone; + return new Intl.DateTimeFormat(undefined, options).format(now); + } + } + + _formatDate(iso, fmt, timeZone) { if (!iso) return ""; const d = new Date(iso); if (isNaN(d.getTime())) return ""; @@ -1341,13 +1536,13 @@ function createAlbumSlideshowCardClass(Base) { const preset = DATE_FORMAT_PRESETS[fmt]; if (preset) { try { - return new Intl.DateTimeFormat(locale, preset).format(d); + return new Intl.DateTimeFormat(locale, { ...preset, timeZone }).format(d); } catch (_) { return d.toLocaleDateString(); } } // Anything else is treated as a custom token string. - return this._formatTokens(d, String(fmt)); + return this._formatTokens(d, String(fmt), timeZone); } _relativeTime(d) { @@ -1391,29 +1586,40 @@ function createAlbumSlideshowCardClass(Base) { } } - _formatTokens(d, fmt) { + _formatTokens(d, fmt, timeZone) { const locale = this._locale(); const pad = (n) => String(n).padStart(2, "0"); const part = (opts) => { try { - return new Intl.DateTimeFormat(locale, opts).format(d); + return new Intl.DateTimeFormat(locale, { ...opts, timeZone }).format(d); } catch (_) { return ""; } }; + let calendar = { year: d.getFullYear(), month: d.getMonth() + 1, day: d.getDate(), hour: d.getHours(), minute: d.getMinutes() }; + if (timeZone) { + try { + const parts = new Intl.DateTimeFormat("en-US-u-nu-latn", { + year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", + hourCycle: "h23", timeZone, + }).formatToParts(d); + calendar = Object.fromEntries(parts.filter((value) => value.type !== "literal") + .map((value) => [value.type, Number(value.value)])); + } catch (_) {} + } const map = { - YYYY: d.getFullYear(), - YY: pad(d.getFullYear() % 100), + YYYY: calendar.year, + YY: pad(calendar.year % 100), MMMM: part({ month: "long" }), MMM: part({ month: "short" }), - MM: pad(d.getMonth() + 1), - M: d.getMonth() + 1, - DD: pad(d.getDate()), - D: d.getDate(), + MM: pad(calendar.month), + M: calendar.month, + DD: pad(calendar.day), + D: calendar.day, dddd: part({ weekday: "long" }), ddd: part({ weekday: "short" }), - HH: pad(d.getHours()), - mm: pad(d.getMinutes()), + HH: pad(calendar.hour), + mm: pad(calendar.minute), // Lets relative time be mixed into a format string, e.g. "DD MMMM YYYY - REL". REL: this._relativeTime(d), }; @@ -1498,9 +1704,19 @@ const TAP_OPTIONS = [ ]; const CAPTION_SHOW_OPTIONS = [ - { value: "date", label: "Date" }, + { value: "date", label: "Photo date" }, { value: "location", label: "Location" }, { value: "description", label: "Description" }, + { value: "camera", label: "Camera (make and model)" }, + { value: "camera_make", label: "Camera make" }, + { value: "camera_model", label: "Camera model" }, + { value: "focal_length_mm", label: "Focal length" }, + { value: "aperture_f_number", label: "Aperture" }, + { value: "iso", label: "ISO" }, + { value: "exposure_time_seconds", label: "Exposure time" }, + { value: "current_date", label: "Today's date" }, + { value: "current_time", label: "Current time" }, + { value: "weather", label: "Weather" }, ]; const CAPTION_POSITION_OPTIONS = [ @@ -1554,6 +1770,8 @@ const CAPTION_DEFAULTS = { position: "bottom-left", per_image: true, date_format: "medium", + time_format: "auto", + time_seconds: false, color: "#ffffff", font_size: "14px", font_weight: "medium", @@ -1568,6 +1786,8 @@ const CAPTION_DEFAULTS = { const LIVE_FIELDS = [ "paused", "date_filter", + "custom_lookback_days", + "shuffle_age_bias", "missing_date_mode", "portrait_mode", "order_mode", @@ -1580,6 +1800,8 @@ const LIVE_FIELDS = [ const LIVE_SUFFIX = { paused: "_paused", date_filter: "_date_filter", + custom_lookback_days: "_custom_lookback_days", + shuffle_age_bias: "_shuffle_age_bias", missing_date_mode: "_missing_date_mode", portrait_mode: "_portrait_mode", order_mode: "_order_mode", @@ -1595,6 +1817,8 @@ const LIVE_SUFFIX = { const LIVE_LABELS = { live_paused: "Pause slideshow", live_date_filter: "Date filter", + live_custom_lookback_days: "Custom lookback (days)", + live_shuffle_age_bias: "Shuffle age bias (older - / newer +)", live_missing_date_mode: "Missing capture date", live_portrait_mode: "Orientation mismatch mode", live_order_mode: "Order mode", @@ -1741,7 +1965,7 @@ function createAlbumSlideshowCardEditorClass(Base) { min: a.min != null ? a.min : fallback.min, max: a.max != null ? a.max : fallback.max, step: a.step != null ? a.step : fallback.step, - mode: "box", + mode: fallback.mode || "box", unit_of_measurement: fallback.unit, }; } @@ -1769,6 +1993,22 @@ function createAlbumSlideshowCardEditorClass(Base) { }); } } + if (s.custom_lookback_days && this._hass?.states[s.date_filter]?.state === "custom_days") { + items.push({ + name: "live_custom_lookback_days", + selector: { number: this._liveNumberConfig(s.custom_lookback_days, { + min: 1, max: 36500, step: 1, unit: "d", + }) }, + }); + } + if (s.shuffle_age_bias && this._hass?.states[s.order_mode]?.state === "random") { + items.push({ + name: "live_shuffle_age_bias", + selector: { number: this._liveNumberConfig(s.shuffle_age_bias, { + min: -100, max: 100, step: 1, mode: "slider", + }) }, + }); + } if (s.slide_interval) { items.push({ name: "live_slide_interval", @@ -1905,56 +2145,6 @@ function createAlbumSlideshowCardEditorClass(Base) { }, ], }, - { - type: "expandable", - title: "Caption (date, location & description)", - icon: "mdi:format-text", - schema: [ - { name: "caption_enabled", selector: { boolean: {} } }, - { - name: "caption_show", - selector: { - select: { - multiple: true, - mode: "list", - options: CAPTION_SHOW_OPTIONS, - }, - }, - }, - { - name: "caption_position", - selector: { - select: { mode: "dropdown", options: CAPTION_POSITION_OPTIONS }, - }, - }, - { - name: "caption_date_format", - selector: { - select: { - mode: "dropdown", - custom_value: true, - options: CAPTION_DATE_FORMAT_OPTIONS, - }, - }, - }, - { name: "caption_per_image", selector: { boolean: {} } }, - { - type: "grid", - name: "", - schema: [ - { name: "caption_color", selector: { text: {} } }, - { name: "caption_font_size", selector: { text: {} } }, - ], - }, - { - name: "caption_font_weight", - selector: { - select: { mode: "dropdown", options: CAPTION_WEIGHT_OPTIONS }, - }, - }, - { name: "caption_shadow", selector: { boolean: {} } }, - ], - }, ]; if (this._hasLiveControls()) { @@ -1986,15 +2176,13 @@ function createAlbumSlideshowCardEditorClass(Base) { c.tap_pause_seconds != null ? Number(c.tap_pause_seconds) : DEFAULTS.tap_pause_seconds, - ...this._captionData(), ...this._liveDataFromStates(), }; } /** Flatten the nested ``caption`` config into the fields ha-form binds. */ - _captionData() { - const cap = this._config && this._config.caption; - const enabled = !!cap && cap !== false; + _captionData(cap = this._editorCaptions()[0]) { + const enabled = !!cap && cap !== false && cap.enabled !== false; const c = cap && typeof cap === "object" ? cap : {}; let show = c.show; if (typeof show === "string") show = show.split(/[,\s]+/).filter(Boolean); @@ -2005,6 +2193,10 @@ function createAlbumSlideshowCardEditorClass(Base) { caption_position: c.position || CAPTION_DEFAULTS.position, caption_per_image: c.per_image !== false, caption_date_format: c.date_format || CAPTION_DEFAULTS.date_format, + caption_current_date_format: c.current_date_format || c.date_format || CAPTION_DEFAULTS.date_format, + caption_time_format: c.time_format || CAPTION_DEFAULTS.time_format, + caption_time_seconds: c.time_seconds === true, + caption_weather_entity: c.weather_entity || "", caption_color: c.color || CAPTION_DEFAULTS.color, caption_font_size: c.font_size || CAPTION_DEFAULTS.font_size, caption_font_weight: c.font_weight || CAPTION_DEFAULTS.font_weight, @@ -2012,6 +2204,313 @@ function createAlbumSlideshowCardEditorClass(Base) { }; } + _editorCaptions() { + const source = this._config.captions ?? (this._config.caption ? [this._config.caption] : []); + return Array.isArray(source) ? source.map((caption) => ({ + ...(caption && typeof caption === "object" ? caption : { enabled: caption !== false }), + })) : []; + } + + _captionSchema(caption = this._editorCaptions()[0]) { + const data = this._captionData(caption); + const schema = [ + { name: "caption_enabled", selector: { boolean: {} } }, + { name: "caption_position", selector: { select: { mode: "dropdown", options: CAPTION_POSITION_OPTIONS } } }, + { name: "caption_show", selector: { select: { multiple: true, reorder: true, mode: "dropdown", options: CAPTION_SHOW_OPTIONS } } }, + ]; + if (data.caption_show.includes("weather")) { + schema.push({ name: "caption_weather_entity", required: true, + selector: { entity: { filter: [{ domain: ["weather", "sensor"] }] } } }); + } + if (data.caption_show.includes("date")) { + schema.push({ name: "caption_date_format", selector: { select: { + mode: "dropdown", custom_value: true, options: CAPTION_DATE_FORMAT_OPTIONS, + } } }); + } + if (data.caption_show.includes("current_date")) { + schema.push({ name: "caption_current_date_format", selector: { select: { + mode: "dropdown", custom_value: true, options: CAPTION_DATE_FORMAT_OPTIONS, + } } }); + } + if (data.caption_show.includes("current_time")) { + schema.push( + { name: "caption_time_format", selector: { select: { mode: "dropdown", options: [ + { value: "auto", label: "Home Assistant preference" }, + { value: "12h", label: "12-hour" }, { value: "24h", label: "24-hour" }, + ] } } }, + { name: "caption_time_seconds", selector: { boolean: {} } }, + ); + } + if (data.caption_show.some((field) => !LIVE_CAPTION_FIELDS.has(field))) { + schema.push({ name: "caption_per_image", selector: { boolean: {} } }); + } + schema.push( + { type: "grid", name: "", schema: [ + { name: "caption_color", selector: { text: {} } }, + { name: "caption_font_size", selector: { text: {} } }, + ] }, + { name: "caption_font_weight", selector: { select: { mode: "dropdown", options: CAPTION_WEIGHT_OPTIONS } } }, + { name: "caption_shadow", selector: { boolean: {} } }, + ); + return schema; + } + + _saveCaptions(captions) { + const config = { ...this._config }; + const useList = Array.isArray(config.captions) || captions.length > 1; + delete config.caption; + delete config.captions; + if (captions.length) { + if (useList) config.captions = captions; + else config.caption = captions[0]; + } + this._config = config; + this._renderCaptionEditors(); + this.dispatchEvent(new CustomEvent("config-changed", { + detail: { config }, bubbles: true, composed: true, + })); + } + + _nextCaptionPosition(captions) { + const used = new Set(captions.map((caption) => caption.position || CAPTION_DEFAULTS.position)); + return ["bottom-left", "top-left", "bottom-right", "top-right", "bottom-center", "top-center", "center-left", "center-right", "center"] + .find((position) => !used.has(position)) || CAPTION_DEFAULTS.position; + } + + _addCaption(copyIndex) { + const captions = this._editorCaptions(); + const original = Number.isInteger(copyIndex) ? captions[copyIndex] : null; + captions.push({ + ...(original || {}), + show: [...this._captionData(original || {}).caption_show], + position: this._nextCaptionPosition(captions), + }); + this._openCaptionIndex = captions.length - 1; + this._saveCaptions(captions); + } + + _removeCaption(index) { + const captions = this._editorCaptions(); + captions.splice(index, 1); + this._openCaptionIndex = Math.min(index, captions.length - 1); + this._saveCaptions(captions); + } + + _captionChanged(index, event) { + event.stopPropagation(); + const captions = this._editorCaptions(); + if (!captions[index]) return; + const data = { ...this._captionData(captions[index]), ...event.detail?.value }; + let show = data.caption_show; + if (!Array.isArray(show)) show = typeof show === "string" ? show.split(/[,\s]+/) : []; + const caption = { show: [...new Set(show.filter((field) => CAPTION_FIELDS.includes(field)))] }; + if (data.caption_enabled === false) caption.enabled = false; + for (const field of ["position", "date_format", "time_format", "color", "font_size", "font_weight"]) { + const value = String(data[`caption_${field}`] || CAPTION_DEFAULTS[field]).trim(); + if (value && value !== CAPTION_DEFAULTS[field]) caption[field] = value; + } + if (caption.show.includes("current_date") || captions[index].current_date_format != null) { + const format = String(data.caption_current_date_format || CAPTION_DEFAULTS.date_format).trim(); + if (format !== (caption.date_format || CAPTION_DEFAULTS.date_format)) caption.current_date_format = format; + } + if (data.caption_per_image === false) caption.per_image = false; + if (data.caption_shadow === false) caption.shadow = false; + if (data.caption_time_seconds === true) caption.time_seconds = true; + if (typeof data.caption_weather_entity === "string" && data.caption_weather_entity.trim()) { + caption.weather_entity = data.caption_weather_entity.trim(); + } + captions[index] = caption; + this._saveCaptions(captions); + } + + _captionButton(icon, label, action) { + const button = document.createElement("button"); + button.type = "button"; + button.className = "caption-tool"; + button.title = label; + button.setAttribute("aria-label", label); + const symbol = document.createElement("ha-icon"); + symbol.setAttribute("icon", icon); + button.append(symbol); + button.addEventListener("click", action); + return button; + } + + _moveCaptionContent(index, event) { + event.stopPropagation(); + const { oldIndex, newIndex } = event.detail || {}; + const show = [...this._captionData(this._editorCaptions()[index]).caption_show]; + if (!Number.isInteger(oldIndex) || !Number.isInteger(newIndex) || oldIndex === newIndex || + oldIndex < 0 || oldIndex >= show.length || newIndex < 0 || newIndex >= show.length) return; + const [field] = show.splice(oldIndex, 1); + show.splice(newIndex, 0, field); + this._captionChanged(index, { stopPropagation() {}, detail: { value: { caption_show: show } } }); + } + + _createCaptionContentPicker(index) { + const content = document.createElement("div"); + content.className = "caption-content-selector"; + const label = document.createElement("span"); + label.className = "caption-content-label"; + label.id = `caption-content-label-${index}`; + label.textContent = "Content"; + const picker = document.createElement("ha-generic-picker"); + picker.label = "Content"; + picker.searchLabel = "Search content"; + picker.allowCustomValue = false; + picker.value = ""; + picker.setAttribute("no-sort", ""); + const field = document.createElement("div"); + field.slot = "field"; + field.className = "caption-content-field"; + field.setAttribute("role", "group"); + field.setAttribute("aria-labelledby", label.id); + const sortable = document.createElement("ha-sortable"); + sortable.setAttribute("no-style", ""); + sortable.setAttribute("handle-selector", "button.primary.action"); + sortable.setAttribute("filter", ".caption-content-add"); + sortable.addEventListener("item-moved", (event) => this._moveCaptionContent(index, event)); + const chips = document.createElement("ha-chip-set"); + const add = document.createElement("ha-assist-chip"); + add.className = "caption-content-add"; + add.label = "Add"; + const icon = document.createElement("ha-icon"); + icon.slot = "icon"; + icon.setAttribute("icon", "mdi:plus"); + add.append(icon); + add.addEventListener("click", async (event) => { + event.stopPropagation(); + await picker.updateComplete; + if (!add.disabled) picker.open(); + }); + picker.addEventListener("value-changed", (event) => { + event.stopPropagation(); + const selected = event.detail?.value; + const show = this._captionData(this._editorCaptions()[index]).caption_show; + if (!CAPTION_FIELDS.includes(selected) || show.includes(selected)) return; + this._captionChanged(index, { stopPropagation() {}, detail: { value: { caption_show: [...show, selected] } } }); + picker.value = ""; + }); + chips.append(add); + sortable.append(chips); + field.append(sortable); + picker.append(field); + content.append(label, picker); + return content; + } + + _updateCaptionContentPicker(content, index, data, selector) { + const picker = content.querySelector("ha-generic-picker"); + const chips = content.querySelector("ha-chip-set"); + const add = content.querySelector(".caption-content-add"); + const show = data.caption_show.filter((field) => CAPTION_FIELDS.includes(field)); + const items = selector.options.filter((option) => !show.includes(option.value)) + .map((option) => ({ id: option.value, primary: option.label, sorting_label: option.label })); + picker.hass = this._hass; + picker.getItems = () => items; + add.disabled = items.length === 0; + content.querySelector("ha-sortable").disabled = !selector.reorder; + const signature = JSON.stringify(show); + if (content._captionContentSignature === signature) return; + content._captionContentSignature = signature; + const selected = show.map((value) => { + const label = selector.options.find((option) => option.value === value)?.label || value; + const chip = document.createElement("ha-input-chip"); + chip.label = label; + chip.title = label; + chip.selected = true; + chip.setAttribute("data-field", value); + const icon = document.createElement("ha-icon"); + icon.slot = "icon"; + icon.setAttribute("icon", "mdi:drag-horizontal-variant"); + chip.append(icon, document.createTextNode(label)); + chip.addEventListener("click", (event) => event.stopPropagation()); + chip.addEventListener("remove", (event) => { + event.stopPropagation(); + const remaining = this._captionData(this._editorCaptions()[index]).caption_show.filter((field) => field !== value); + this._captionChanged(index, { stopPropagation() {}, detail: { value: { caption_show: remaining } } }); + }); + return chip; + }); + chips.replaceChildren(...selected, add); + } + + _renderCaptionEditors() { + const list = this.shadowRoot?.querySelector(".caption-list"); + if (!list) return; + const captions = this._editorCaptions(); + if (list.children.length !== captions.length) { + list.replaceChildren(); + captions.forEach((_caption, index) => { + const item = document.createElement("div"); + item.className = "caption-item"; + const details = document.createElement("details"); + details.open = index === this._openCaptionIndex || captions.length === 1; + const summary = document.createElement("summary"); + const chevron = document.createElement("ha-icon"); + chevron.className = "caption-chevron"; + chevron.setAttribute("icon", "mdi:chevron-right"); + chevron.setAttribute("aria-hidden", "true"); + const heading = document.createElement("span"); + heading.className = "caption-summary"; + const title = document.createElement("span"); + title.className = "caption-title"; + const meta = document.createElement("span"); + meta.className = "caption-meta"; + heading.append(title, meta); + summary.append(chevron, heading); + const body = document.createElement("div"); + body.className = "caption-body"; + const controls = document.createElement("ha-form"); + controls.className = "caption-controls"; + const options = document.createElement("ha-form"); + options.className = "caption-options"; + for (const form of [controls, options]) { + form.computeLabel = this._computeLabel; + form.computeHelper = this._computeHelper; + form.addEventListener("value-changed", (event) => this._captionChanged(index, event)); + } + body.append(controls, this._createCaptionContentPicker(index), options); + details.append(summary, body); + const tools = document.createElement("div"); + tools.className = "caption-tools"; + tools.append( + this._captionButton("mdi:content-copy", `Duplicate caption ${index + 1}`, () => this._addCaption(index)), + this._captionButton("mdi:delete-outline", `Remove caption ${index + 1}`, () => this._removeCaption(index)), + ); + item.append(details, tools); + list.append(item); + }); + } + captions.forEach((caption, index) => { + const item = list.children[index]; + const data = this._captionData(caption); + const position = CAPTION_POSITION_OPTIONS.find((option) => option.value === data.caption_position)?.label || data.caption_position; + const fields = data.caption_show.map((field) => CAPTION_SHOW_OPTIONS.find((option) => option.value === field)?.label) + .filter(Boolean).join(", ") || "Empty caption"; + const title = `${position}${data.caption_enabled ? "" : " (off)"}`; + item.querySelector(".caption-title").textContent = title; + item.querySelector(".caption-title").title = title; + item.querySelector(".caption-meta").textContent = fields; + item.querySelector(".caption-meta").title = fields; + item.querySelector("summary").setAttribute("aria-label", `Caption ${index + 1}: ${title}. ${fields}`); + item.classList.toggle("caption-disabled", !data.caption_enabled); + const schema = this._captionSchema(caption); + const contentIndex = schema.findIndex((field) => field.name === "caption_show"); + for (const [className, fields] of [ + [".caption-controls", schema.slice(0, contentIndex)], + [".caption-options", schema.slice(contentIndex + 1)], + ]) { + const form = item.querySelector(className); + form.hass = this._hass; + form.schema = fields; + form.data = data; + } + this._updateCaptionContentPicker(item.querySelector(".caption-content-selector"), index, data, + schema[contentIndex].selector.select); + }); + } + /** Read the current value of each surfaced integration entity. */ _liveDataFromStates() { const s = this._siblings; @@ -2028,7 +2527,7 @@ function createAlbumSlideshowCardEditorClass(Base) { out[`live_${f}`] = e ? e.state : ""; } } - for (const f of ["slide_interval", "pair_divider_px", "pair_min_gap_percent"]) { + for (const f of ["slide_interval", "pair_divider_px", "pair_min_gap_percent", "custom_lookback_days", "shuffle_age_bias"]) { if (s[f]) { const e = st(s[f]); out[`live_${f}`] = e ? Number(e.state) : null; @@ -2057,7 +2556,11 @@ function createAlbumSlideshowCardEditorClass(Base) { caption_show: "Show", caption_position: "Position", caption_per_image: "Per-image captions on pairs", - caption_date_format: "Date format", + caption_date_format: "Photo date format", + caption_current_date_format: "Today's date format", + caption_time_format: "Time format", + caption_time_seconds: "Show seconds", + caption_weather_entity: "Weather source", caption_color: "Text color", caption_font_size: "Font size", caption_font_weight: "Font weight", @@ -2075,10 +2578,12 @@ function createAlbumSlideshowCardEditorClass(Base) { "How long the card freezes its slide after a tap. 0 disables it.", caption_date_format: "Pick a preset or type a custom format (YYYY, MMMM, MMM, MM, DD, D, REL for relative time).", + caption_current_date_format: + "Pick a preset or type a custom format (YYYY, MMMM, MMM, MM, DD, D, REL for relative time).", caption_show: - "Description comes from the photo's EXIF/IPTC/XMP caption and is only available with the local-folder provider.", + "Available fields depend on the photo source. Missing values are omitted.", caption_per_image: - "When a portrait pair is shown, caption each photo with its own date, location and description.", + "Use each photo's own metadata on paired slides.", caption_color: "CSS color, e.g. #ffffff or white.", caption_font_size: "CSS size, e.g. 14px, 1.1em.", live_paused: @@ -2124,10 +2629,50 @@ function createAlbumSlideshowCardEditorClass(Base) { background: var(--primary-color); color: var(--text-primary-color, #fff); } .act:hover { opacity: 0.9; } + .caption-editors { display: block; } + .caption-content { padding: 4px 12px 12px; } + .caption-list { display: flex; flex-direction: column; gap: 12px; } + .caption-item { display: grid; min-width: 0; border: 1px solid var(--divider-color, #e0e0e0); border-radius: 8px; background: var(--card-background-color, #fff); } + .caption-item details { grid-area: 1 / 1; min-width: 0; } + .caption-item summary { display: flex; align-items: center; gap: 8px; box-sizing: border-box; padding: 12px 100px 12px 12px; min-height: 70px; border-radius: 7px; list-style: none; cursor: pointer; background: var(--secondary-background-color, #f5f5f5); } + .caption-item summary::-webkit-details-marker { display: none; } + .caption-item summary:focus-visible { outline: 2px solid var(--primary-color); outline-offset: -2px; } + .caption-item details[open] > summary { border-radius: 7px 7px 0 0; border-bottom: 1px solid var(--divider-color, #e0e0e0); } + .caption-chevron { flex: 0 0 18px; --mdc-icon-size: 18px; color: var(--secondary-text-color); } + .caption-item details[open] .caption-chevron { transform: rotate(90deg); } + .caption-summary { display: flex; flex-direction: column; flex: 1; min-width: 0; gap: 3px; } + .caption-title { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 14px; font-weight: 500; line-height: 1.35; } + .caption-meta { color: var(--secondary-text-color); font-size: 12px; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + .caption-disabled .caption-title { color: var(--secondary-text-color); } + .caption-body { padding: 12px; display: flex; flex-direction: column; gap: 20px; } + .caption-body ha-form { min-width: 0; } + .caption-content-selector { min-width: 0; } + .caption-content-label { display: block; margin-bottom: 8px; font-size: 14px; font-weight: 500; } + .caption-content-selector ha-generic-picker { display: block; width: 100%; } + .caption-content-field { position: relative; background: var(--mdc-text-field-fill-color, #f5f5f5); border-radius: 4px 4px 0 0; border-bottom: 1px solid var(--mdc-text-field-idle-line-color, #9e9e9e); } + .caption-content-field:focus-within { border-bottom-color: var(--primary-color); box-shadow: 0 1px 0 var(--primary-color); } + .caption-content-field ha-chip-set { padding: 10px 12px; min-height: 54px; box-sizing: border-box; } + .caption-content-field ha-input-chip { max-width: 100%; } + .caption-content-field ha-icon { --mdc-icon-size: 18px; } + .caption-content-add { order: 1; } + .caption-content-field .sortable-fallback { display: none; opacity: 0; } + .caption-content-field .sortable-ghost { opacity: 0.4; } + .caption-content-field .sortable-drag { cursor: grabbing; } + .caption-tools { grid-area: 1 / 1; align-self: start; justify-self: end; z-index: 1; display: flex; gap: 2px; padding: 10px 8px; } + .caption-tool { display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box; flex-shrink: 0; width: 36px; height: 36px; padding: 6px; border: 0; border-radius: 4px; background: transparent; color: var(--secondary-text-color, var(--primary-text-color)); cursor: pointer; } + .caption-tool:hover { background: var(--divider-color, #e0e0e0); color: var(--primary-text-color); } + .caption-tool:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 2px; } + .caption-add { width: 100%; min-height: 40px; gap: 8px; margin-top: 12px; border: 1px dashed var(--divider-color, #e0e0e0); border-radius: 6px; color: var(--primary-color); } + .caption-tool ha-icon { --mdc-icon-size: 20px; }
+ + +
Captions
+
+
@@ -2136,6 +2681,10 @@ function createAlbumSlideshowCardEditorClass(Base) { form.computeLabel = this._computeLabel; form.computeHelper = this._computeHelper; form.addEventListener("value-changed", (ev) => this._valueChanged(ev)); + const addCaption = this._captionButton("mdi:plus", "Add caption", () => this._addCaption()); + addCaption.classList.add("caption-add"); + addCaption.append(document.createTextNode("Add caption")); + this.shadowRoot.querySelector(".caption-content").append(addCaption); this._photoControls = new PhotoControls( this.shadowRoot.querySelector(".photo-controls"), () => this._hass, ); @@ -2153,6 +2702,7 @@ function createAlbumSlideshowCardEditorClass(Base) { form.hass = this._hass; form.schema = this._schema(); form.data = this._data(); + this._renderCaptionEditors(); const count = this._countSlideshowCameras(); this._lastEntityCount = count; @@ -2246,6 +2796,8 @@ function createAlbumSlideshowCardEditorClass(Base) { }); } else if ( field === "slide_interval" || + field === "custom_lookback_days" || + field === "shuffle_age_bias" || field === "pair_divider_px" || field === "pair_min_gap_percent" ) { @@ -2316,32 +2868,8 @@ function createAlbumSlideshowCardEditorClass(Base) { n.tap_pause_seconds = tps; } - // Caption: only emit a ``caption`` block when enabled and at least one - // field is selected. Non-default sub-settings are written; defaults are - // omitted to keep the YAML lean. - if (data.caption_enabled) { - let show = data.caption_show; - if (!Array.isArray(show)) show = show ? [show] : []; - show = show.filter( - (v) => v === "date" || v === "location" || v === "description", - ); - if (show.length > 0) { - const cap = { show }; - const pos = data.caption_position || CAPTION_DEFAULTS.position; - if (pos !== CAPTION_DEFAULTS.position) cap.position = pos; - if (data.caption_per_image === false) cap.per_image = false; - const df = data.caption_date_format || CAPTION_DEFAULTS.date_format; - if (df !== CAPTION_DEFAULTS.date_format) cap.date_format = df; - const col = (data.caption_color || "").trim(); - if (col && col.toLowerCase() !== CAPTION_DEFAULTS.color) cap.color = col; - const fs = (data.caption_font_size || "").trim(); - if (fs && fs !== CAPTION_DEFAULTS.font_size) cap.font_size = fs; - const fw = data.caption_font_weight || CAPTION_DEFAULTS.font_weight; - if (fw !== CAPTION_DEFAULTS.font_weight) cap.font_weight = fw; - if (data.caption_shadow === false) cap.shadow = false; - n.caption = cap; - } - } + if (Array.isArray(this._config.captions)) n.captions = this._config.captions; + else if (this._config.caption != null) n.caption = this._config.caption; this._config = n; this.dispatchEvent( diff --git a/custom_components/maintenance_supporter/__init__.py b/custom_components/maintenance_supporter/__init__.py index 67afa2a1..69b88299 100644 --- a/custom_components/maintenance_supporter/__init__.py +++ b/custom_components/maintenance_supporter/__init__.py @@ -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 diff --git a/custom_components/maintenance_supporter/calendar.py b/custom_components/maintenance_supporter/calendar.py index 4e56edc5..47069c16 100644 --- a/custom_components/maintenance_supporter/calendar.py +++ b/custom_components/maintenance_supporter/calendar.py @@ -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 diff --git a/custom_components/maintenance_supporter/config_flow_options_global.py b/custom_components/maintenance_supporter/config_flow_options_global.py index 4ec89b55..012c9901 100644 --- a/custom_components/maintenance_supporter/config_flow_options_global.py +++ b/custom_components/maintenance_supporter/config_flow_options_global.py @@ -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(), } ), ) diff --git a/custom_components/maintenance_supporter/config_flow_options_task_trigger.py b/custom_components/maintenance_supporter/config_flow_options_task_trigger.py index e64ee736..408c353b 100644 --- a/custom_components/maintenance_supporter/config_flow_options_task_trigger.py +++ b/custom_components/maintenance_supporter/config_flow_options_task_trigger.py @@ -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: diff --git a/custom_components/maintenance_supporter/const.py b/custom_components/maintenance_supporter/const.py index 264e8a3c..4e1151a8 100644 --- a/custom_components/maintenance_supporter/const.py +++ b/custom_components/maintenance_supporter/const.py @@ -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 diff --git a/custom_components/maintenance_supporter/coordinator.py b/custom_components/maintenance_supporter/coordinator.py index 0130c9c8..899af2d3 100644 --- a/custom_components/maintenance_supporter/coordinator.py +++ b/custom_components/maintenance_supporter/coordinator.py @@ -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 diff --git a/custom_components/maintenance_supporter/entity/triggers/__init__.py b/custom_components/maintenance_supporter/entity/triggers/__init__.py index bda183fa..a0de0a44 100644 --- a/custom_components/maintenance_supporter/entity/triggers/__init__.py +++ b/custom_components/maintenance_supporter/entity/triggers/__init__.py @@ -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. diff --git a/custom_components/maintenance_supporter/export.py b/custom_components/maintenance_supporter/export.py index 48b980a4..e8572b82 100644 --- a/custom_components/maintenance_supporter/export.py +++ b/custom_components/maintenance_supporter/export.py @@ -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_`` part ids). diff --git a/custom_components/maintenance_supporter/frontend-src/__tests__/_test-utils.ts b/custom_components/maintenance_supporter/frontend-src/__tests__/_test-utils.ts index d36841ae..e27a34eb 100644 --- a/custom_components/maintenance_supporter/frontend-src/__tests__/_test-utils.ts +++ b/custom_components/maintenance_supporter/frontend-src/__tests__/_test-utils.ts @@ -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, }; /** diff --git a/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-renderer.test.ts b/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-renderer.test.ts index f1ac1b09..81d20cdd 100644 --- a/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-renderer.test.ts +++ b/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-renderer.test.ts @@ -69,7 +69,7 @@ function ctx(overrides: Partial = {}): 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]), }), diff --git a/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-view.test.ts b/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-view.test.ts index 848ebca3..a4983c16 100644 --- a/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-view.test.ts +++ b/custom_components/maintenance_supporter/frontend-src/__tests__/task-detail-view.test.ts @@ -66,7 +66,7 @@ function ctx(overrides: Partial = {}): 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(), diff --git a/custom_components/maintenance_supporter/frontend-src/components/object-dialog.ts b/custom_components/maintenance_supporter/frontend-src/components/object-dialog.ts index 5a1af106..1da2ae5e 100644 --- a/custom_components/maintenance_supporter/frontend-src/components/object-dialog.ts +++ b/custom_components/maintenance_supporter/frontend-src/components/object-dialog.ts @@ -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` + 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; + }} + > + ${missing ? html`
${t("place_missing", L)}
` : nothing} + + ${this._place ? html`
${t("remind_on_site_hint", L)}
` : nothing} + `; + } + private async _save(): Promise { 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) || "")} > + ${this.placesEnabled ? this._renderPlace(L) : nothing} { + 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(OBJECT_DIALOG_TAG); if (!syncHass(dlg)) return false; dlg.openEdit(entryId, obj); + void applyObjectDialogSettings(dlg); return true; } diff --git a/custom_components/maintenance_supporter/frontend-src/locales/cs.json b/custom_components/maintenance_supporter/frontend-src/locales/cs.json index 496d5a89..553503b8 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/cs.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/cs.json @@ -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í.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/da.json b/custom_components/maintenance_supporter/frontend-src/locales/da.json index ee9fe532..e05874ee 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/da.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/da.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/de.json b/custom_components/maintenance_supporter/frontend-src/locales/de.json index d6be2e3b..26e3f83f 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/de.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/de.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/en.json b/custom_components/maintenance_supporter/frontend-src/locales/en.json index 963791e3..74362d38 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/en.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/en.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/es.json b/custom_components/maintenance_supporter/frontend-src/locales/es.json index 6a35fc58..614611a6 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/es.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/es.json @@ -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í.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/fi.json b/custom_components/maintenance_supporter/frontend-src/locales/fi.json index 9dfb0ca3..65c11c42 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/fi.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/fi.json @@ -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ä.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/fr.json b/custom_components/maintenance_supporter/frontend-src/locales/fr.json index b83b4dfc..87b6809c 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/fr.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/fr.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/hi.json b/custom_components/maintenance_supporter/frontend-src/locales/hi.json index ff6aad53..94fdc93d 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/hi.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/hi.json @@ -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": "केवल वे कार्य अनुस्मारक भेजते हैं जो चुने गए व्यू के लेबल/उपयोगकर्ता फ़िल्टर से मेल खाते हैं। व्यू की स्थिति, क्रम और समूहन यहाँ अनदेखे रहते हैं।", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/hu.json b/custom_components/maintenance_supporter/frontend-src/locales/hu.json index c819bab9..0fe88085 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/hu.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/hu.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/it.json b/custom_components/maintenance_supporter/frontend-src/locales/it.json index 25a11695..d7426916 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/it.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/it.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/ja.json b/custom_components/maintenance_supporter/frontend-src/locales/ja.json index cde6c06d..19acbefa 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/ja.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/ja.json @@ -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": "選択した保存済みビューのラベル/ユーザーフィルターに一致するタスクのみがリマインダーを送信します。ビューのステータス・並び順・グループ化はここでは無視されます。", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/ko.json b/custom_components/maintenance_supporter/frontend-src/locales/ko.json index dff2c732..10b873b2 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/ko.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/ko.json @@ -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": "선택한 저장된 보기의 라벨/사용자 필터와 일치하는 작업만 알림을 보냅니다. 보기의 상태·정렬·그룹화는 여기서 무시됩니다.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/nb.json b/custom_components/maintenance_supporter/frontend-src/locales/nb.json index d0640429..49db1a37 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/nb.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/nb.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/nl.json b/custom_components/maintenance_supporter/frontend-src/locales/nl.json index 82b507ac..90df823c 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/nl.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/nl.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/pl.json b/custom_components/maintenance_supporter/frontend-src/locales/pl.json index e7d7b605..bd71473e 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/pl.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/pl.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/pt-br.json b/custom_components/maintenance_supporter/frontend-src/locales/pt-br.json index 03c1a270..af53a8f0 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/pt-br.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/pt-br.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/pt.json b/custom_components/maintenance_supporter/frontend-src/locales/pt.json index 35d58bf1..48941a72 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/pt.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/pt.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/ru.json b/custom_components/maintenance_supporter/frontend-src/locales/ru.json index 30823484..788f909c 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/ru.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/ru.json @@ -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": "Напоминания отправляют только задачи, совпадающие с фильтрами метки/пользователя выбранного представления. Статус, сортировка и группировка представления здесь игнорируются.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/sv.json b/custom_components/maintenance_supporter/frontend-src/locales/sv.json index 2ed19dbc..7780d503 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/sv.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/sv.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/tr.json b/custom_components/maintenance_supporter/frontend-src/locales/tr.json index 26f2d7af..b65b9f5a 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/tr.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/tr.json @@ -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.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/uk.json b/custom_components/maintenance_supporter/frontend-src/locales/uk.json index e013ceb3..40d4978a 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/uk.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/uk.json @@ -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": "Нагадування надсилають лише завдання, що відповідають фільтрам мітки/користувача обраного подання. Статус, сортування та групування подання тут ігноруються.", diff --git a/custom_components/maintenance_supporter/frontend-src/locales/zh.json b/custom_components/maintenance_supporter/frontend-src/locales/zh.json index 64d4d24a..ed804b8e 100644 --- a/custom_components/maintenance_supporter/frontend-src/locales/zh.json +++ b/custom_components/maintenance_supporter/frontend-src/locales/zh.json @@ -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": "只有匹配所选视图的标签/用户筛选的任务才会发送提醒。视图的状态、排序和分组在此处被忽略。", diff --git a/custom_components/maintenance_supporter/frontend-src/maintenance-panel.ts b/custom_components/maintenance_supporter/frontend-src/maintenance-panel.ts index ea37680f..f91baef3 100644 --- a/custom_components/maintenance_supporter/frontend-src/maintenance-panel.ts +++ b/custom_components/maintenance_supporter/frontend-src/maintenance-panel.ts @@ -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 = {}; @state() private _detailStatsData: Map = new Map(); @state() private _miniStatsData: Map = 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(); + 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 { @@ -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 { ` : nothing} + ${this._features.places && this._allPlaces.length > 0 ? html` + + ` : nothing} + ${this._place?l`
${n("remind_on_site_hint",e)}
`:h} + `}async _save(){if(this._loading||!this._name.trim())return;this._error="";let e={name:this._name,manufacturer:this._manufacturer||null,model:this._model||null,serial_number:this._serialNumber||null,area_id:this._areaId||null,installation_date:this._installationDate||null,warranty_expiry:this._warrantyExpiry||null,documentation_url:this._documentationUrl.trim()||null,notes:this._notes.trim()||null,ha_device_id:this._haDeviceId||null,parent_entry_id:this._parentEntryId||null,...this.placesEnabled?{place:this._place||null,remind_on_site:!!this._place&&this._remindOnSite}:{}},t=await j(this,this._entryId?{type:"maintenance_supporter/object/update",entry_id:this._entryId,...e}:{type:"maintenance_supporter/object/create",...e},{busy:i=>{this._loading=i},fallbackKey:"save_error",onError:i=>{this._error=i}});t!==void 0&&(this._open=!1,this.dispatchEvent(new CustomEvent("object-saved",{detail:{device_swap:t?.device_swap}})))}_parentChoices(){return(this.objects||[]).filter(e=>e.entry_id!==this._entryId)}_close(){this._open=!1}render(){if(!this._open)return l``;if(this._replacing)return this._renderReplace();let e=this._lang,t=this._entryId?n("edit_object",e):n("new_object",e);return l`
${t}
@@ -1515,6 +1534,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._areaId} @value-changed=${i=>this._areaId=i.detail.value||""} > + ${this.placesEnabled?this._renderPlace(e):h}
- `}};P.styles=E` + `}};R.styles=E` + .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; @@ -1648,7 +1687,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .radio-row input { margin: 0; } - `,c([v({attribute:!1})],P.prototype,"hass",2),c([v({attribute:!1})],P.prototype,"objects",2),c([u()],P.prototype,"_open",2),c([u()],P.prototype,"_loading",2),c([u()],P.prototype,"_error",2),c([u()],P.prototype,"_name",2),c([u()],P.prototype,"_manufacturer",2),c([u()],P.prototype,"_model",2),c([u()],P.prototype,"_serialNumber",2),c([u()],P.prototype,"_areaId",2),c([u()],P.prototype,"_installationDate",2),c([u()],P.prototype,"_warrantyExpiry",2),c([u()],P.prototype,"_documentationUrl",2),c([u()],P.prototype,"_notes",2),c([u()],P.prototype,"_haDeviceId",2),c([u()],P.prototype,"_parentEntryId",2),c([u()],P.prototype,"_entryId",2),c([u()],P.prototype,"_replacing",2),c([u()],P.prototype,"_oldDeviceId",2),c([u()],P.prototype,"_replaceDevice",2);customElements.get("maintenance-object-dialog")||customElements.define("maintenance-object-dialog",P)});function co(s){let r=(s||"").split(/\s+/).filter(Boolean);return r.length===0?"?":r.length===1?r[0][0].toUpperCase():(r[0][0]+r[r.length-1][0]).toUpperCase()}function po(s){let r=0;for(let e of s)r=r*31+e.charCodeAt(0)>>>0;return Gs[r%Gs.length]}function Ks(s){return s?{id:s.id,name:s.name,initials:s.initials||co(s.name),color:s.color||po(s.id)}:null}var Gs,Ys=y(()=>{"use strict";I();Gs=["#c62828","#ad1457","#6a1b9a","#4527a0","#283593","#1565c0","#00838f","#2e7d32","#558b2f","#ef6c00","#6d4c41","#546e7a"]});var ti,Qs=y(()=>{"use strict";Ys();ti=class{constructor(r){this.usersCache=null;this.cacheTimestamp=0;this.CACHE_TTL_MS=6e4;this.hass=r}updateHass(r){this.hass=r}async getUsers(r=!1){let e=Date.now();if(!r&&this.usersCache&&e-this.cacheTimestampt.id===r)?.name||null}getPerson(r){return Ks(this.getUser(r))}getUser(r){return!r||!this.usersCache?null:this.usersCache.find(e=>e.id===r)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(r){return r?r===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}}});function ae(s){return`${s.entry_id??""}\0${s.part_id}`}function Zs(s,r,e,t){let i=!!s.entry_id&&s.entry_id!==r,a=i?s.entry_id:r,o=e.find(m=>m.entry_id===a),d=(o?.parts||[]).find(m=>m.id===s.part_id)||null,p=i&&o?.object?.name||"",_=d?.name||n("shared_part_unknown",t);return{part:d,foreign:i,ownerName:p,label:p?`${_} (${p})`:_}}function Js(s,r,e,t){let{part:i,label:a}=Zs(s,r,e,t),o=i&&i.stock!==null&&i.stock!==void 0?` (${Ye(i.stock,i.unit,t)})`:"",d=i?.storage_location?` \u2014 ${i.storage_location}`:"";return`${C(s.quantity,t)}\xD7 ${a}${o}${d}`}function Xs(s,r,e,t){let a=(e.find(d=>d.entry_id===r)?.parts||[]).map(d=>({...d})),o=new Set(a.map(d=>ae({part_id:d.id})));for(let d of s?.consumes_parts||[]){if(!d.entry_id||d.entry_id===r)continue;let p=ae(d);if(o.has(p))continue;o.add(p);let{part:_,ownerName:m}=Zs(d,r,e,t);a.push({id:d.part_id,name:_?.name||n("shared_part_unknown",t),unit:_?.unit,stock:_?.stock??null,storage_location:_?.storage_location,entry_id:d.entry_id,owner_name:m})}return a}var ii=y(()=>{"use strict";T()});var Ki,en,tn,rn=y(()=>{"use strict";Ki=["sensor","binary_sensor","number","input_number","input_boolean","switch","climate","vacuum","cover","fan","light","water_heater","humidifier","media_player","weather","air_quality","valve","lawn_mower","lock"],en=["sensor"],tn=["temperature","humidity","pressure"]});function et(s){let r=(s??"").trim();if(r==="")return null;let e=Number(r.replace(",","."));return!Number.isFinite(e)||e<0?null:Math.round(e)}var ri=y(()=>{"use strict"});var Yi,Tt,Qi=y(()=>{"use strict";Yi=["notes","cost","duration","photo","user"],Tt={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"}});var uo,ho,Zi,sn=y(()=>{"use strict";uo={cleaning:"mdi:broom",inspection:"mdi:magnify",replacement:"mdi:swap-horizontal",calibration:"mdi:tune",service:"mdi:wrench",reading:"mdi:counter",custom:"mdi:wrench-clock"},ho="mdi:wrench-clock",Zi=s=>s&&uo[s]||ho});var ke,si=y(()=>{"use strict";I();F();T();ke=class extends S{constructor(){super(...arguments);this.value="";this.lang="en";this._credit=!1;this._amount=""}willUpdate(e){if(!e.has("value"))return;let t=(this.value??"").trim();if(t===this._signed())return;let i=parseFloat(t);if(t===""||Number.isNaN(i)){this._amount="",this._credit=!1;return}this._credit=i<0,this._amount=String(Math.abs(i))}_signed(){let e=this._amount.trim();return e===""?"":this._credit?`-${e}`:e}_emit(){this.value=this._signed(),this.dispatchEvent(new CustomEvent("value-changed",{detail:{value:this.value},bubbles:!0,composed:!0}))}_setCredit(e){this._credit!==e&&(this._credit=e,this._emit())}_onInput(e){let t=e.target.value;t.startsWith("-")&&(this._credit=!0),this._amount=t.replace(/^-+/,""),this._emit()}render(){let e=this.lang;return l` + `,c([v({attribute:!1})],R.prototype,"hass",2),c([v({attribute:!1})],R.prototype,"objects",2),c([v({type:Boolean})],R.prototype,"placesEnabled",2),c([u()],R.prototype,"_open",2),c([u()],R.prototype,"_loading",2),c([u()],R.prototype,"_error",2),c([u()],R.prototype,"_name",2),c([u()],R.prototype,"_manufacturer",2),c([u()],R.prototype,"_model",2),c([u()],R.prototype,"_serialNumber",2),c([u()],R.prototype,"_areaId",2),c([u()],R.prototype,"_installationDate",2),c([u()],R.prototype,"_warrantyExpiry",2),c([u()],R.prototype,"_documentationUrl",2),c([u()],R.prototype,"_notes",2),c([u()],R.prototype,"_haDeviceId",2),c([u()],R.prototype,"_parentEntryId",2),c([u()],R.prototype,"_place",2),c([u()],R.prototype,"_remindOnSite",2),c([u()],R.prototype,"_entryId",2),c([u()],R.prototype,"_replacing",2),c([u()],R.prototype,"_oldDeviceId",2),c([u()],R.prototype,"_replaceDevice",2);customElements.get("maintenance-object-dialog")||customElements.define("maintenance-object-dialog",R)});function _o(s){let r=(s||"").split(/\s+/).filter(Boolean);return r.length===0?"?":r.length===1?r[0][0].toUpperCase():(r[0][0]+r[r.length-1][0]).toUpperCase()}function mo(s){let r=0;for(let e of s)r=r*31+e.charCodeAt(0)>>>0;return Ks[r%Ks.length]}function Ys(s){return s?{id:s.id,name:s.name,initials:s.initials||_o(s.name),color:s.color||mo(s.id)}:null}var Ks,Qs=y(()=>{"use strict";I();Ks=["#c62828","#ad1457","#6a1b9a","#4527a0","#283593","#1565c0","#00838f","#2e7d32","#558b2f","#ef6c00","#6d4c41","#546e7a"]});var ii,Zs=y(()=>{"use strict";Qs();ii=class{constructor(r){this.usersCache=null;this.cacheTimestamp=0;this.CACHE_TTL_MS=6e4;this.hass=r}updateHass(r){this.hass=r}async getUsers(r=!1){let e=Date.now();if(!r&&this.usersCache&&e-this.cacheTimestampt.id===r)?.name||null}getPerson(r){return Ys(this.getUser(r))}getUser(r){return!r||!this.usersCache?null:this.usersCache.find(e=>e.id===r)||null}getCurrentUserId(){return this.hass.user?.id||null}isCurrentUser(r){return r?r===this.getCurrentUserId():!1}clearCache(){this.usersCache=null,this.cacheTimestamp=0}}});function ae(s){return`${s.entry_id??""}\0${s.part_id}`}function Js(s,r,e,t){let i=!!s.entry_id&&s.entry_id!==r,a=i?s.entry_id:r,o=e.find(m=>m.entry_id===a),d=(o?.parts||[]).find(m=>m.id===s.part_id)||null,p=i&&o?.object?.name||"",_=d?.name||n("shared_part_unknown",t);return{part:d,foreign:i,ownerName:p,label:p?`${_} (${p})`:_}}function Xs(s,r,e,t){let{part:i,label:a}=Js(s,r,e,t),o=i&&i.stock!==null&&i.stock!==void 0?` (${Ye(i.stock,i.unit,t)})`:"",d=i?.storage_location?` \u2014 ${i.storage_location}`:"";return`${C(s.quantity,t)}\xD7 ${a}${o}${d}`}function en(s,r,e,t){let a=(e.find(d=>d.entry_id===r)?.parts||[]).map(d=>({...d})),o=new Set(a.map(d=>ae({part_id:d.id})));for(let d of s?.consumes_parts||[]){if(!d.entry_id||d.entry_id===r)continue;let p=ae(d);if(o.has(p))continue;o.add(p);let{part:_,ownerName:m}=Js(d,r,e,t);a.push({id:d.part_id,name:_?.name||n("shared_part_unknown",t),unit:_?.unit,stock:_?.stock??null,storage_location:_?.storage_location,entry_id:d.entry_id,owner_name:m})}return a}var ri=y(()=>{"use strict";T()});var Yi,tn,rn,sn=y(()=>{"use strict";Yi=["sensor","binary_sensor","number","input_number","input_boolean","switch","climate","vacuum","cover","fan","light","water_heater","humidifier","media_player","weather","air_quality","valve","lawn_mower","lock"],tn=["sensor"],rn=["temperature","humidity","pressure"]});function et(s){let r=(s??"").trim();if(r==="")return null;let e=Number(r.replace(",","."));return!Number.isFinite(e)||e<0?null:Math.round(e)}var si=y(()=>{"use strict"});var Qi,Tt,Zi=y(()=>{"use strict";Qi=["notes","cost","duration","photo","user"],Tt={notes:"notes_label",cost:"cost",duration:"duration",photo:"photo_label",user:"user_label"}});var go,fo,Ji,nn=y(()=>{"use strict";go={cleaning:"mdi:broom",inspection:"mdi:magnify",replacement:"mdi:swap-horizontal",calibration:"mdi:tune",service:"mdi:wrench",reading:"mdi:counter",custom:"mdi:wrench-clock"},fo="mdi:wrench-clock",Ji=s=>s&&go[s]||fo});function ni(s){return s?Array.isArray(s.entity_ids)&&s.entity_ids.length>0?[...s.entity_ids]:s.entity_id?[s.entity_id]:[]:[]}function an(s){if(!(!s||s.type==="compound"))return ni(s)[0]}var on=y(()=>{"use strict"});var ke,ai=y(()=>{"use strict";I();F();T();ke=class extends S{constructor(){super(...arguments);this.value="";this.lang="en";this._credit=!1;this._amount=""}willUpdate(e){if(!e.has("value"))return;let t=(this.value??"").trim();if(t===this._signed())return;let i=parseFloat(t);if(t===""||Number.isNaN(i)){this._amount="",this._credit=!1;return}this._credit=i<0,this._amount=String(Math.abs(i))}_signed(){let e=this._amount.trim();return e===""?"":this._credit?`-${e}`:e}_emit(){this.value=this._signed(),this.dispatchEvent(new CustomEvent("value-changed",{detail:{value:this.value},bubbles:!0,composed:!0}))}_setCredit(e){this._credit!==e&&(this._credit=e,this._emit())}_onInput(e){let t=e.target.value;t.startsWith("-")&&(this._credit=!0),this._amount=t.replace(/^-+/,""),this._emit()}render(){let e=this.lang;return l`
- `}_applyConsumesQtyText(){let e={...this._consumesParts};for(let t of Object.keys(e)){let i=this._consumesQtyText[t];if(i===void 0)continue;let a=parseFloat(i.replace(",","."));if(!Number.isFinite(a)||aMe[1]){let o=d=>C(d,this._lang,{maximumFractionDigits:2});return this._error=n("settings_value_out_of_range",this._lang).replace("{min}",o(Me[0])).replace("{max}",o(Me[1])),!1}e[t]={...e[t],quantity:a}}return this._consumesParts=e,!0}_toggleRequired(e,t){let i=new Set(this._requiredCompletion);t?i.add(e):i.delete(e),this._requiredCompletion=[...i]}_patchReading(e,t){this._readings=this._readings.map(i=>i.id===e?{...i,...t}:i)}_renderReadingsEditor(e){let t=Ls(this._readings);return l` + `}_applyConsumesQtyText(){let e={...this._consumesParts};for(let t of Object.keys(e)){let i=this._consumesQtyText[t];if(i===void 0)continue;let a=parseFloat(i.replace(",","."));if(!Number.isFinite(a)||aMe[1]){let o=d=>C(d,this._lang,{maximumFractionDigits:2});return this._error=n("settings_value_out_of_range",this._lang).replace("{min}",o(Me[0])).replace("{max}",o(Me[1])),!1}e[t]={...e[t],quantity:a}}return this._consumesParts=e,!0}_toggleRequired(e,t){let i=new Set(this._requiredCompletion);t?i.add(e):i.delete(e),this._requiredCompletion=[...i]}_patchReading(e,t){this._readings=this._readings.map(i=>i.id===e?{...i,...t}:i)}_renderReadingsEditor(e){let t=Ns(this._readings);return l`
${n("readings_section",e)}
${n("readings_hint",e)}
@@ -1811,9 +1850,9 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:"
`)} - ${this._readings.lengththis._readings=[...this._readings,{id:As(),name:"",unit:this._readings.length?this._readings[this._readings.length-1].unit:this._readingUnit}]}> + @click=${()=>this._readings=[...this._readings,{id:Cs(),name:"",unit:this._readings.length?this._readings[this._readings.length-1].unit:this._readingUnit}]}> ${n("reading_add",e)} `:h}
@@ -1868,7 +1907,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" ${i.reqOverride?l`
- ${Yi.map(a=>l` + ${Qi.map(a=>l`
`:h} - `}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),t=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(t)&&e>t){this._error=`${n("adaptive_min_interval",this._lang)} > ${n("adaptive_max_interval",this._lang)}`;return}}if(this._triggerType==="threshold"&&this._thresholdLimitsOverlap()){this._error=n("trigger_hint_overlap",this._lang);return}if(this._scheduleType==="calendar"&&!this._calendarEntity.trim().startsWith("calendar.")){this._error=n("calendar_entity_required",this._lang);return}if(this._applyConsumesQtyText()){this._loading=!0,this._error="";try{let e=await j(this,()=>this.hass.connection.sendMessagePromise(this._savePayload()),{fallbackKey:"save_error",onError:o=>{this._error=o}});if(e===void 0)return;let t=this._taskId||e?.task_id,i=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;this._warning="";let a=o=>{this._warning=n("subsave_warning",this._lang).replace("{detail}",o)};if(t&&this._scheduleType==="sensor_based"&&i&&await j(this,{type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:t,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null},{onError:a})!==void 0&&(this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute),t&&this._adaptiveSnapshot()!==this._adaptiveInitial){let o=parseFloat(this._adaptiveAlpha),d=parseInt(this._adaptiveMin,10),p=parseInt(this._adaptiveMax,10);await j(this,{type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:t,enabled:this._adaptiveEnabled,...o>=$t[0]&&o<=$t[1]?{ewa_alpha:o}:{},...!isNaN(d)&&d>=1?{min_interval_days:d}:{},...!isNaN(p)&&p>=1?{max_interval_days:p}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction},{onError:a})!==void 0&&(this._adaptiveInitial=this._adaptiveSnapshot())}this._warning?t&&(this._taskId=t):this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}finally{this._loading=!1}}}}_savePayload(){let e={type:this._taskId?"maintenance_supporter/task/update":"maintenance_supporter/task/create",entry_id:this._entryId,name:this._name,task_type:this._type,schedule_type:this._scheduleType,warning_days:Number.isNaN(parseInt(this._warningDays,10))?this.defaultWarningDays:Math.max(0,parseInt(this._warningDays,10))},t=this._earliestCompletionDays.trim();e.earliest_completion_days=t===""?null:Math.max(0,parseInt(t,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):ni.includes(this._scheduleType)?(e.schedule={...this._buildSchedule(),...this._recurrenceExtras()},e.interval_days=null,this._taskId&&(e.due_date=null)):(this._taskId&&(e.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(e.interval_days=parseInt(this._intervalDays,10),e.interval_unit=this._intervalUnit,e.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(e.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(e.interval_days=null,e.interval_anchor="completion")),e.notes=this._notes||null,e.documentation_url=this._documentationUrl||null,e.custom_icon=this._customIcon||null,e.notify_icon=this._notifyIcon.trim()||null,e.priority=this._priority,e.labels=this._labels.split(",").map(i=>i.trim()).filter(Boolean),e.mirror_todo_entities=this._mirrorTodoEntities.filter(Boolean),e.enabled=this._enabled,(!this._taskId||this._lastPerformed!==this._loadedLastPerformed)&&(e.last_performed=this._lastPerformed||null),e.nfc_tag_id=this._nfcTagId||null,e.require_tag_scan=this._requireTagScan,e.allow_skip=this._allowSkip,e.notify_enabled=this._notifyEnabled,e.reading_unit=this._readingUnit.trim()||null,e.readings=Ns(this._readings);{let i={};for(let o of this._phaseDefs){if(!o.name.trim())continue;let d={...o.carry,name:o.name.trim()},p=o.checklistText.split(` -`).map(m=>m.trim()).filter(Boolean);p.length&&(d.checklist=p);let _=[];if(o.partId){let m=parseFloat(o.partQty);_.push({part_id:o.partId,quantity:Number.isFinite(m)&&m>0?m:1})}for(let m of o.extraParts)_.push(m.entry_id?{part_id:m.part_id,quantity:m.quantity,entry_id:m.entry_id}:{part_id:m.part_id,quantity:m.quantity});_.length&&(d.consumes_parts=_),o.reqOverride&&(d.required_completion_fields=[...o.reqFields]),i[o.id]=d}let a=this._phaseSeq.filter(o=>o in i);e.phases=Object.keys(i).length&&a.length?i:null,e.phase_sequence=e.phases?a:null}if((this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(i=>i.entry_id?{part_id:i.part_id,quantity:i.quantity,entry_id:i.entry_id}:{part_id:i.part_id,quantity:i.quantity})),(!this._taskId||this._responsibleUserId!==this._loadedResponsibleUserId)&&(e.responsible_user_id=this._responsibleUserId),e.assignee_pool=this._assigneePool,e.required_completion_fields=this._requiredCompletion,e.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let i=this._compoundConditions.map(bo).filter(a=>a!==null);if(i.length>0){let a={type:"compound",compound_logic:this._compoundLogic,conditions:i};this._autoCompleteOnRecovery&&(a.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(a.trigger_combinator="all"),e.trigger_config=a}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let i=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],a={entity_id:i[0],entity_ids:i,type:this._triggerType};if(dn(a,this._typeFields()),this._autoCompleteOnRecovery&&(a.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(a.trigger_combinator="all"),i.length>1&&(a.entity_logic=this._triggerEntityLogic),this._triggerType==="counter"&&this._triggerDeltaMode&&this._triggerBaselineValue){let o=parseFloat(this._triggerBaselineValue);!isNaN(o)&&o>=0&&(a.trigger_baseline_value=o)}else if(this._triggerType==="runtime"&&this._triggerRuntimeMaxSession){let o=parseInt(this._triggerRuntimeMaxSession,10);!isNaN(o)&&o>0&&(a.trigger_runtime_max_session_seconds=o)}e.trigger_config=a}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&nn.includes(this._scheduleType)){let i=this._scheduleTimeOn?this._scheduleTime.trim():"";e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(i)?i:null}if(this.checklistsEnabled){let i=this._checklistText.split(` + `}async _save(){if(!this._loading&&this._name.trim()){if(this._adaptiveSnapshot()!==this._adaptiveInitial){let e=parseInt(this._adaptiveMin,10),t=parseInt(this._adaptiveMax,10);if(!isNaN(e)&&!isNaN(t)&&e>t){this._error=`${n("adaptive_min_interval",this._lang)} > ${n("adaptive_max_interval",this._lang)}`;return}}if(this._triggerType==="threshold"&&this._thresholdLimitsOverlap()){this._error=n("trigger_hint_overlap",this._lang);return}if(this._scheduleType==="calendar"&&!this._calendarEntity.trim().startsWith("calendar.")){this._error=n("calendar_entity_required",this._lang);return}if(this._applyConsumesQtyText()){this._loading=!0,this._error="";try{let e=await j(this,()=>this.hass.connection.sendMessagePromise(this._savePayload()),{fallbackKey:"save_error",onError:o=>{this._error=o}});if(e===void 0)return;let t=this._taskId||e?.task_id,i=this._environmentalEntity!==this._environmentalInitial||this._environmentalAttribute!==this._environmentalAttributeInitial;this._warning="";let a=o=>{this._warning=n("subsave_warning",this._lang).replace("{detail}",o)};if(t&&this._scheduleType==="sensor_based"&&i&&await j(this,{type:"maintenance_supporter/task/set_environmental_entity",entry_id:this._entryId,task_id:t,environmental_entity:this._environmentalEntity||null,environmental_attribute:this._environmentalAttribute||null},{onError:a})!==void 0&&(this._environmentalInitial=this._environmentalEntity,this._environmentalAttributeInitial=this._environmentalAttribute),t&&this._adaptiveSnapshot()!==this._adaptiveInitial){let o=parseFloat(this._adaptiveAlpha),d=parseInt(this._adaptiveMin,10),p=parseInt(this._adaptiveMax,10);await j(this,{type:"maintenance_supporter/task/set_adaptive",entry_id:this._entryId,task_id:t,enabled:this._adaptiveEnabled,...o>=$t[0]&&o<=$t[1]?{ewa_alpha:o}:{},...!isNaN(d)&&d>=1?{min_interval_days:d}:{},...!isNaN(p)&&p>=1?{max_interval_days:p}:{},seasonal_enabled:this._adaptiveSeasonal,sensor_prediction_enabled:this._adaptivePrediction},{onError:a})!==void 0&&(this._adaptiveInitial=this._adaptiveSnapshot())}this._warning?t&&(this._taskId=t):this._open=!1,this.dispatchEvent(new CustomEvent("task-saved"))}finally{this._loading=!1}}}}_savePayload(){let e={type:this._taskId?"maintenance_supporter/task/update":"maintenance_supporter/task/create",entry_id:this._entryId,name:this._name,task_type:this._type,schedule_type:this._scheduleType,warning_days:Number.isNaN(parseInt(this._warningDays,10))?this.defaultWarningDays:Math.max(0,parseInt(this._warningDays,10))},t=this._earliestCompletionDays.trim();e.earliest_completion_days=t===""?null:Math.max(0,parseInt(t,10)||0),this._taskId&&(e.task_id=this._taskId),this._scheduleType==="one_time"?(e.due_date=this._dueDate||null,e.interval_days=null):oi.includes(this._scheduleType)?(e.schedule={...this._buildSchedule(),...this._recurrenceExtras()},e.interval_days=null,this._taskId&&(e.due_date=null)):(this._taskId&&(e.due_date=null),this._scheduleType!=="manual"&&this._intervalDays?(e.interval_days=parseInt(this._intervalDays,10),e.interval_unit=this._intervalUnit,e.interval_anchor=this._intervalAnchor,this._scheduleType==="time_based"&&(e.schedule={kind:"interval",...this._recurrenceExtras()})):this._taskId&&(e.interval_days=null,e.interval_anchor="completion")),e.notes=this._notes||null,e.documentation_url=this._documentationUrl||null,e.custom_icon=this._customIcon||null,e.notify_icon=this._notifyIcon.trim()||null,e.priority=this._priority,e.labels=this._labels.split(",").map(i=>i.trim()).filter(Boolean),e.mirror_todo_entities=this._mirrorTodoEntities.filter(Boolean),e.enabled=this._enabled,(!this._taskId||this._lastPerformed!==this._loadedLastPerformed)&&(e.last_performed=this._lastPerformed||null),e.nfc_tag_id=this._nfcTagId||null,e.require_tag_scan=this._requireTagScan,e.allow_skip=this._allowSkip,e.notify_enabled=this._notifyEnabled,e.reading_unit=this._readingUnit.trim()||null,e.readings=qs(this._readings);{let i={};for(let o of this._phaseDefs){if(!o.name.trim())continue;let d={...o.carry,name:o.name.trim()},p=o.checklistText.split(` +`).map(m=>m.trim()).filter(Boolean);p.length&&(d.checklist=p);let _=[];if(o.partId){let m=parseFloat(o.partQty);_.push({part_id:o.partId,quantity:Number.isFinite(m)&&m>0?m:1})}for(let m of o.extraParts)_.push(m.entry_id?{part_id:m.part_id,quantity:m.quantity,entry_id:m.entry_id}:{part_id:m.part_id,quantity:m.quantity});_.length&&(d.consumes_parts=_),o.reqOverride&&(d.required_completion_fields=[...o.reqFields]),i[o.id]=d}let a=this._phaseSeq.filter(o=>o in i);e.phases=Object.keys(i).length&&a.length?i:null,e.phase_sequence=e.phases?a:null}if((this.parts.length||this._foreignOwners.length)&&(e.consumes_parts=Object.values(this._consumesParts).map(i=>i.entry_id?{part_id:i.part_id,quantity:i.quantity,entry_id:i.entry_id}:{part_id:i.part_id,quantity:i.quantity})),(!this._taskId||this._responsibleUserId!==this._loadedResponsibleUserId)&&(e.responsible_user_id=this._responsibleUserId),e.assignee_pool=this._assigneePool,e.required_completion_fields=this._requiredCompletion,e.rotation_strategy=this._assigneePool.length>=2&&this._rotationStrategy?this._rotationStrategy:null,this._scheduleType==="sensor_based"&&this._triggerType==="compound"){let i=this._compoundConditions.map($o).filter(a=>a!==null);if(i.length>0){let a={type:"compound",compound_logic:this._compoundLogic,conditions:i};this._autoCompleteOnRecovery&&(a.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(a.trigger_combinator="all"),e.trigger_config=a}else this._taskId&&(e.trigger_config=null)}else if(this._scheduleType==="sensor_based"&&this._triggerEntityId){let i=this._triggerEntityIds.length>0?this._triggerEntityIds:[this._triggerEntityId],a={entity_id:i[0],entity_ids:i,type:this._triggerType};if(hn(a,this._typeFields()),this._autoCompleteOnRecovery&&(a.auto_complete_on_recovery=!0),this._triggerCombinator==="all"&&(a.trigger_combinator="all"),i.length>1&&(a.entity_logic=this._triggerEntityLogic),this._triggerType==="counter"&&this._triggerDeltaMode&&this._triggerBaselineValue){let o=parseFloat(this._triggerBaselineValue);!isNaN(o)&&o>=0&&(a.trigger_baseline_value=o)}else if(this._triggerType==="runtime"&&this._triggerRuntimeMaxSession){let o=parseInt(this._triggerRuntimeMaxSession,10);!isNaN(o)&&o>0&&(a.trigger_runtime_max_session_seconds=o)}e.trigger_config=a}else this._taskId&&(e.trigger_config=null);if(this.scheduleTimeEnabled&&ln.includes(this._scheduleType)){let i=this._scheduleTimeOn?this._scheduleTime.trim():"";e.schedule_time=/^([01]\d|2[0-3]):[0-5]\d$/.test(i)?i:null}if(this.checklistsEnabled){let i=this._checklistText.split(` `).map(a=>a.trim()).filter(Boolean).slice(0,100);e.checklist=i.length?i:null}if(this.completionActionsEnabled||this._actionPresent){let i=this._actionService.trim();if(i&&/^[a-z][a-z0-9_]*\.[a-z0-9_]+$/.test(i)){let a={service:i},o=this._actionTargetEntity.trim();this._actionTargetStored&&o===this._actionTargetInitial?a.target=JSON.parse(JSON.stringify(this._actionTargetStored)):o&&(a.target={entity_id:o});let d=this._buildActionData();Object.keys(d).length>0&&(a.data=d),this._actionSkipAuto&&(a.skip_auto=!0),e.on_complete_action=a}else e.on_complete_action=null}if(this.completionActionsEnabled){let i={};this._qcNotes.trim()&&(i.notes=this._qcNotes.trim());let a=parseFloat(this._qcCost);isNaN(a)||(i.cost=a);let o=et(this._qcDuration);o!==null&&(i.duration=o),this._qcFeedback&&(i.feedback=this._qcFeedback),e.quick_complete_defaults=Object.keys(i).length?i:null}return e}_close(){this._open=!1,this._warning="",this._pickerProbeTimer!==void 0&&(clearTimeout(this._pickerProbeTimer),this._pickerProbeTimer=void 0),this._pickerProbeStrikes=0}_renderTriggerFields(){if(this._scheduleType!=="sensor_based")return h;let e=this._lang,t=this._triggerType==="compound";return l`

${n("trigger_configuration",e)}

@@ -1914,7 +1953,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._triggerType} @change=${i=>this._triggerType=i.target.value} > - ${fo.map(i=>l``)} + ${xo.map(i=>l``)}
${t?this._renderCompoundEditor():l` @@ -1928,7 +1967,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" 0?this._triggerEntityIds:this._triggerEntityId?[this._triggerEntityId]:[]}} .computeLabel=${()=>n("entity_id",e)} @value-changed=${i=>{let a=(i.detail.value.trigger_entities||[]).filter(Boolean);this._triggerEntityId=a[0]||"",this._triggerEntityIds=a,a[0]?this._fetchEntityAttributes(a[0]):this._fetchEntityAttributes("")}} @@ -1976,7 +2015,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" `:h} - `}_patchCondition(e,t){this._compoundConditions=this._compoundConditions.map((i,a)=>a===e?{...i,...t}:i)}_addCondition(){this._compoundConditions=[...this._compoundConditions,on()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((t,i)=>i!==e)}_renderCompoundEditor(){let e=this._lang;return l` + `}_patchCondition(e,t){this._compoundConditions=this._compoundConditions.map((i,a)=>a===e?{...i,...t}:i)}_addCondition(){this._compoundConditions=[...this._compoundConditions,dn()]}_removeCondition(e){this._compoundConditions=this._compoundConditions.filter((t,i)=>i!==e)}_renderCompoundEditor(){let e=this._lang;return l`
${this._renderConditionTypeFields(e,t)} @@ -2175,12 +2214,12 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" > ${["days","weeks","months","years"].map(t=>l``)} - `}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(t=>t!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(this._scheduleType==="calendar"&&!this._calendarEntity.trim())return null;if(ni.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let e=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!e||e<=0?null:{kind:"interval",every:e,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(e){super.updated?.(e),this._scheduleEntityPickerProbe();for(let t of e.keys())if(g._PREVIEW_RELEVANT.has(String(t))){this._schedulePreviewRefresh();return}}_scheduleEntityPickerProbe(){this._entityPickerFallback||this._pickerProbeTimer!==void 0||!this._open||this._scheduleType!=="sensor_based"||(this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),1500))}_probeEntityPickers(){if(this._pickerProbeTimer=void 0,this._entityPickerFallback||!this._open)return;let e=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),t=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!t){this._pickerProbeStrikes=0;return}let i=(p,_,m=0)=>{if(!(!p||m>10)){(p.tagName?.toLowerCase()??"")==="ha-entity-picker"&&_.push(p);for(let f of[p.shadowRoot,p])if(f)for(let x of Array.from(f.children??[]))i(x,_,m+1)}},a=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],o=[];for(let p of a)i(p,o);let d=o.length===0||o.some(p=>p.offsetHeight===0);if(e.offsetHeight===0||d){if(this._pickerProbeStrikes+=1,this._pickerProbeStrikes>=2){this._entityPickerFallback=!0;return}this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),700)}else this._pickerProbeStrikes=0}_schedulePreviewRefresh(){this._previewTimer&&clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._fetchSchedulePreview()},300)}async _fetchSchedulePreview(){let e=this._open?this._previewScheduleDict():null;if(!e){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let t=++this._previewSeq;try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(t!==this._previewSeq)return;this._schedulePreview=i.occurrences||[],this._schedulePreviewEnded=!!i.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return h;let e=this._lang,t=this.scheduleTimeEnabled&&this._scheduleTimeOn&&this._scheduleTime?` ${this._scheduleTime}`:"",i=this._schedulePreview.map((o,d)=>{let p=new Date(`${o}T12:00:00`).getDay();return`${Ke(p===0?6:p-1,e,"short")} ${O(o,e)}${d===0?t:""}`}).join(" \xB7 "),a=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?l`
${n("schedule_preview_ontime",e)}
`:h;return l` + `}_toggleWeekday(e){this._weekdays=this._weekdays.includes(e)?this._weekdays.filter(t=>t!==e):[...this._weekdays,e]}_previewScheduleDict(){if(this._scheduleType==="one_time")return this._dueDate?{kind:"one_time",due_date:this._dueDate}:null;if(this._scheduleType==="calendar"&&!this._calendarEntity.trim())return null;if(oi.includes(this._scheduleType))return{...this._buildSchedule(),...this._recurrenceExtras()};let e=parseInt(this._intervalDays,10);return this._scheduleType==="manual"||!e||e<=0?null:{kind:"interval",every:e,unit:this._intervalUnit,anchor:this._intervalAnchor,...this._recurrenceExtras()}}updated(e){super.updated?.(e),this._scheduleEntityPickerProbe();for(let t of e.keys())if(g._PREVIEW_RELEVANT.has(String(t))){this._schedulePreviewRefresh();return}}_scheduleEntityPickerProbe(){this._entityPickerFallback||this._pickerProbeTimer!==void 0||!this._open||this._scheduleType!=="sensor_based"||(this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),1500))}_probeEntityPickers(){if(this._pickerProbeTimer=void 0,this._entityPickerFallback||!this._open)return;let e=this.shadowRoot?.querySelector("ha-form.entity-picker-form"),t=(this.shadowRoot?.querySelector(".content")?.offsetHeight??0)>0;if(!e||!t){this._pickerProbeStrikes=0;return}let i=(p,_,m=0)=>{if(!(!p||m>10)){(p.tagName?.toLowerCase()??"")==="ha-entity-picker"&&_.push(p);for(let f of[p.shadowRoot,p])if(f)for(let x of Array.from(f.children??[]))i(x,_,m+1)}},a=[...this.shadowRoot?.querySelectorAll("ha-form.entity-picker-form")??[]],o=[];for(let p of a)i(p,o);let d=o.length===0||o.some(p=>p.offsetHeight===0);if(e.offsetHeight===0||d){if(this._pickerProbeStrikes+=1,this._pickerProbeStrikes>=2){this._entityPickerFallback=!0;return}this._pickerProbeTimer=setTimeout(()=>this._probeEntityPickers(),700)}else this._pickerProbeStrikes=0}_schedulePreviewRefresh(){this._previewTimer&&clearTimeout(this._previewTimer),this._previewTimer=setTimeout(()=>{this._fetchSchedulePreview()},300)}async _fetchSchedulePreview(){let e=this._open?this._previewScheduleDict():null;if(!e){this._schedulePreview=[],this._schedulePreviewEnded=!1;return}let t=++this._previewSeq;try{let i=await this.hass.connection.sendMessagePromise({type:"maintenance_supporter/schedule/preview",schedule:e,...this._lastPerformed?{last_performed:this._lastPerformed}:{}});if(t!==this._previewSeq)return;this._schedulePreview=i.occurrences||[],this._schedulePreviewEnded=!!i.series_ended}catch{}}_renderSchedulePreview(){if(this._schedulePreview.length===0)return h;let e=this._lang,t=this.scheduleTimeEnabled&&this._scheduleTimeOn&&this._scheduleTime?` ${this._scheduleTime}`:"",i=this._schedulePreview.map((o,d)=>{let p=new Date(`${o}T12:00:00`).getDay();return`${Ke(p===0?6:p-1,e,"short")} ${O(o,e)}${d===0?t:""}`}).join(" \xB7 "),a=this._scheduleType==="time_based"&&this._intervalAnchor==="completion"?l`
${n("schedule_preview_ontime",e)}
`:h;return l`
${n("schedule_preview_title",e)}: ${i}${this._schedulePreviewEnded?l` ${n("schedule_preview_ends",e)}`:h} ${a}
- `}_buildSchedule(){let e=i=>{let a=parseInt(this._calOffset,10)||0;return a&&(i.offset=Math.max(-kt,Math.min(a,kt))),i};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((i,a)=>i-a)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});if(this._scheduleType==="calendar")return e({kind:"calendar",entity_id:this._calendarEntity.trim()});let t={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(t.business=!0),e(t)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((t,i)=>t-i)),this._endsMode==="count"){let t=parseInt(this._endsCount,10);t>=1&&(e.ends={count:t})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(t=>t!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||ni.includes(this._scheduleType)))return h;let i=wo(e);return l` + `}_buildSchedule(){let e=i=>{let a=parseInt(this._calOffset,10)||0;return a&&(i.offset=Math.max(-kt,Math.min(a,kt))),i};if(this._scheduleType==="weekdays")return e({kind:"weekdays",weekdays:[...this._weekdays].sort((i,a)=>i-a)});if(this._scheduleType==="nth_weekday")return e({kind:"nth_weekday",nth:parseInt(this._nth,10),weekday:parseInt(this._nthWeekday,10)});if(this._scheduleType==="calendar")return e({kind:"calendar",entity_id:this._calendarEntity.trim()});let t={kind:"day_of_month",day:this._domLastDay?-1:parseInt(this._domDay,10)||1};return this._domBusiness&&(t.business=!0),e(t)}_recurrenceExtras(){let e={};if(this._seasonMonths.length&&(e.season_months=[...this._seasonMonths].sort((t,i)=>t-i)),this._endsMode==="count"){let t=parseInt(this._endsCount,10);t>=1&&(e.ends={count:t})}else this._endsMode==="until"&&this._endsUntil&&(e.ends={until:this._endsUntil});return e}_toggleSeasonMonth(e){this._seasonMonths=this._seasonMonths.includes(e)?this._seasonMonths.filter(t=>t!==e):[...this._seasonMonths,e]}_renderRecurrenceExtras(){let e=this._lang;if(!(this._scheduleType==="time_based"||oi.includes(this._scheduleType)))return h;let i=So(e);return l`
${n("season_window_hint",e)}
@@ -2217,7 +2256,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._endsUntil} @value-changed=${a=>this._endsUntil=a.detail.value} >`:h} - `}_renderCalendarFields(){let e=this._lang,t=xo(e);if(this._scheduleType==="weekdays")return l` + `}_renderCalendarFields(){let e=this._lang,t=Eo(e);if(this._scheduleType==="weekdays")return l`
${t.map((i,a)=>l` @@ -2360,7 +2399,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" this._triggerTargetChanges=t.target.value} > @@ -2369,7 +2408,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" this._triggerForMinutes=t.target.value} > @@ -2432,7 +2471,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._type} @change=${i=>this._type=i.target.value} > - ${_o.map(i=>l``)} + ${vo.map(i=>l``)}
${this._type==="reading"?l` @@ -2467,7 +2506,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._priority} @change=${i=>this._priority=i.target.value} > - ${mo.map(i=>l``)} + ${yo.map(i=>l``)}
@@ -2505,7 +2544,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" .value=${this._scheduleType} @change=${i=>this._scheduleType=i.target.value} > - ${go.map(i=>l``)} + ${bo.map(i=>l``)}
${this._scheduleType==="time_based"?l` @@ -2538,7 +2577,7 @@ Test pressure`,checklist_help:"One step per line. Max 100 items.",err_too_long:" @value-changed=${i=>this._dueDate=i.detail.value} >
`:h} - ${this.scheduleTimeEnabled&&nn.includes(this._scheduleType)?l` + ${this.scheduleTimeEnabled&&ln.includes(this._scheduleType)?l`