_airbnb.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. import asyncio
  2. import base64
  3. import json
  4. import os
  5. import random
  6. import string
  7. import uuid
  8. from datetime import datetime
  9. from zoneinfo import ZoneInfo
  10. import httpx
  11. from dataclasses import dataclass
  12. import logging
  13. from ._scripts import _assert_not_async, _npm_env, _ts_dir, _ensure_installed
  14. from room_cal._utils import data_home, get_config, read_env
  15. from ._utils import month_bounds, months_in_range
  16. from .credentials import is_stale, mark_stale
  17. from .types import CalendarEvent, DayInfo, ServiceAuthError, Reservation
  18. _log = logging.getLogger(__name__)
  19. @dataclass
  20. class AirbnbMessage:
  21. id: str # global ID (base64)
  22. created_at_ms: str
  23. body: str | None # None for non-text messages (photos, system events, etc.)
  24. body_translated: str | None # Airbnb AI translation; None when not provided
  25. sender_account_id: str
  26. sender_name: str | None = None # resolved from thread participants; None only if resolution failed
  27. @dataclass
  28. class AirbnbThread:
  29. thread_id: str # numeric string, matches Reservation.thread_id
  30. messages: list[AirbnbMessage]
  31. @dataclass
  32. class AirbnbData:
  33. suggested_prices: dict[str, int] # date → Airbnb smart-pricing suggestion (USD)
  34. calendar_events: list[CalendarEvent] # holidays and local demand events
  35. _BASE = 'https://www.airbnb.com/api/v3'
  36. _API_KEY = 'd306zoyjsyarp7ifhu67rjxn52tv0t20'
  37. _CLIENT_VERSION = '4e93a4878415297ab95d22665c666b6602dcfcbb'
  38. _HASHES = {
  39. 'getDLSHostCalendar': '048e22675ffa53121628d2d07b519b9b71f5dab342a1ceb75aa72d8814a00ea7',
  40. 'EditPanelPricingSettingsMutation': 'e27fed4f08dd4ab4c0267c5d6c0a7e4920730deadf48f92feba9b0d08befafa4',
  41. 'EditPanelAvailabilityMutation': '2e056e7f98f8dc410a294c649adf719452980eb4d8ea95540fb1297af2637f67',
  42. 'StayHostingDetailsQuery': '5d3e94e76186b839be544fc77e5f2fcac0b8d7639c3da16941b89cda5ee03ed9',
  43. 'getNightlyPriceTips': '07538bf1a5afc8171f1e7443f0007d7f020142fc7ab60df065e7e1edd1a0b29f',
  44. 'HostCalendarListingEventsQuery': '8bfe5f5572a25fdaff5b5790604e1de3aec5f37731fc505684022d590d06e0a8',
  45. 'ViaductGetThreadAndDataQuery': 'dd7478b376ad0a9709c7201b7e43cf402df011ec9d2fe4c1dff2ac418bcd9fb3',
  46. 'CreateBulkMessagesMutation': '94ac2c4bd07edace539dbf2b9665d9030b6dee479db345ba8a8bbc234b3bbfa3',
  47. }
  48. _AUTH_HINT = 'refresh-creds'
  49. class AirbnbAuthError(ServiceAuthError):
  50. pass
  51. def _encode_listing_id(listing_id: str) -> str:
  52. return base64.b64encode(f'StayListing:{listing_id}'.encode()).decode()
  53. def _trace_id() -> str:
  54. return ''.join(random.choices(string.ascii_lowercase + string.digits, k=28))
  55. class _AirbnbClient:
  56. service_name = 'AirBnB'
  57. def __init__(self, cookies: str, listing_id: str, tz: str = 'America/Los_Angeles'):
  58. self._cookies = cookies
  59. self._listing_id = listing_id
  60. self._global_id = _encode_listing_id(listing_id)
  61. self._tz = tz
  62. self._cache: dict[str, DayInfo] = {}
  63. self._fetched_months: set[tuple[int, int]] = set()
  64. self._raw_months: dict[tuple[int, int], list[dict]] = {}
  65. self._months_inflight: dict[tuple[int, int], asyncio.Task] = {}
  66. self._refresh_lock = asyncio.Lock()
  67. self._refresh_task: asyncio.Task | None = None
  68. @classmethod
  69. def from_env(cls) -> '_AirbnbClient':
  70. env_file = data_home() / 'airbnb.env'
  71. env = {**read_env(env_file), **os.environ}
  72. cookies = env.get('AIRBNB_COOKIES', '')
  73. if not cookies:
  74. raise ValueError(f'AIRBNB_COOKIES must be set in {env_file}')
  75. listing_id = get_config().services['airbnb'].room_id
  76. if not listing_id:
  77. raise ValueError('airbnb.room_id must be set in config.json')
  78. return cls(cookies=cookies, listing_id=listing_id)
  79. def clear_cache(self) -> None:
  80. self._cache.clear()
  81. self._fetched_months.clear()
  82. self._raw_months.clear()
  83. def _reload_from_env(self) -> None:
  84. env_file = data_home() / 'airbnb.env'
  85. env = {**read_env(env_file), **os.environ}
  86. self._cookies = env.get('AIRBNB_COOKIES', self._cookies)
  87. self.clear_cache()
  88. @staticmethod
  89. def refresh_credentials() -> None:
  90. _assert_not_async('refresh_credentials')
  91. ts_dir = _ts_dir()
  92. _ensure_installed(ts_dir)
  93. import subprocess
  94. _log.info('airbnb: starting credential refresh')
  95. env = _npm_env()
  96. env['HEADLESS'] = '1'
  97. try:
  98. subprocess.run(['npm', 'run', 'refresh-airbnb'], cwd=ts_dir, env=env, check=True)
  99. except subprocess.CalledProcessError as e:
  100. _log.error('airbnb: credential refresh failed (exit %d)', e.returncode)
  101. raise ServiceAuthError(f'Airbnb session expired — re-run without HEADLESS to re-authenticate (exit {e.returncode})') from None
  102. _log.info('airbnb: credential refresh complete')
  103. async def _auto_refresh(self) -> None:
  104. _log.warning('Airbnb session may be expired — launching headless Playwright')
  105. try:
  106. await asyncio.get_running_loop().run_in_executor(None, _AirbnbClient.refresh_credentials)
  107. self._reload_from_env()
  108. except ServiceAuthError:
  109. mark_stale('airbnb')
  110. raise
  111. async def _ensure_refreshed(self) -> None:
  112. async with self._refresh_lock:
  113. if self._refresh_task is None or self._refresh_task.done():
  114. self._refresh_task = asyncio.create_task(self._auto_refresh())
  115. task = self._refresh_task
  116. await task
  117. def _headers(self, referer: str, extra: dict | None = None) -> dict[str, str]:
  118. h = {
  119. 'Cookie': self._cookies,
  120. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:152.0) Gecko/20100101 Firefox/152.0',
  121. 'Accept': '*/*',
  122. 'Accept-Language': 'en-US,en;q=0.9',
  123. 'Content-Type': 'application/json',
  124. 'Referer': referer,
  125. 'Sec-Fetch-Mode': 'cors',
  126. 'Sec-Fetch-Dest': 'empty',
  127. 'Sec-Fetch-Site': 'same-origin',
  128. 'X-Airbnb-API-Key': _API_KEY,
  129. 'X-Airbnb-GraphQL-Platform': 'web',
  130. 'X-Airbnb-GraphQL-Platform-Client': 'minimalist-niobe',
  131. 'X-Airbnb-Supports-Airlock-V2': 'true',
  132. 'X-Niobe-Short-Circuited': 'true',
  133. 'X-Client-Version': _CLIENT_VERSION,
  134. 'X-CSRF-Token': '',
  135. 'X-CSRF-Without-Token': '1',
  136. 'x-airbnb-client-trace-id': _trace_id(),
  137. 'x-client-request-id': _trace_id(),
  138. 'x-airbnb-network-log-link': _trace_id(),
  139. }
  140. if extra:
  141. h.update(extra)
  142. return h
  143. def _check_auth(self, body: dict) -> None:
  144. if any(
  145. e.get('extensions', {}).get('response', {}).get('status') in (400, 401, 403)
  146. for e in body.get('errors', [])
  147. ):
  148. mark_stale('airbnb')
  149. raise AirbnbAuthError(f'Airbnb session expired — run: {_AUTH_HINT}')
  150. async def _gql(self, op: str, h: str, variables: dict, referer: str) -> dict:
  151. url = f'{_BASE}/{op}/{h}'
  152. params = {
  153. 'operationName': op,
  154. 'locale': 'en',
  155. 'currency': 'USD',
  156. 'variables': json.dumps(variables),
  157. 'extensions': json.dumps({'persistedQuery': {'version': 1, 'sha256Hash': h}}),
  158. }
  159. async def _attempt() -> httpx.Response:
  160. async with httpx.AsyncClient() as client:
  161. return await client.get(url, params=params, headers=self._headers(referer))
  162. try:
  163. r = await _attempt()
  164. except (httpx.TransportError, OSError, ExceptionGroup) as e:
  165. raise AirbnbAuthError(f'Airbnb connection failed — session may be expired, run: {_AUTH_HINT}') from e
  166. if r.status_code in (400, 401, 403):
  167. await self._ensure_refreshed()
  168. r = await _attempt()
  169. if r.status_code in (400, 401, 403):
  170. mark_stale('airbnb')
  171. raise AirbnbAuthError(f'Airbnb session expired (HTTP {r.status_code}) — run: {_AUTH_HINT}')
  172. r.raise_for_status()
  173. body = r.json()
  174. self._check_auth(body)
  175. return body
  176. async def _mutate(self, op: str, h: str, variables: dict, referer: str) -> dict:
  177. url = f'{_BASE}/{op}/{h}?operationName={op}&locale=en&currency=USD'
  178. payload = {'operationName': op, 'variables': variables,
  179. 'extensions': {'persistedQuery': {'version': 1, 'sha256Hash': h}}}
  180. async def _attempt() -> httpx.Response:
  181. async with httpx.AsyncClient() as client:
  182. return await client.post(
  183. url, json=payload,
  184. headers=self._headers(referer, {'Origin': 'https://www.airbnb.com'}),
  185. )
  186. try:
  187. r = await _attempt()
  188. except (httpx.TransportError, OSError, ExceptionGroup) as e:
  189. raise AirbnbAuthError(f'Airbnb connection failed — session may be expired, run: {_AUTH_HINT}') from e
  190. if r.status_code in (400, 401, 403):
  191. await self._ensure_refreshed()
  192. r = await _attempt()
  193. if r.status_code in (400, 401, 403):
  194. mark_stale('airbnb')
  195. raise AirbnbAuthError(f'Airbnb session expired (HTTP {r.status_code}) — run: {_AUTH_HINT}')
  196. r.raise_for_status()
  197. body = r.json()
  198. self._check_auth(body)
  199. return body
  200. async def _fetch_month_days(self, month: int, year: int) -> list[dict]:
  201. start, end = month_bounds(month, year)
  202. variables = {
  203. 'listingId': self._global_id,
  204. 'startDate': start,
  205. 'endDate': end,
  206. 'hostCalendarViewType': 'MONTH_VIEW',
  207. 'lensTypes': ['NOTE', 'PRICE', 'PROMOTION'],
  208. 'timeZone': self._tz,
  209. 'localizationContext': {'timeZone': self._tz, 'firstDayOfWeek': 0},
  210. 'hostCalendarSectionTypes': ['MAIN_VIEW'],
  211. 'readConsistency': 'EVENTUAL',
  212. }
  213. referer = f'https://www.airbnb.com/multicalendar/{self._listing_id}'
  214. def _extract_days(resp: dict) -> list[dict]:
  215. section = (
  216. resp.get('data', {}).get('presentation', {})
  217. .get('hostCalendar', {}).get('sections', {})
  218. .get('calendarGridViewSection')
  219. ) or {}
  220. return section.get('days', [])
  221. def _has_prices(days: list[dict]) -> bool:
  222. return any(d.get('priceData', {}).get('price') is not None for d in days)
  223. resp = await self._gql('getDLSHostCalendar', _HASHES['getDLSHostCalendar'], variables, referer)
  224. days = _extract_days(resp)
  225. if not days or not _has_prices(days):
  226. _log.warning('Airbnb: empty or priceless calendar for %d-%02d; retrying', year, month)
  227. await asyncio.sleep(1)
  228. resp = await self._gql('getDLSHostCalendar', _HASHES['getDLSHostCalendar'], variables, referer)
  229. days = _extract_days(resp)
  230. if not days or not _has_prices(days):
  231. _log.warning('Airbnb: still empty/priceless calendar for %d-%02d after retry', year, month)
  232. return days
  233. async def _get_month_days(self, month: int, year: int) -> list[dict]:
  234. key = (month, year)
  235. if key in self._raw_months:
  236. return self._raw_months[key]
  237. if key in self._months_inflight:
  238. return await self._months_inflight[key]
  239. task = asyncio.create_task(self._fetch_month_days(month, year))
  240. self._months_inflight[key] = task
  241. try:
  242. result = await task
  243. finally:
  244. self._months_inflight.pop(key, None)
  245. self._raw_months[key] = result
  246. return result
  247. async def get_calendar(self, date_from: str, date_to: str) -> dict[str, DayInfo]:
  248. if is_stale('airbnb'):
  249. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  250. month_list = months_in_range(date_from, date_to)
  251. all_days = await asyncio.gather(*[self._get_month_days(m, y) for m, y in month_list])
  252. for (month, year), days in zip(month_list, all_days):
  253. if (month, year) not in self._fetched_months:
  254. for day in days:
  255. d = day.get('day', '')
  256. if d:
  257. self._cache[d] = DayInfo(
  258. date=d,
  259. price=day.get('priceData', {}).get('price'),
  260. available=day.get('available', False),
  261. booked=day.get('reservationData') is not None,
  262. rooms_to_sell=None,
  263. )
  264. self._fetched_months.add((month, year))
  265. return {d: info for d, info in self._cache.items() if date_from <= d <= date_to}
  266. async def get_reservations(self, date_from: str, date_to: str) -> list[Reservation]:
  267. if is_stale('airbnb'):
  268. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  269. month_list = months_in_range(date_from, date_to)
  270. all_days = await asyncio.gather(*[self._get_month_days(m, y) for m, y in month_list])
  271. booked: dict[str, str] = {}
  272. for days in all_days:
  273. for day in days:
  274. d = day.get('day', '')
  275. res_data = day.get('reservationData')
  276. if res_data and date_from <= d <= date_to:
  277. booked[d] = res_data.get('confirmationCode', '')
  278. if not booked:
  279. return []
  280. unique_codes = set(booked.values())
  281. def _utc_to_local_date(ts: str) -> str:
  282. dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
  283. return dt.astimezone(ZoneInfo(self._tz)).date().isoformat()
  284. async def fetch_details(c: str) -> tuple[str, str | None, str | None, str | None, str | None, str | None]:
  285. resp = await self._gql(
  286. 'StayHostingDetailsQuery', _HASHES['StayHostingDetailsQuery'],
  287. {'viewerTimeZoneOffset': 0, 'requestSource': 'RESERVATION_TAB', 'confirmationCode': c},
  288. f'https://www.airbnb.com/hosting/reservations/details/{c}',
  289. )
  290. sections = (
  291. resp.get('data', {}).get('presentation', {})
  292. .get('hostingDetails', {}).get('stayHostingDetails', {})
  293. .get('rootPlacement', [])
  294. )
  295. whoscoming = next((s for s in sections if s.get('sectionId') == 'WHOSCOMING_SECTION'), None)
  296. wc_groups = (whoscoming or {}).get('sectionData', {}).get('reservationGroups', [])
  297. wc_guests = wc_groups[0].get('guests', []) if wc_groups else []
  298. facepile = next((s for s in sections if s.get('sectionId') == 'FACEPILE_SECTION'), None)
  299. fp_guests = (facepile or {}).get('sectionData', {}).get('guests', [])
  300. name = (wc_guests[0].get('name') if wc_guests else None) or (fp_guests[0].get('name') if fp_guests else None)
  301. checkinout = next((s for s in sections if s.get('sectionId') == 'CHECK_IN_CHECK_OUT_SECTION'), None)
  302. ci_out_data = (checkinout or {}).get('sectionData') or {}
  303. action = ci_out_data.get('checkInAction', {})
  304. ci_ts = action.get('checkInTime')
  305. co_ts = action.get('checkOutTime')
  306. ci = _utc_to_local_date(ci_ts) if ci_ts else None
  307. co = _utc_to_local_date(co_ts) if co_ts else None
  308. door_code = (ci_out_data.get('airkeyAction') or {}).get('guestPhoneNumberLastFourDigits')
  309. # thread_id is in footerPlacement FLOATINGFOOTER_SECTION, not rootPlacement
  310. details = resp.get('data', {}).get('presentation', {}).get('hostingDetails', {}).get('stayHostingDetails', {})
  311. footer_sections = details.get('footerPlacement', [])
  312. footer = next((s for s in footer_sections if s.get('sectionId') == 'FLOATINGFOOTER_SECTION'), None)
  313. buttons = ((footer or {}).get('sectionData') or {}).get('buttons', [])
  314. thread_id = None
  315. for btn in buttons:
  316. action = btn.get('buttonAction') or {}
  317. if action.get('__typename') == 'NavigateToMessageGuest':
  318. url = action.get('url', '')
  319. m = __import__('re').search(r'/thread/(\d+)', url)
  320. if m:
  321. thread_id = m.group(1)
  322. break
  323. return c, name, ci, co, door_code, thread_id
  324. details_list = await asyncio.gather(*[fetch_details(c) for c in unique_codes])
  325. details = {c: (name, ci, co, door_code, thread_id) for c, name, ci, co, door_code, thread_id in details_list}
  326. return sorted(
  327. [
  328. Reservation(
  329. service='airbnb',
  330. reservation_id=c,
  331. check_in=ci,
  332. check_out=co,
  333. guest_name=name,
  334. door_code=door_code,
  335. thread_id=thread_id,
  336. service_data={k: v for k, v in {'door_code': door_code, 'thread_id': thread_id}.items() if v is not None},
  337. chat_id=thread_id,
  338. )
  339. for c, (name, ci, co, door_code, thread_id) in details.items()
  340. if ci and co
  341. ],
  342. key=lambda r: r.check_in,
  343. )
  344. async def set_price(self, d: str, price: int) -> None:
  345. price = int(round(price))
  346. if is_stale('airbnb'):
  347. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  348. if (cached := self._cache.get(d)) and cached.price == price:
  349. return
  350. await self._mutate(
  351. 'EditPanelPricingSettingsMutation', _HASHES['EditPanelPricingSettingsMutation'],
  352. {'input': {
  353. 'listingId': self._listing_id,
  354. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  355. 'nightlyPriceAmount': price,
  356. 'turnOnSmartPricing': False,
  357. 'isCalendarV2': True,
  358. }},
  359. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}/nightly-price',
  360. )
  361. self.clear_cache()
  362. _log.info('airbnb set_price date=%s price=$%d', d, price)
  363. async def set_availability(self, d: str, available: bool) -> None:
  364. if is_stale('airbnb'):
  365. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  366. if (cached := self._cache.get(d)) and cached.available == available:
  367. return
  368. body = await self._mutate(
  369. 'EditPanelAvailabilityMutation', _HASHES['EditPanelAvailabilityMutation'],
  370. {'input': {
  371. 'listingId': self._listing_id,
  372. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  373. 'actionType': 'OPEN' if available else 'BLOCK',
  374. }, 'blockNotesEnabled': True},
  375. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}',
  376. )
  377. if errors := body.get('errors'):
  378. _log.error('airbnb set_availability date=%s errors=%s', d, errors)
  379. raise AirbnbAuthError(f'Airbnb set_availability failed for {d}: {errors[0].get("message", errors)}')
  380. self.clear_cache()
  381. _log.info('airbnb set_availability date=%s available=%s', d, available)
  382. def _global_thread_id(self, thread_id: str) -> str:
  383. return base64.b64encode(f'MessageThread:{thread_id}'.encode()).decode()
  384. async def get_thread(self, thread_id: str) -> AirbnbThread:
  385. """Fetch a conversation thread and its messages by numeric thread ID."""
  386. if is_stale('airbnb'):
  387. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  388. resp = await self._gql(
  389. 'ViaductGetThreadAndDataQuery', _HASHES['ViaductGetThreadAndDataQuery'],
  390. {
  391. 'globalThreadId': self._global_thread_id(thread_id),
  392. 'numRequestedMessages': 50,
  393. 'getThreadState': True,
  394. 'getParticipants': True,
  395. 'getLastReads': True,
  396. 'getInboxFields': True,
  397. 'getInboxOnlyFields': False,
  398. 'getMessageFields': True,
  399. 'getThreadOnlyFields': True,
  400. 'forceUgcTranslation': False,
  401. 'isNovaLite': False,
  402. 'mockThreadIdentifier': None,
  403. 'mockMessageTestIdentifier': None,
  404. 'mockListFooterSlot': None,
  405. 'forceReturnAllReadReceipts': False,
  406. 'originType': 'USER_INBOX',
  407. 'skipOldMessagePreviewFields': False,
  408. },
  409. f'https://www.airbnb.com/messages/{thread_id}',
  410. )
  411. thread_data = resp.get('data', {}).get('threadData', {})
  412. participants: dict[str, str] = {}
  413. for edge in thread_data.get('participants', {}).get('edges', []):
  414. node = edge.get('node', {})
  415. account_id = node.get('accountId', '')
  416. name = (node.get('enrichedParticipantInfo') or {}).get('name', '')
  417. if account_id and name:
  418. participants[account_id] = name
  419. messages = []
  420. for m in thread_data.get('messageData', {}).get('messages', []):
  421. aid = (m.get('account') or {}).get('accountId', '')
  422. messages.append(AirbnbMessage(
  423. id=m['id'],
  424. created_at_ms=m['createdAtMs'],
  425. body=(((m.get('hydratedContent') or {}).get('content') or {}).get('body')),
  426. body_translated=(((m.get('hydratedContent') or {}).get('content') or {}).get('bodyTranslated')),
  427. sender_account_id=aid,
  428. sender_name=participants.get(aid, 'Airbnb'),
  429. ))
  430. return AirbnbThread(thread_id=thread_id, messages=messages)
  431. async def send_message(self, thread_id: str, body: str) -> None:
  432. """Send a text message to an existing thread."""
  433. if is_stale('airbnb'):
  434. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  435. await self._mutate(
  436. 'CreateBulkMessagesMutation', _HASHES['CreateBulkMessagesMutation'],
  437. {
  438. 'messageThreadId': thread_id,
  439. 'messages': [{
  440. 'content': {'textContent': {'body': body}},
  441. 'uniqueIdentifier': str(uuid.uuid4()),
  442. 'loggingSource': {'sourceType': '', 'sourceId': ''},
  443. 'loggingExtras': {'entries': []},
  444. }],
  445. 'actAs': 'PARTICIPANT',
  446. 'businessJustification': {'feature': 'USER_INBOX'},
  447. 'originType': 'USER_INBOX',
  448. 'senderPlatform': 'WEB',
  449. 'skipOldMessagePreviewFields': False,
  450. },
  451. f'https://www.airbnb.com/messages/{thread_id}',
  452. )
  453. async def get_suggested_prices(self, date_from: str, date_to: str) -> dict[str, int]:
  454. """Airbnb's per-day smart-pricing suggestions (USD). Only includes days where shouldShowTip=True."""
  455. if is_stale('airbnb'):
  456. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  457. resp = await self._gql(
  458. 'getNightlyPriceTips', _HASHES['getNightlyPriceTips'],
  459. {
  460. 'listingId': self._global_id,
  461. 'dateRanges': [{'startDate': date_from, 'endDate': date_to}],
  462. },
  463. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  464. )
  465. tips = (
  466. resp.get('data', {}).get('presentation', {})
  467. .get('pricingGuidance', {}).get('nightlyPriceTip', {})
  468. .get('nightlyPriceTip', {}).get('discretePriceTips', [])
  469. )
  470. return {
  471. t['date']: t['priceTip']['intValue']
  472. for t in tips
  473. if t.get('shouldShowTip') and date_from <= t['date'] <= date_to
  474. }
  475. async def get_service_data(self, date_from: str, date_to: str) -> AirbnbData:
  476. suggested_prices, calendar_events = await asyncio.gather(
  477. self.get_suggested_prices(date_from, date_to),
  478. self.get_calendar_events(),
  479. )
  480. return AirbnbData(suggested_prices=suggested_prices, calendar_events=calendar_events)
  481. async def probe(self) -> None:
  482. from datetime import date
  483. today = date.today().isoformat()
  484. await self.get_calendar(today, today)
  485. async def get_calendar_events(self) -> list[CalendarEvent]:
  486. """Local events and holidays Airbnb shows on the host calendar (holidays, major events, etc.)."""
  487. if is_stale('airbnb'):
  488. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  489. resp = await self._gql(
  490. 'HostCalendarListingEventsQuery', _HASHES['HostCalendarListingEventsQuery'],
  491. {'listingId': self._global_id},
  492. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  493. )
  494. events = (
  495. resp.get('data', {}).get('presentation', {})
  496. .get('hostCalendarListingEvents', {}).get('events', [])
  497. )
  498. return [
  499. CalendarEvent(
  500. start_date=e['startDate'],
  501. end_date=e['endDate'],
  502. name=e['displayName'],
  503. type=e['type'],
  504. event_id=e['eventId'],
  505. )
  506. for e in events
  507. ]