| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276 |
- import asyncio
- import logging
- from datetime import date
- from ._airbnb import _AirbnbClient
- from ._booking import _BookingClient
- from ._protocols import ChatClient, ServiceClient
- from .types import DayInfo, ServiceAuthError
- _log = logging.getLogger(__name__)
- _instance: 'ServiceAPI | None' = None
- class ServiceAPI:
- """Unified async client for all booking platform services.
- Credentials are read from <service>.env files in the data directory
- (~/.local/room_cal/ or ROOM_CAL_DATA_HOME).
- All date arguments are native datetime.date objects.
- Pass a custom `clients` dict to substitute stubs for testing.
- """
- _CLIENT_CLASSES: dict[str, type] = {
- 'airbnb': _AirbnbClient,
- 'booking': _BookingClient,
- }
- @classmethod
- def get(cls) -> 'ServiceAPI':
- """Return the process-wide singleton, creating it on first call."""
- global _instance
- if _instance is None:
- _instance = cls()
- return _instance
- @classmethod
- def set(cls, instance: 'ServiceAPI') -> None:
- """Replace the singleton — use in tests to install a stub."""
- global _instance
- _instance = instance
- def __init__(self, clients: dict[str, ServiceClient] | None = None) -> None:
- if clients is not None:
- self._clients: dict[str, ServiceClient] = clients
- self._disabled: dict[str, str] = {}
- return
- self._clients = {}
- self._disabled: dict[str, str] = {}
- for key, cls in self._CLIENT_CLASSES.items():
- try:
- self._clients[key] = cls.from_env()
- except Exception as e:
- _log.warning('service %s failed to load: %s', key, e)
- self._disabled[key] = str(e)
- def keys(self) -> list[str]:
- """Return the keys of all successfully loaded services."""
- return list(self._clients.keys())
- def service_name(self, key: str) -> str:
- """Return the human-readable display name for a service key."""
- cls = self._CLIENT_CLASSES.get(key)
- return getattr(cls, 'service_name', key.capitalize()) if cls else key.capitalize()
- async def refresh_credentials(self, key: str) -> None:
- """Trigger credential refresh for the named service. Raises ServiceAuthError on failure."""
- cls = self._CLIENT_CLASSES.get(key)
- if cls is None or not hasattr(cls, 'refresh_credentials'):
- from .types import ServiceAuthError
- raise ServiceAuthError(f'No automatic refresh handler for service: {key}')
- loop = asyncio.get_running_loop()
- await loop.run_in_executor(None, cls.refresh_credentials)
- def client(self, key: str) -> ServiceClient:
- """Return the platform client for `key`, typed as ServiceClient."""
- try:
- return self._clients[key]
- except KeyError:
- raise KeyError(f'unknown service: {key!r}') from None
- def chat_client(self, key: str) -> ChatClient:
- """Return the platform client for `key` if it supports chat; raise TypeError otherwise."""
- c = self.client(key)
- if not isinstance(c, ChatClient):
- raise TypeError(f'{key!r} does not support chat')
- return c # type: ignore[return-value]
- async def _gather(self, coros: dict[str, object]) -> dict[str, object]:
- """Gather per-service results; isolate ServiceAuthError so one failed service can't kill others."""
- keys = list(coros.keys())
- raw = await asyncio.gather(*coros.values(), return_exceptions=True) # type: ignore[arg-type]
- out: dict[str, object] = {}
- for key, result in zip(keys, raw):
- if isinstance(result, BaseException):
- _log.error('service %s error (skipping): %s', key, result, exc_info=result)
- out[key] = None
- else:
- out[key] = result
- return out
- async def get_prices_range(self, start_date: date, end_date: date) -> dict[str, dict[str, int | None]]:
- """Return {date_str: {service_key: price}} for all dates in the range.
- Uses each client's bulk get_calendar call so the whole range is fetched
- in one pass (month-by-month internally). Price is None for booked or
- unavailable dates where the platform does not report a price.
- """
- ds_from = start_date.isoformat()
- ds_to = end_date.isoformat()
- cals = await self._gather({
- key: client.get_calendar(ds_from, ds_to) for key, client in self._clients.items()
- })
- all_dates: set[str] = set()
- for cal in cals.values():
- if cal is not None:
- all_dates.update(d for d in cal if ds_from <= d <= ds_to) # type: ignore[union-attr]
- result: dict[str, dict[str, int | None]] = {}
- for d in sorted(all_dates):
- result[d] = {
- key: cal[d].price if (cal is not None and d in cal) else None # type: ignore[index]
- for key, cal in cals.items()
- }
- return result
- async def get_booked_nets(self, start_date: date, end_date: date) -> dict[str, dict[str, int | None]]:
- """Return {date_str: {service_key: net}} for booked dates where per-night net is available.
- Only services that implement get_booked_nets contribute data; others are absent from the result.
- Dispatch is via hasattr so new clients opt in by implementing the method.
- """
- ds_from = start_date.isoformat()
- ds_to = end_date.isoformat()
- per_service = await self._gather({
- key: client.get_booked_nets(ds_from, ds_to) # type: ignore[attr-defined]
- for key, client in self._clients.items()
- if hasattr(client, 'get_booked_nets')
- })
- result: dict[str, dict[str, int | None]] = {}
- for key, nets in per_service.items():
- if nets is None:
- continue
- for d, net in nets.items(): # type: ignore[union-attr]
- result.setdefault(d, {})[key] = net
- return result
- async def get_prices(self, d: date) -> dict[str, int | None]:
- """Return {service_key: price} for all services on a single date."""
- ds = d.isoformat()
- cals = await self._gather({
- key: client.get_calendar(ds, ds) for key, client in self._clients.items()
- })
- return {
- key: cal[ds].price if (cal is not None and ds in cal) else None # type: ignore[index]
- for key, cal in cals.items()
- }
- async def set_prices(self, d: date, prices: dict[str, int]) -> None:
- """Set price on each specified service; skips booked dates."""
- ds = d.isoformat()
- _fallback = DayInfo(date=ds, price=None, available=True, booked=False, rooms_to_sell=None)
- cals = await self._gather({
- key: self._clients[key].get_calendar(ds, ds) for key in prices if key in self._clients
- })
- to_set = {
- key: price
- for (key, price) in prices.items()
- if cals.get(key) is not None and not cals[key].get(ds, _fallback).booked # type: ignore[union-attr]
- }
- if to_set:
- await self._gather({
- key: self._clients[key].set_price(ds, price) for key, price in to_set.items()
- })
- async def get_available(self, d: date) -> bool:
- """Return True only when all active (non-failed) services have the date open."""
- ds = d.isoformat()
- _closed = DayInfo(date=ds, price=None, available=False, booked=False, rooms_to_sell=None)
- cals = await self._gather({
- key: client.get_calendar(ds, ds) for key, client in self._clients.items()
- })
- return all(
- cal.get(ds, _closed).available # type: ignore[union-attr]
- for cal in cals.values() if cal is not None
- )
- async def set_available(self, d: date, available: bool) -> None:
- """Open or block a date on all services; skips booked dates."""
- ds = d.isoformat()
- _fallback = DayInfo(date=ds, price=None, available=True, booked=False, rooms_to_sell=None)
- cals = await self._gather({
- key: client.get_calendar(ds, ds) for key, client in self._clients.items()
- })
- to_set = {
- key: self._clients[key]
- for key, cal in cals.items()
- if cal is not None and not cal.get(ds, _fallback).booked # type: ignore[union-attr]
- }
- if to_set:
- await self._gather({
- key: client.set_availability(ds, available) for key, client in to_set.items()
- })
- async def get_closed_by_date(self, start_date: date, end_date: date) -> dict[str, list[str]]:
- """Return {date_str: [service_keys]} for dates blocked (not available, not booked) on at least one service."""
- ds_from = start_date.isoformat()
- ds_to = end_date.isoformat()
- cals = await self._gather({
- key: client.get_calendar(ds_from, ds_to) for key, client in self._clients.items()
- })
- all_dates: set[str] = set()
- for cal in cals.values():
- if cal is not None:
- all_dates.update(cal.keys()) # type: ignore[union-attr]
- result: dict[str, list[str]] = {}
- for d in sorted(all_dates):
- if not (ds_from <= d <= ds_to):
- continue
- closed = [
- key for key, cal in cals.items()
- if cal is not None and (day := cal.get(d)) and not day.available and not day.booked # type: ignore[union-attr]
- ]
- if closed:
- result[d] = closed
- return result
- async def get_reservations(self, start_date: date, end_date: date) -> list[dict]:
- """Return reservations from all services, sorted by start_date.
- Each entry: {service, start_date, end_date, id, guest_name}
- """
- ds_from = start_date.isoformat()
- ds_to = end_date.isoformat()
- all_res = await self._gather({
- key: client.get_reservations(ds_from, ds_to) for key, client in self._clients.items()
- })
- result: list[dict] = []
- for key, reservations in all_res.items():
- if reservations is None:
- continue
- for r in reservations: # type: ignore[union-attr]
- result.append({
- 'service': key,
- 'start_date': date.fromisoformat(r.check_in),
- 'end_date': date.fromisoformat(r.check_out),
- 'id': r.reservation_id,
- 'guest_name': r.guest_name,
- 'service_data': r.service_data or {},
- 'chat_id': r.chat_id,
- 'door_code': r.door_code,
- })
- result.sort(key=lambda x: x['start_date'])
- return result
- async def diff_remote_sync(self, start_date: date, end_date: date) -> dict[str, list[dict]]:
- """Return per-service integrity issues without making any changes."""
- ds_from, ds_to = start_date.isoformat(), end_date.isoformat()
- out: dict[str, list[dict]] = {}
- for key, client in self._clients.items():
- if hasattr(client, 'diff_remote_sync'):
- result = await client.diff_remote_sync(ds_from, ds_to)
- if result:
- out[key] = result
- return out
- async def remote_sync(self, start_date: date, end_date: date) -> dict[str, list[dict]]:
- """Fix per-service integrity issues. Returns per-service list of corrections made."""
- ds_from, ds_to = start_date.isoformat(), end_date.isoformat()
- out: dict[str, list[dict]] = {}
- for key, client in self._clients.items():
- if hasattr(client, 'remote_sync'):
- result = await client.remote_sync(ds_from, ds_to)
- if result:
- out[key] = result
- return out
|