Home Assistant Unofficial Reference 2024.12.1
coordinator.py
Go to the documentation of this file.
1 """Coordinator for fetching data from Google Photos API.
2 
3 This coordinator fetches the list of Google Photos albums that were created by
4 Home Assistant, which for large libraries may take some time. The list of album
5 ids and titles is cached and this provides a method to refresh urls since they
6 are short lived.
7 """
8 
9 import asyncio
10 import datetime
11 import logging
12 from typing import Final
13 
14 from google_photos_library_api.api import GooglePhotosLibraryApi
15 from google_photos_library_api.exceptions import GooglePhotosApiError
16 from google_photos_library_api.model import Album, NewAlbum
17 
18 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 UPDATE_INTERVAL: Final = datetime.timedelta(hours=24)
24 ALBUM_PAGE_SIZE = 50
25 
26 
28  """Coordinator for fetching Google Photos albums.
29 
30  The `data` object is a dict from Album ID to Album title.
31  """
32 
33  def __init__(self, hass: HomeAssistant, client: GooglePhotosLibraryApi) -> None:
34  """Initialize TaskUpdateCoordinator."""
35  super().__init__(
36  hass,
37  _LOGGER,
38  name="Google Photos",
39  update_interval=UPDATE_INTERVAL,
40  )
41  self.clientclient = client
42 
43  async def _async_update_data(self) -> dict[str, str]:
44  """Fetch albums from API endpoint."""
45  albums: dict[str, str] = {}
46  try:
47  async for album_result in await self.clientclient.list_albums(
48  page_size=ALBUM_PAGE_SIZE
49  ):
50  for album in album_result.albums:
51  albums[album.id] = album.title
52  except GooglePhotosApiError as err:
53  _LOGGER.debug("Error listing albums: %s", err)
54  raise UpdateFailed(f"Error listing albums: {err}") from err
55  return albums
56 
57  async def list_albums(self) -> list[Album]:
58  """Return Albums with refreshed URLs based on the cached list of album ids."""
59  return await asyncio.gather(
60  *(self.clientclient.get_album(album_id) for album_id in self.datadata)
61  )
62 
63  async def get_or_create_album(self, album: str) -> str:
64  """Return an existing album id or create a new one."""
65  for album_id, album_title in self.datadata.items():
66  if album_title == album:
67  return album_id
68  new_album = await self.clientclient.create_album(NewAlbum(title=album))
69  _LOGGER.debug("Created new album: %s", new_album)
70  self.datadata[new_album.id] = new_album.title
71  return new_album.id
None __init__(self, HomeAssistant hass, GooglePhotosLibraryApi client)
Definition: coordinator.py:33