generated from ludeeus/integration_blueprint
-
Notifications
You must be signed in to change notification settings - Fork 107
/
media_source.py
1346 lines (1189 loc) · 47.9 KB
/
media_source.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Frigate Media Source."""
from __future__ import annotations
import datetime as dt
import enum
import logging
from typing import Any, cast
import attr
from dateutil.relativedelta import relativedelta
import pytz
from homeassistant.components.media_player.const import (
MEDIA_CLASS_DIRECTORY,
MEDIA_CLASS_IMAGE,
MEDIA_CLASS_MOVIE,
MEDIA_CLASS_VIDEO,
MEDIA_TYPE_IMAGE,
MEDIA_TYPE_VIDEO,
)
from homeassistant.components.media_source.error import MediaSourceError, Unresolvable
from homeassistant.components.media_source.models import (
BrowseMediaSource,
MediaSource,
MediaSourceItem,
PlayMedia,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import system_info
from homeassistant.helpers.template import DATE_STR_FORMAT
from homeassistant.util.dt import DEFAULT_TIME_ZONE
from . import get_friendly_name
from .api import FrigateApiClient, FrigateApiClientError
from .const import CONF_MEDIA_BROWSER_ENABLE, DOMAIN, NAME
from .views import (
get_client_for_frigate_instance_id,
get_config_entry_for_frigate_instance_id,
get_default_config_entry,
get_frigate_instance_id_for_config_entry,
)
_LOGGER = logging.getLogger(__name__)
ITEM_LIMIT = 50
SECONDS_IN_DAY = 60 * 60 * 24
SECONDS_IN_MONTH = SECONDS_IN_DAY * 31
async def async_get_media_source(hass: HomeAssistant) -> MediaSource:
"""Set up Frigate media source."""
return FrigateMediaSource(hass)
class FrigateBrowseMediaMetadata:
"""Metadata for browsable Frigate media files."""
event: dict[str, Any] | None
def __init__(self, event: dict[str, Any]):
"""Initialize a FrigateBrowseMediaMetadata object."""
self.event = event
def as_dict(self) -> dict:
"""Convert the object to a dictionary."""
return {"event": self.event}
class FrigateBrowseMediaSource(BrowseMediaSource): # type: ignore[misc]
"""Represent a browsable Frigate media file."""
children: list[FrigateBrowseMediaSource] | None
frigate: FrigateBrowseMediaMetadata
def as_dict(self, *args: Any, **kwargs: Any) -> dict:
"""Convert the object to a dictionary."""
res: dict = super().as_dict(*args, **kwargs)
res["frigate"] = self.frigate.as_dict()
return res
def __init__(
self, frigate: FrigateBrowseMediaMetadata, *args: Any, **kwargs: Any
) -> None:
"""Initialize media source browse media."""
super().__init__(*args, **kwargs)
self.frigate = frigate
@attr.s(frozen=True)
class Identifier:
"""Base class for Identifiers."""
frigate_instance_id: str = attr.ib(
validator=[attr.validators.instance_of(str)],
)
@classmethod
def _get_index(cls, data: list, index: int, default: Any = None) -> Any:
try:
return data[index] if data[index] != "" else default
except IndexError:
return default
@classmethod
def _empty_if_none(cls, data: Any) -> str:
"""Return an empty string if data is None."""
return str(data) if data is not None else ""
@classmethod
def from_str(
cls,
data: str,
default_frigate_instance_id: str | None = None,
) -> EventSearchIdentifier | EventIdentifier | RecordingIdentifier | None:
"""Generate a EventSearchIdentifier from a string."""
return (
EventSearchIdentifier.from_str(data, default_frigate_instance_id)
or EventIdentifier.from_str(data, default_frigate_instance_id)
or RecordingIdentifier.from_str(data, default_frigate_instance_id)
)
@classmethod
def get_identifier_type(cls) -> str:
"""Get the identifier type."""
raise NotImplementedError
def get_integration_proxy_path(self, timezone: str) -> str:
"""Get the proxy (Home Assistant view) path for this identifier."""
raise NotImplementedError
@classmethod
def _add_frigate_instance_id_to_parts_if_absent(
cls, parts: list[str], default_frigate_instance_id: str | None = None
) -> list[str]:
"""Add a frigate instance id if it's not specified."""
if (
cls._get_index(parts, 0) == cls.get_identifier_type()
and default_frigate_instance_id is not None
):
parts.insert(0, default_frigate_instance_id)
return parts
@property
def mime_type(self) -> str:
"""Get mime type for this identifier."""
raise NotImplementedError
@property
def media_type(self) -> str:
"""Get media type for this identifier."""
raise NotImplementedError
@property
def media_class(self) -> str:
"""Get media class for this identifier."""
raise NotImplementedError
class FrigateMediaType(enum.Enum):
"""Type of media this identifier represents."""
CLIPS = "clips"
SNAPSHOTS = "snapshots"
@property
def mime_type(self) -> str:
"""Get mime type for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return "application/x-mpegURL"
return "image/jpg"
@property
def media_type(self) -> str:
"""Get media type for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return str(MEDIA_TYPE_VIDEO)
return str(MEDIA_TYPE_IMAGE)
@property
def media_class(self) -> str:
"""Get media class for this frigate media type."""
if self == FrigateMediaType.CLIPS:
return str(MEDIA_CLASS_VIDEO)
return str(MEDIA_CLASS_IMAGE)
@property
def extension(self) -> str:
"""Get filename extension."""
if self == FrigateMediaType.CLIPS:
return "m3u8"
return "jpg"
@attr.s(frozen=True)
class EventIdentifier(Identifier):
"""Event Identifier (clip or snapshot)."""
frigate_media_type: FrigateMediaType = attr.ib(
validator=[attr.validators.in_(FrigateMediaType)]
)
id: str = attr.ib(
validator=[attr.validators.instance_of(str)],
)
camera: str = attr.ib(
validator=[attr.validators.instance_of(str)],
)
def __str__(self) -> str:
"""Convert to a string."""
return "/".join(
(
self.frigate_instance_id,
self.get_identifier_type(),
self.frigate_media_type.value,
self.camera,
self.id,
)
)
@classmethod
def from_str(
cls, data: str, default_frigate_instance_id: str | None = None
) -> EventIdentifier | None:
"""Generate a EventIdentifier from a string."""
parts = cls._add_frigate_instance_id_to_parts_if_absent(
data.split("/"), default_frigate_instance_id
)
if len(parts) != 5 or parts[1] != cls.get_identifier_type():
return None
try:
return cls(
frigate_instance_id=parts[0],
frigate_media_type=FrigateMediaType(parts[2]),
camera=parts[3],
id=parts[4],
)
except ValueError:
return None
@classmethod
def get_identifier_type(cls) -> str:
"""Get the identifier type."""
return "event"
def get_integration_proxy_path(self, timezone: str) -> str:
"""Get the equivalent Frigate server path."""
if self.frigate_media_type == FrigateMediaType.CLIPS:
return f"vod/event/{self.id}/index.{self.frigate_media_type.extension}"
return f"snapshot/{self.id}"
@property
def mime_type(self) -> str:
"""Get mime type for this identifier."""
return self.frigate_media_type.mime_type
def _to_int_or_none(data: str) -> int | None:
"""Convert to an integer or None."""
return int(data) if data is not None else None
@attr.s(frozen=True)
class EventSearchIdentifier(Identifier):
"""Event Search Identifier."""
frigate_media_type: FrigateMediaType = attr.ib(
validator=[attr.validators.in_(FrigateMediaType)]
)
name: str = attr.ib(
default="",
validator=[attr.validators.instance_of(str)],
)
after: int | None = attr.ib(
default=None,
converter=_to_int_or_none,
validator=[attr.validators.instance_of((int, type(None)))],
)
before: int | None = attr.ib(
default=None,
converter=_to_int_or_none,
validator=[attr.validators.instance_of((int, type(None)))],
)
camera: str | None = attr.ib(
default=None, validator=[attr.validators.instance_of((str, type(None)))]
)
label: str | None = attr.ib(
default=None, validator=[attr.validators.instance_of((str, type(None)))]
)
zone: str | None = attr.ib(
default=None, validator=[attr.validators.instance_of((str, type(None)))]
)
@classmethod
def from_str(
cls, data: str, default_frigate_instance_id: str | None = None
) -> EventSearchIdentifier | None:
"""Generate a EventSearchIdentifier from a string."""
parts = cls._add_frigate_instance_id_to_parts_if_absent(
data.split("/"), default_frigate_instance_id
)
if len(parts) < 3 or parts[1] != cls.get_identifier_type():
return None
try:
return cls(
frigate_instance_id=cls._get_index(parts, 0),
frigate_media_type=FrigateMediaType(cls._get_index(parts, 2)),
name=cls._get_index(parts, 3, ""),
after=cls._get_index(parts, 4),
before=cls._get_index(parts, 5),
camera=cls._get_index(parts, 6),
label=cls._get_index(parts, 7),
zone=cls._get_index(parts, 8),
)
except ValueError:
return None
def __str__(self) -> str:
"""Convert to a string."""
return "/".join(
[self.frigate_instance_id, self.get_identifier_type()]
+ [
self._empty_if_none(val)
for val in (
self.frigate_media_type.value,
self.name,
self.after,
self.before,
self.camera,
self.label,
self.zone,
)
]
)
def is_root(self) -> bool:
"""Determine if an identifier is an event root for a given server."""
return not any(
[self.name, self.after, self.before, self.camera, self.label, self.zone]
)
@classmethod
def get_identifier_type(cls) -> str:
"""Get the identifier type."""
return "event-search"
@property
def media_type(self) -> str:
"""Get mime type for this identifier."""
return self.frigate_media_type.media_type
@property
def media_class(self) -> str:
"""Get media class for this identifier."""
return self.frigate_media_type.media_class
def _validate_year_month_day(
inst: RecordingIdentifier, attribute: attr.Attribute, data: str | None
) -> None:
"""Validate input."""
if data:
try:
dt.datetime.strptime(data, "%Y-%m-%d")
except ValueError as exc:
raise ValueError(f"Invalid date in identifier: {data}") from exc
def _validate_hour(
inst: RecordingIdentifier, attribute: attr.Attribute, value: int | None
) -> None:
"""Determine if a value is a valid hour."""
if value is not None and (int(value) < 0 or int(value) > 23):
raise ValueError(f"Invalid hour in identifier: {value}")
@attr.s(frozen=True)
class RecordingIdentifier(Identifier):
"""Recording Identifier."""
camera: str | None = attr.ib(
default=None, validator=[attr.validators.instance_of((str, type(None)))]
)
year_month_day: str | None = attr.ib(
default=None,
validator=[
attr.validators.instance_of((str, type(None))),
_validate_year_month_day,
],
)
hour: int | None = attr.ib(
default=None,
converter=_to_int_or_none,
validator=[
attr.validators.instance_of((int, type(None))),
_validate_hour,
],
)
@classmethod
def from_str(
cls, data: str, default_frigate_instance_id: str | None = None
) -> RecordingIdentifier | None:
"""Generate a RecordingIdentifier from a string."""
parts = cls._add_frigate_instance_id_to_parts_if_absent(
data.split("/"), default_frigate_instance_id
)
if len(parts) < 2 or parts[1] != cls.get_identifier_type():
return None
try:
return cls(
frigate_instance_id=parts[0],
camera=cls._get_index(parts, 2),
year_month_day=cls._get_index(parts, 3),
hour=cls._get_index(parts, 4),
)
except ValueError:
return None
def __str__(self) -> str:
"""Convert to a string."""
return "/".join(
[self.frigate_instance_id, self.get_identifier_type()]
+ [
self._empty_if_none(val)
for val in (
self.camera,
f"{self.year_month_day}"
if self.year_month_day is not None
else None,
f"{self.hour:02}" if self.hour is not None else None,
)
]
)
@classmethod
def get_identifier_type(cls) -> str:
"""Get the identifier type."""
return "recordings"
def get_integration_proxy_path(self, timezone: str) -> str:
"""Get the integration path that will proxy this identifier."""
if (
self.camera is not None
and self.year_month_day is not None
and self.hour is not None
):
year, month, day = self.year_month_day.split("-")
# Take the selected time in users local time and find the offset to
# UTC, convert to UTC then request the vod for that time.
start_date: dt.datetime = dt.datetime(
int(year),
int(month),
int(day),
int(self.hour),
tzinfo=dt.timezone.utc,
) - (dt.datetime.now(pytz.timezone(timezone)).utcoffset() or dt.timedelta())
parts = [
"vod",
f"{start_date.year}-{start_date.month:02}",
f"{start_date.day:02}",
f"{start_date.hour:02}",
self.camera,
"utc",
"index.m3u8",
]
return "/".join(parts)
raise MediaSourceError(
"Can not get proxy-path without year_month_day and hour."
)
@property
def mime_type(self) -> str:
"""Get mime type for this identifier."""
return "application/x-mpegURL"
@property
def media_class(self) -> str:
"""Get media class for this identifier."""
return str(MEDIA_CLASS_MOVIE)
@property
def media_type(self) -> str:
"""Get media type for this identifier."""
return str(MEDIA_TYPE_VIDEO)
@attr.s(frozen=True)
class EventSummaryData:
"""Summary data from Frigate events."""
data: list[dict[str, Any]] = attr.ib()
cameras: list[str] = attr.ib()
labels: list[str] = attr.ib()
zones: list[str] = attr.ib()
@classmethod
def from_raw_data(cls, summary_data: list[dict[str, Any]]) -> EventSummaryData:
"""Generate an EventSummaryData object from raw data."""
cameras = list({d["camera"] for d in summary_data})
labels = list({d["label"] for d in summary_data})
zones = list({zone for d in summary_data for zone in d["zones"]})
return cls(summary_data, cameras, labels, zones)
class FrigateMediaSource(MediaSource): # type: ignore[misc]
"""Provide Frigate camera recordings as media sources."""
name: str = "Frigate"
def __init__(self, hass: HomeAssistant):
"""Initialize Frigate source."""
super().__init__(DOMAIN)
self.hass = hass
def _is_allowed_as_media_source(self, instance_id: str) -> bool:
"""Whether a given frigate instance is allowed as a media source."""
config_entry: ConfigEntry = get_config_entry_for_frigate_instance_id(
self.hass, instance_id
)
return (
config_entry.options.get(CONF_MEDIA_BROWSER_ENABLE, True) is True
if config_entry
else False
)
def _get_client(self, identifier: Identifier) -> FrigateApiClient:
"""Get client for a given identifier."""
client = get_client_for_frigate_instance_id(
self.hass, identifier.frigate_instance_id
)
if client:
return client
raise MediaSourceError(
"Could not find client for frigate instance "
f"id: {identifier.frigate_instance_id}"
)
def _get_default_frigate_instance_id(self) -> str | None:
"""Get the default frigate_instance_id if any."""
default_config_entry = get_default_config_entry(self.hass)
if default_config_entry:
return get_frigate_instance_id_for_config_entry(
self.hass, default_config_entry
)
return None
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
identifier = Identifier.from_str(
item.identifier,
default_frigate_instance_id=self._get_default_frigate_instance_id(),
)
if identifier and self._is_allowed_as_media_source(
identifier.frigate_instance_id
):
info = await system_info.async_get_system_info(self.hass)
server_path = identifier.get_integration_proxy_path(
info.get("timezone", "utc")
)
return PlayMedia(
f"/api/frigate/{identifier.frigate_instance_id}/{server_path}",
identifier.mime_type,
)
raise Unresolvable(f"Unknown or disallowed identifier: {item.identifier}")
async def async_browse_media(
self,
item: MediaSourceItem,
) -> BrowseMediaSource:
"""Browse media."""
if item.identifier is None:
base = BrowseMediaSource(
domain=DOMAIN,
identifier="",
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=MEDIA_CLASS_VIDEO,
media_content_type=MEDIA_TYPE_VIDEO,
title=NAME,
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
)
for config_entry in self.hass.config_entries.async_entries(DOMAIN):
frigate_instance_id = get_frigate_instance_id_for_config_entry(
self.hass, config_entry
)
if frigate_instance_id and self._is_allowed_as_media_source(
frigate_instance_id
):
clips_identifier = EventSearchIdentifier(
frigate_instance_id, FrigateMediaType.CLIPS
)
recording_identifier = RecordingIdentifier(frigate_instance_id)
snapshots_identifier = EventSearchIdentifier(
frigate_instance_id, FrigateMediaType.SNAPSHOTS
)
# Use the media class of the children to help distinguish
# the icons in the frontend.
base.children.extend(
[
BrowseMediaSource(
domain=DOMAIN,
identifier=clips_identifier,
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=clips_identifier.media_class,
media_content_type=clips_identifier.media_type,
title=f"Clips [{config_entry.title}]",
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
),
BrowseMediaSource(
domain=DOMAIN,
identifier=recording_identifier,
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=recording_identifier.media_class,
media_content_type=recording_identifier.media_type,
title=f"Recordings [{config_entry.title}]",
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
),
BrowseMediaSource(
domain=DOMAIN,
identifier=snapshots_identifier,
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=snapshots_identifier.media_class,
media_content_type=snapshots_identifier.media_type,
title=f"Snapshots [{config_entry.title}]",
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
),
],
)
return base
identifier = Identifier.from_str(
item.identifier,
default_frigate_instance_id=self._get_default_frigate_instance_id(),
)
if identifier is not None and not self._is_allowed_as_media_source(
identifier.frigate_instance_id
):
raise MediaSourceError(
f"Forbidden media source identifier: {item.identifier}"
)
if isinstance(identifier, EventSearchIdentifier):
if identifier.frigate_media_type == FrigateMediaType.CLIPS:
media_kwargs = {"has_clip": True}
else:
media_kwargs = {"has_snapshot": True}
try:
events = await self._get_client(identifier).async_get_events(
after=identifier.after,
before=identifier.before,
cameras=[identifier.camera] if identifier.camera else None,
labels=[identifier.label] if identifier.label else None,
sub_labels=None,
zones=[identifier.zone] if identifier.zone else None,
limit=10000 if identifier.name.endswith(".all") else ITEM_LIMIT,
**media_kwargs,
)
except FrigateApiClientError as exc:
raise MediaSourceError from exc
return self._browse_events(
await self._get_event_summary_data(identifier), identifier, events
)
if isinstance(identifier, RecordingIdentifier):
try:
if not identifier.camera:
config = await self._get_client(identifier).async_get_config()
return self._get_camera_recording_folders(identifier, config)
info = await system_info.async_get_system_info(self.hass)
recording_summary = cast(
list[dict[str, Any]],
await self._get_client(identifier).async_get_recordings_summary(
camera=identifier.camera, timezone=info.get("timezone", "utc")
),
)
if not identifier.year_month_day:
return self._get_recording_days(identifier, recording_summary)
return self._get_recording_hours(identifier, recording_summary)
except FrigateApiClientError as exc:
raise MediaSourceError from exc
raise MediaSourceError(f"Invalid media source identifier: {item.identifier}")
async def _get_event_summary_data(
self, identifier: EventSearchIdentifier
) -> EventSummaryData:
"""Get event summary data."""
try:
info = await system_info.async_get_system_info(self.hass)
if identifier.frigate_media_type == FrigateMediaType.CLIPS:
kwargs = {"has_clip": True}
else:
kwargs = {"has_snapshot": True}
summary_data = await self._get_client(identifier).async_get_event_summary(
timezone=info.get("timezone", "utc"), **kwargs
)
except FrigateApiClientError as exc:
raise MediaSourceError from exc
# Add timestamps to raw data.
for data in summary_data:
data["timestamp"] = int(
dt.datetime.strptime(data["day"], "%Y-%m-%d")
.astimezone(DEFAULT_TIME_ZONE)
.timestamp()
)
return EventSummaryData.from_raw_data(summary_data)
def _browse_events(
self,
summary_data: EventSummaryData,
identifier: EventSearchIdentifier,
events: list[dict[str, Any]],
) -> BrowseMediaSource:
"""Browse events."""
count = self._count_by(summary_data, identifier)
if identifier.is_root():
title = f"{identifier.frigate_media_type.value.capitalize()} ({count})"
else:
title = f"{' > '.join([s for s in get_friendly_name(identifier.name).split('.') if s != '']).title()} ({count})"
base = BrowseMediaSource(
domain=DOMAIN,
identifier=identifier,
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=identifier.media_class,
media_content_type=identifier.media_type,
title=title,
can_play=False,
can_expand=True,
thumbnail=None,
children=[],
)
event_items = self._build_event_response(identifier, events)
# if you are at the limit, but not at the root
if count > 0 and len(event_items) == ITEM_LIMIT and identifier.is_root():
# only render if > 10% is represented in view
if ITEM_LIMIT / float(count) > 0.1:
base.children.extend(event_items)
else:
base.children.extend(event_items)
drilldown_sources = []
drilldown_sources.extend(
self._build_date_sources(summary_data, identifier, len(base.children))
)
if not identifier.camera:
drilldown_sources.extend(
self._build_camera_sources(summary_data, identifier, len(base.children))
)
if not identifier.label:
drilldown_sources.extend(
self._build_label_sources(summary_data, identifier, len(base.children))
)
if not identifier.zone:
drilldown_sources.extend(
self._build_zone_sources(summary_data, identifier, len(base.children))
)
# only show the drill down options if there are more than 10 events
# and there is more than 1 drilldown or when you aren't showing any events
if len(events) > 10 and (len(drilldown_sources) > 1 or len(base.children) == 0):
base.children.extend(drilldown_sources)
# add an all source if there are no drilldowns available and you are at the item limit
if (
(len(base.children) == 0 or len(base.children) == len(event_items))
and not identifier.name.endswith(".all")
and len(event_items) == ITEM_LIMIT
):
base.children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=attr.evolve(identifier, name=f"{identifier.name}.all"),
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=MEDIA_CLASS_DIRECTORY,
media_content_type=identifier.media_type,
title=f"All ({count})",
can_play=False,
can_expand=True,
thumbnail=None,
)
)
return base
@classmethod
def _build_event_response(
cls, identifier: EventSearchIdentifier, events: list[dict[str, Any]]
) -> BrowseMediaSource:
children = []
for event in events:
start_time = event.get("start_time")
end_time = event.get("end_time")
if start_time is None:
continue
if end_time is None:
# Events that are in progress will not yet have an end_time, so
# the duration is shown as the current time minus the start
# time.
duration = int(
dt.datetime.now(DEFAULT_TIME_ZONE).timestamp() - start_time
)
else:
duration = int(end_time - start_time)
children.append(
FrigateBrowseMediaSource(
domain=DOMAIN,
identifier=EventIdentifier(
identifier.frigate_instance_id,
frigate_media_type=identifier.frigate_media_type,
camera=event["camera"],
id=event["id"],
),
media_class=identifier.media_class,
media_content_type=identifier.media_type,
title=f"{dt.datetime.fromtimestamp(event['start_time'], DEFAULT_TIME_ZONE).strftime(DATE_STR_FORMAT)} [{duration}s, {event['label'].capitalize()} {int((event['data'].get('top_score') or event['top_score'] or 0)*100)}%]",
can_play=identifier.media_type == MEDIA_TYPE_VIDEO,
can_expand=False,
thumbnail=f"/api/frigate/{identifier.frigate_instance_id}/thumbnail/{event['id']}",
frigate=FrigateBrowseMediaMetadata(event=event),
)
)
return children
def _build_camera_sources(
self,
summary_data: EventSummaryData,
identifier: EventSearchIdentifier,
shown_event_count: int,
) -> BrowseMediaSource:
sources = []
for camera in summary_data.cameras:
count = self._count_by(
summary_data,
attr.evolve(
identifier,
camera=camera,
),
)
if count in (0, shown_event_count):
continue
sources.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=attr.evolve(
identifier,
name=f"{identifier.name}.{camera}",
camera=camera,
),
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=MEDIA_CLASS_DIRECTORY,
media_content_type=identifier.media_type,
title=f"{get_friendly_name(camera)} ({count})",
can_play=False,
can_expand=True,
thumbnail=None,
)
)
return sources
def _build_label_sources(
self,
summary_data: EventSummaryData,
identifier: EventSearchIdentifier,
shown_event_count: int,
) -> BrowseMediaSource:
sources = []
for label in summary_data.labels:
count = self._count_by(
summary_data,
attr.evolve(
identifier,
label=label,
),
)
if count in (0, shown_event_count):
continue
sources.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=attr.evolve(
identifier,
name=f"{identifier.name}.{label}",
label=label,
),
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=MEDIA_CLASS_DIRECTORY,
media_content_type=identifier.media_type,
title=f"{get_friendly_name(label)} ({count})",
can_play=False,
can_expand=True,
thumbnail=None,
)
)
return sources
def _build_zone_sources(
self,
summary_data: EventSummaryData,
identifier: EventSearchIdentifier,
shown_event_count: int,
) -> BrowseMediaSource:
"""Build zone media sources."""
sources = []
for zone in summary_data.zones:
count = self._count_by(summary_data, attr.evolve(identifier, zone=zone))
if count in (0, shown_event_count):
continue
sources.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=attr.evolve(
identifier,
name=f"{identifier.name}.{zone}",
zone=zone,
),
media_class=MEDIA_CLASS_DIRECTORY,
children_media_class=MEDIA_CLASS_DIRECTORY,
media_content_type=identifier.media_type,
title=f"{get_friendly_name(zone)} ({count})",
can_play=False,
can_expand=True,
thumbnail=None,
)
)
return sources
def _build_date_sources(
self,
summary_data: EventSummaryData,
identifier: EventSearchIdentifier,
shown_event_count: int,
) -> BrowseMediaSource:
"""Build data media sources."""
sources = []
now = dt.datetime.now(DEFAULT_TIME_ZONE)
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
start_of_today = int(today.timestamp())
start_of_yesterday = start_of_today - SECONDS_IN_DAY
start_of_month = int(today.replace(day=1).timestamp())
start_of_last_month = int(
(today.replace(day=1) + relativedelta(months=-1)).timestamp()
)
start_of_year = int(today.replace(month=1, day=1).timestamp())
count_today = self._count_by(
summary_data, attr.evolve(identifier, after=start_of_today)
)
count_yesterday = self._count_by(
summary_data,
attr.evolve(
identifier,
after=start_of_yesterday,