_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import asyncio
  2. import json
  3. import os
  4. from dataclasses import dataclass, field
  5. from datetime import date, datetime, timedelta
  6. from importlib.resources import files
  7. from pathlib import Path
  8. from typing import Generic, TypeVar
  9. from zoneinfo import ZoneInfo
  10. _T = TypeVar('_T')
  11. @dataclass
  12. class FetchResult(Generic[_T]):
  13. """Return type for fetch_* actions: the synced data plus a changed flag."""
  14. data: _T
  15. changed: bool
  16. def __bool__(self) -> bool:
  17. return self.changed
  18. _source_registry: dict[str, 'EventSource'] = {}
  19. class EventSource:
  20. """Base class for event-producing objects. Registers the instance by domain name on init."""
  21. def __init__(self, name: str) -> None:
  22. self._name = name
  23. _source_registry[name] = self
  24. def _domain(self) -> str:
  25. return self._name
  26. def _ephemeral(self) -> bool:
  27. return False
  28. def is_ephemeral_domain(name: str | None) -> bool:
  29. """Return True if the named domain was registered as ephemeral (e.g. 'api')."""
  30. if not name:
  31. return False
  32. source = _source_registry.get(name)
  33. return source._ephemeral() if source else False
  34. def registered_domains() -> frozenset[str]:
  35. """Return the set of all registered source domain names."""
  36. return frozenset(_source_registry)
  37. def safe_json_loads(s: str | None) -> dict | None:
  38. if not s:
  39. return None
  40. try:
  41. return json.loads(s)
  42. except (ValueError, TypeError):
  43. return None
  44. def iter_dates(start: date, end: date):
  45. d = start
  46. while d <= end:
  47. yield d
  48. d += timedelta(days=1)
  49. def event_dates(event, start_date: date, end_date: date):
  50. """Yield dates covered by an EventRecord, clamped to [start_date, end_date]."""
  51. ev_start = event.start.date()
  52. ev_end = event.end.date()
  53. last_day = (ev_end - timedelta(days=1)) if event.all_day else ev_end
  54. for d in iter_dates(ev_start, last_day):
  55. if start_date <= d <= end_date:
  56. yield d
  57. async def drop_stale_events(
  58. events: list,
  59. covered: set[date],
  60. *,
  61. domain: str,
  62. id_: str,
  63. cal,
  64. ) -> None:
  65. """Delete events whose source domain/id match but whose date is no longer covered."""
  66. to_delete = []
  67. for ev in events:
  68. xd = safe_json_loads(ev.x_data)
  69. stored = xd.get('source', {}) if xd else {}
  70. if not isinstance(stored, dict):
  71. continue
  72. ev_date = ev.start.date()
  73. if ev_date not in covered and stored.get('domain') == domain and stored.get('id') == id_:
  74. to_delete.append(ev)
  75. if to_delete:
  76. await asyncio.gather(*[cal.delete(ev) for ev in to_delete])
  77. def filter_events(
  78. events: list,
  79. prefix: str,
  80. *,
  81. all_day: bool | None = None,
  82. require_x_data: bool = True,
  83. ) -> list:
  84. return [
  85. e for e in events
  86. if e.title.startswith(prefix)
  87. and (all_day is None or e.all_day == all_day)
  88. and (not require_x_data or e.x_data)
  89. ]
  90. def data_home() -> Path:
  91. override = os.environ.get('ROOM_CAL_DATA_HOME')
  92. return Path(override) if override else Path.home() / '.local' / 'room_cal'
  93. def _deep_merge(base: dict, override: dict) -> dict:
  94. result = dict(base)
  95. for k, v in override.items():
  96. if k in result and isinstance(result[k], dict) and isinstance(v, dict):
  97. result[k] = _deep_merge(result[k], v)
  98. else:
  99. result[k] = v
  100. return result
  101. # ── Config dataclasses ─────────────────────────────────────────────────────────
  102. @dataclass
  103. class ServiceFees:
  104. commission: float = 0.0
  105. client_fee: float = 0.0
  106. @classmethod
  107. def from_dict(cls, d: dict) -> 'ServiceFees':
  108. return cls(commission=d.get('commission', 0.0), client_fee=d.get('client_fee', 0.0))
  109. @dataclass
  110. class ServiceTaxes:
  111. wrong: float | None = None
  112. flat_tax: int = 0
  113. @classmethod
  114. def from_dict(cls, d: dict) -> 'ServiceTaxes':
  115. return cls(wrong=d.get('wrong'), flat_tax=d.get('flat_tax', 0))
  116. @dataclass
  117. class ServiceConfig:
  118. key: str
  119. name: str
  120. room_id: str = ''
  121. account_id: str = ''
  122. hotel_id: str = ''
  123. rate_id: str = ''
  124. fees: ServiceFees = field(default_factory=ServiceFees)
  125. taxes: ServiceTaxes = field(default_factory=ServiceTaxes)
  126. @classmethod
  127. def from_dict(cls, key: str, d: dict) -> 'ServiceConfig':
  128. return cls(
  129. key=key,
  130. name=d['name'],
  131. room_id=str(d.get('room_id', '')),
  132. account_id=str(d.get('account_id', '')),
  133. hotel_id=str(d.get('hotel_id', '')),
  134. rate_id=str(d.get('rate_id', '')),
  135. fees=ServiceFees.from_dict(d.get('fees', {})),
  136. taxes=ServiceTaxes.from_dict(d.get('taxes', {})),
  137. )
  138. @dataclass
  139. class GlobalTaxes:
  140. sales: float = 0.0
  141. @classmethod
  142. def from_dict(cls, d: dict) -> 'GlobalTaxes':
  143. return cls(sales=d.get('sales', 0.0))
  144. @dataclass
  145. class DefaultPrices:
  146. weekday: int = 62
  147. weekend: int = 72
  148. @classmethod
  149. def from_dict(cls, d: dict) -> 'DefaultPrices':
  150. return cls(weekday=d.get('weekday', 62), weekend=d.get('weekend', 72))
  151. @dataclass
  152. class PropertyConfig:
  153. timezone: str = 'America/Los_Angeles'
  154. checkin_hour: int = 14
  155. checkout_hour: int = 12
  156. @classmethod
  157. def from_dict(cls, d: dict) -> 'PropertyConfig':
  158. return cls(
  159. timezone=d.get('timezone', 'America/Los_Angeles'),
  160. checkin_hour=d.get('checkin_hour', 14),
  161. checkout_hour=d.get('checkout_hour', 12),
  162. )
  163. @dataclass
  164. class GlobalConfig:
  165. taxes: GlobalTaxes = field(default_factory=GlobalTaxes)
  166. property: PropertyConfig = field(default_factory=PropertyConfig)
  167. prices: DefaultPrices = field(default_factory=DefaultPrices)
  168. reservation_window_days: int = 90
  169. long_window_days: int = 400
  170. busy_calendar_name: str = 'Busy'
  171. @classmethod
  172. def from_dict(cls, d: dict) -> 'GlobalConfig':
  173. return cls(
  174. taxes=GlobalTaxes.from_dict(d.get('taxes', {})),
  175. property=PropertyConfig.from_dict(d.get('property', {})),
  176. prices=DefaultPrices.from_dict(d.get('prices', {})),
  177. reservation_window_days=d.get('reservation_window_days', 90),
  178. long_window_days=d.get('long_window_days', 400),
  179. busy_calendar_name=d.get('busy_calendar_name', 'Busy'),
  180. )
  181. @dataclass
  182. class PipelineConfig:
  183. type: str
  184. rules: list[str]
  185. @classmethod
  186. def from_dict(cls, d: dict) -> 'PipelineConfig':
  187. return cls(type=d['type'], rules=d.get('rules', []))
  188. @dataclass
  189. class FutureBlockRule:
  190. days_out: int = 150
  191. @classmethod
  192. def from_dict(cls, d: dict) -> 'FutureBlockRule':
  193. return cls(days_out=d.get('days_out', 150))
  194. @dataclass
  195. class ShortNoticeRule:
  196. max_days: int = 14
  197. ramp_days: int = 7
  198. @classmethod
  199. def from_dict(cls, d: dict) -> 'ShortNoticeRule':
  200. return cls(max_days=d.get('max_days', 14), ramp_days=d.get('ramp_days', 7))
  201. @dataclass
  202. class FillMonthRule:
  203. discount_pct: int = 10
  204. max_days: int = 30
  205. ramp_days: int = 7
  206. @classmethod
  207. def from_dict(cls, d: dict) -> 'FillMonthRule':
  208. return cls(
  209. discount_pct=d.get('discount_pct', 10),
  210. max_days=d.get('max_days', 30),
  211. ramp_days=d.get('ramp_days', 7),
  212. )
  213. @dataclass
  214. class FireRule:
  215. day_of: int = 314
  216. day_before: int = 111
  217. day_after: int = 222
  218. feed_name: str = 'Fire'
  219. @classmethod
  220. def from_dict(cls, d: dict) -> 'FireRule':
  221. return cls(
  222. day_of=d.get('day_of', 314),
  223. day_before=d.get('day_before', 111),
  224. day_after=d.get('day_after', 222),
  225. feed_name=d.get('feed_name', 'Fire'),
  226. )
  227. @dataclass
  228. class RulesConfig:
  229. future_block: FutureBlockRule = field(default_factory=FutureBlockRule)
  230. short_notice: ShortNoticeRule = field(default_factory=ShortNoticeRule)
  231. fill_month: FillMonthRule = field(default_factory=FillMonthRule)
  232. fire: FireRule = field(default_factory=FireRule)
  233. pipelines: dict[str, PipelineConfig] = field(default_factory=dict)
  234. @classmethod
  235. def from_dict(cls, d: dict) -> 'RulesConfig':
  236. return cls(
  237. future_block=FutureBlockRule.from_dict(d.get('future_block', {})),
  238. short_notice=ShortNoticeRule.from_dict(d.get('short_notice', {})),
  239. fill_month=FillMonthRule.from_dict(d.get('fill_month', {})),
  240. fire=FireRule.from_dict(d.get('fire', {})),
  241. pipelines={k: PipelineConfig.from_dict(v) for k, v in d.get('pipelines', {}).items()},
  242. )
  243. @dataclass
  244. class CalendarEntry:
  245. name: str
  246. url: str | None = None
  247. caldav: str | None = None
  248. past_days: int | None = None
  249. future_days: int | None = None
  250. @classmethod
  251. def from_dict(cls, d: dict) -> 'CalendarEntry':
  252. return cls(
  253. name=d['name'],
  254. url=d.get('url'),
  255. caldav=d.get('caldav'),
  256. past_days=d.get('past_days'),
  257. future_days=d.get('future_days'),
  258. )
  259. @dataclass
  260. class CaldavStoreConfig:
  261. url: str = ''
  262. username: str = ''
  263. password: str = ''
  264. calendar_name: str = 'Room'
  265. @classmethod
  266. def from_dict(cls, d: dict) -> 'CaldavStoreConfig':
  267. return cls(
  268. url=d.get('url', ''),
  269. username=d.get('username', ''),
  270. password=d.get('password', ''),
  271. calendar_name=d.get('calendar_name', 'Room'),
  272. )
  273. @dataclass
  274. class SqliteStoreConfig:
  275. db_path: str = 'store.db'
  276. @classmethod
  277. def from_dict(cls, d: dict) -> 'SqliteStoreConfig':
  278. return cls(db_path=d.get('db_path', 'store.db'))
  279. @dataclass
  280. class StoreConfig:
  281. active: str = 'caldav'
  282. caldav: CaldavStoreConfig = field(default_factory=CaldavStoreConfig)
  283. sqlite: SqliteStoreConfig = field(default_factory=SqliteStoreConfig)
  284. @classmethod
  285. def from_dict(cls, d: dict) -> 'StoreConfig':
  286. return cls(
  287. active=d.get('active', 'caldav'),
  288. caldav=CaldavStoreConfig.from_dict(d.get('caldav', {})),
  289. sqlite=SqliteStoreConfig.from_dict(d.get('sqlite', {})),
  290. )
  291. @dataclass
  292. class ReservationDefaultsConfig:
  293. wifi_key: str | None = None
  294. wifi_ssid: str | None = None
  295. door_code: str | None = None
  296. @classmethod
  297. def from_dict(cls, d: dict) -> 'ReservationDefaultsConfig':
  298. return cls(
  299. wifi_key=d.get('wifi_key') or None,
  300. wifi_ssid=d.get('wifi_ssid') or None,
  301. door_code=d.get('door_code') or None,
  302. )
  303. @dataclass
  304. class ReservationConfig:
  305. default: ReservationDefaultsConfig = field(default_factory=ReservationDefaultsConfig)
  306. @classmethod
  307. def from_dict(cls, d: dict) -> 'ReservationConfig':
  308. return cls(default=ReservationDefaultsConfig.from_dict(d.get('default', {})))
  309. @dataclass
  310. class ChatConfig:
  311. default_datetime_format: str = '%a, %b %-d @ %-I %p'
  312. templates: dict[str, str] = field(default_factory=dict)
  313. @classmethod
  314. def from_dict(cls, d: dict) -> 'ChatConfig':
  315. return cls(
  316. default_datetime_format=d.get('default_datetime_format', '%a, %b %-d @ %-I %p'),
  317. templates=d.get('templates', {}),
  318. )
  319. @dataclass
  320. class Config:
  321. global_: GlobalConfig = field(default_factory=GlobalConfig)
  322. services: dict[str, ServiceConfig] = field(default_factory=dict)
  323. rules: RulesConfig = field(default_factory=RulesConfig)
  324. calendars: list[CalendarEntry] = field(default_factory=list)
  325. api_url: str | None = None
  326. store: StoreConfig = field(default_factory=StoreConfig)
  327. reservation: ReservationConfig = field(default_factory=ReservationConfig)
  328. chat: ChatConfig = field(default_factory=ChatConfig)
  329. @classmethod
  330. def from_dict(cls, d: dict) -> 'Config':
  331. store_d = d.get('store', {})
  332. return cls(
  333. global_=GlobalConfig.from_dict(d.get('global', {})),
  334. services={k: ServiceConfig.from_dict(k, v) for k, v in d.get('services', {}).items()},
  335. rules=RulesConfig.from_dict(d.get('rules', {})),
  336. calendars=[CalendarEntry.from_dict(e) for e in d.get('calendars', [])],
  337. api_url=d.get('api_url'),
  338. store=StoreConfig.from_dict(store_d),
  339. reservation=ReservationConfig.from_dict(d.get('reservation', {})),
  340. chat=ChatConfig.from_dict(d.get('chat', {})),
  341. )
  342. # ── Config loading ─────────────────────────────────────────────────────────────
  343. def get_config() -> Config:
  344. """Load room_cal config.
  345. Always starts from the bundled default config.json, then deep-merges
  346. data_home()/config.json on top. Dict keys are merged recursively; lists
  347. and scalar values in the user config replace their defaults entirely.
  348. """
  349. default = json.loads(files('room_cal').joinpath('config.json').read_text(encoding='utf-8'))
  350. override_path = data_home() / 'config.json'
  351. if not override_path.exists():
  352. return Config.from_dict(default)
  353. try:
  354. override = json.loads(override_path.read_text(encoding='utf-8'))
  355. except json.JSONDecodeError as e:
  356. raise SystemExit(f"config.json parse error: {e}") from None
  357. return Config.from_dict(_deep_merge(default, override))
  358. def local_today() -> date:
  359. """Return today's date in the configured property timezone."""
  360. tz = ZoneInfo(get_config().global_.property.timezone)
  361. return datetime.now(tz).date()
  362. def services() -> list[ServiceConfig]:
  363. """Return list of ServiceConfig for all configured services."""
  364. return list(get_config().services.values())
  365. def service_name(key: str) -> str:
  366. """Return the display name for a service key, falling back to key.capitalize()."""
  367. svc = get_config().services.get(key)
  368. return svc.name if svc else key.capitalize()
  369. def source_line(source: dict) -> str:
  370. """Format a source dict {name, id} into a human-readable string."""
  371. name = source.get('name', '')
  372. id_ = source.get('id', '')
  373. return f"{name} {id_}".strip()
  374. def read_env(path: Path) -> dict[str, str]:
  375. env: dict[str, str] = {}
  376. try:
  377. for line in path.read_text().splitlines():
  378. line = line.strip()
  379. if not line or line.startswith('#') or '=' not in line:
  380. continue
  381. k, _, v = line.partition('=')
  382. env[k.strip()] = v.strip().strip("'\"")
  383. except FileNotFoundError:
  384. pass
  385. return env