_airbnb.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 date, datetime, timedelta
  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': '6da83b8bc9ae1b434f13938a55435118347b0e8ceb838e04c1feb84ecb587e6d',
  43. 'getNightlyPriceTips': '07538bf1a5afc8171f1e7443f0007d7f020142fc7ab60df065e7e1edd1a0b29f',
  44. 'HostCalendarListingEventsQuery': '8bfe5f5572a25fdaff5b5790604e1de3aec5f37731fc505684022d590d06e0a8',
  45. 'ViaductGetThreadAndDataQuery': 'dd7478b376ad0a9709c7201b7e43cf402df011ec9d2fe4c1dff2ac418bcd9fb3',
  46. 'CreateBulkMessagesMutation': '94ac2c4bd07edace539dbf2b9665d9030b6dee479db345ba8a8bbc234b3bbfa3',
  47. }
  48. _AUTH_HINT = 'refresh-creds'
  49. def _parse_price(s: str) -> float | None:
  50. """Parse a formatted price string like '$143.56' → 143.56, or None on failure."""
  51. try:
  52. return float(s.replace('$', '').replace(',', '').strip())
  53. except (ValueError, AttributeError):
  54. return None
  55. def _parse_booked_nets(det: dict, check_in: str, check_out: str) -> dict[str, int]:
  56. """Return {YYYY-MM-DD: net_dollars} for each night of a reservation.
  57. Uses proportional apportionment: net_i = total_host_net * (list_i / sum(list)).
  58. Reads PAYMENTINFO_SECTION from stayHostingDetails (rootPlacement).
  59. Returns {} if the section is missing or the data is malformed.
  60. """
  61. sections = det.get('rootPlacement', [])
  62. pay = next((s for s in sections if s.get('sectionId') == 'PAYMENTINFO_SECTION'), None)
  63. if not pay:
  64. return {}
  65. eg = (pay.get('sectionData') or {}).get('hostEarningsGroup', {})
  66. total_net = _parse_price((eg.get('totalLineItem') or {}).get('formattedValue', ''))
  67. if total_net is None:
  68. return {}
  69. nights_item = next(
  70. (li for li in eg.get('lineItems', []) if (li.get('collapsibleLineItemGroup') or {}).get('collapsedLineItems')),
  71. None,
  72. )
  73. if not nights_item:
  74. return {}
  75. weights = [
  76. w for item in nights_item['collapsibleLineItemGroup']['collapsedLineItems']
  77. if (w := _parse_price(item.get('formattedValue', ''))) is not None
  78. ]
  79. ci = date.fromisoformat(check_in)
  80. co = date.fromisoformat(check_out)
  81. nights = [(ci + timedelta(days=i)).isoformat() for i in range((co - ci).days)]
  82. if not weights or len(nights) != len(weights):
  83. return {}
  84. total_weight = sum(weights)
  85. if total_weight == 0:
  86. return {}
  87. return {d: round(total_net * w / total_weight) for d, w in zip(nights, weights)}
  88. class AirbnbAuthError(ServiceAuthError):
  89. pass
  90. def _encode_listing_id(listing_id: str) -> str:
  91. return base64.b64encode(f'StayListing:{listing_id}'.encode()).decode()
  92. def _trace_id() -> str:
  93. return ''.join(random.choices(string.ascii_lowercase + string.digits, k=28))
  94. class _AirbnbClient:
  95. service_name = 'AirBnB'
  96. def __init__(self, cookies: str, listing_id: str, tz: str = 'America/Los_Angeles'):
  97. self._cookies = cookies
  98. self._listing_id = listing_id
  99. self._global_id = _encode_listing_id(listing_id)
  100. self._tz = tz
  101. self._cache: dict[str, DayInfo] = {}
  102. self._fetched_months: set[tuple[int, int]] = set()
  103. self._raw_months: dict[tuple[int, int], list[dict]] = {}
  104. self._months_inflight: dict[tuple[int, int], asyncio.Task] = {}
  105. self._refresh_lock = asyncio.Lock()
  106. self._refresh_task: asyncio.Task | None = None
  107. self._http = httpx.AsyncClient(timeout=10.0)
  108. self._detail_cache: dict[str, dict] = {}
  109. self._booked_nets: dict[str, int] = {}
  110. @classmethod
  111. def from_env(cls) -> '_AirbnbClient':
  112. env_file = data_home() / 'airbnb.env'
  113. env = {**read_env(env_file), **os.environ}
  114. cookies = env.get('AIRBNB_COOKIES', '')
  115. if not cookies:
  116. raise ValueError(f'AIRBNB_COOKIES must be set in {env_file}')
  117. listing_id = get_config().services['airbnb'].room_id
  118. if not listing_id:
  119. raise ValueError('airbnb.room_id must be set in config.json')
  120. return cls(cookies=cookies, listing_id=listing_id)
  121. def clear_cache(self) -> None:
  122. self._cache.clear()
  123. self._fetched_months.clear()
  124. self._raw_months.clear()
  125. self._detail_cache.clear()
  126. self._booked_nets.clear()
  127. def _reload_from_env(self) -> None:
  128. env_file = data_home() / 'airbnb.env'
  129. env = {**read_env(env_file), **os.environ}
  130. self._cookies = env.get('AIRBNB_COOKIES', self._cookies)
  131. self.clear_cache()
  132. @staticmethod
  133. def refresh_credentials() -> None:
  134. _assert_not_async('refresh_credentials')
  135. ts_dir = _ts_dir()
  136. _ensure_installed(ts_dir)
  137. import subprocess
  138. _log.info('airbnb: starting credential refresh')
  139. env = _npm_env()
  140. env['HEADLESS'] = '1'
  141. try:
  142. subprocess.run(['npm', 'run', 'refresh-airbnb'], cwd=ts_dir, env=env, check=True)
  143. except subprocess.CalledProcessError as e:
  144. _log.error('airbnb: credential refresh failed (exit %d)', e.returncode)
  145. raise ServiceAuthError(f'Airbnb session expired — re-run without HEADLESS to re-authenticate (exit {e.returncode})') from None
  146. _log.info('airbnb: credential refresh complete')
  147. async def _auto_refresh(self) -> None:
  148. _log.warning('Airbnb session may be expired — launching headless Playwright')
  149. try:
  150. await asyncio.get_running_loop().run_in_executor(None, _AirbnbClient.refresh_credentials)
  151. self._reload_from_env()
  152. except ServiceAuthError:
  153. mark_stale('airbnb')
  154. raise
  155. async def _ensure_refreshed(self) -> None:
  156. async with self._refresh_lock:
  157. if self._refresh_task is None or self._refresh_task.done():
  158. self._refresh_task = asyncio.create_task(self._auto_refresh())
  159. task = self._refresh_task
  160. await task
  161. def _headers(self, referer: str, extra: dict | None = None) -> dict[str, str]:
  162. h = {
  163. 'Cookie': self._cookies,
  164. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:152.0) Gecko/20100101 Firefox/152.0',
  165. 'Accept': '*/*',
  166. 'Accept-Language': 'en-US,en;q=0.9',
  167. 'Content-Type': 'application/json',
  168. 'Referer': referer,
  169. 'Sec-Fetch-Mode': 'cors',
  170. 'Sec-Fetch-Dest': 'empty',
  171. 'Sec-Fetch-Site': 'same-origin',
  172. 'X-Airbnb-API-Key': _API_KEY,
  173. 'X-Airbnb-GraphQL-Platform': 'web',
  174. 'X-Airbnb-GraphQL-Platform-Client': 'minimalist-niobe',
  175. 'X-Airbnb-Supports-Airlock-V2': 'true',
  176. 'X-Niobe-Short-Circuited': 'true',
  177. 'X-Client-Version': _CLIENT_VERSION,
  178. 'X-CSRF-Token': '',
  179. 'X-CSRF-Without-Token': '1',
  180. 'x-airbnb-client-trace-id': _trace_id(),
  181. 'x-client-request-id': _trace_id(),
  182. 'x-airbnb-network-log-link': _trace_id(),
  183. }
  184. if extra:
  185. h.update(extra)
  186. return h
  187. def _check_auth(self, body: dict) -> None:
  188. if any(
  189. e.get('extensions', {}).get('response', {}).get('status') in (400, 401, 403)
  190. for e in body.get('errors', [])
  191. ):
  192. mark_stale('airbnb')
  193. raise AirbnbAuthError(f'Airbnb session expired — run: {_AUTH_HINT}')
  194. async def _gql(self, op: str, h: str, variables: dict, referer: str) -> dict:
  195. url = f'{_BASE}/{op}/{h}'
  196. params = {
  197. 'operationName': op,
  198. 'locale': 'en',
  199. 'currency': 'USD',
  200. 'variables': json.dumps(variables),
  201. 'extensions': json.dumps({'persistedQuery': {'version': 1, 'sha256Hash': h}}),
  202. }
  203. async def _attempt() -> httpx.Response:
  204. return await self._http.get(url, params=params, headers=self._headers(referer))
  205. try:
  206. r = await _attempt()
  207. except httpx.TimeoutException as e:
  208. raise httpx.ReadTimeout(f'Airbnb request timed out ({op})') from e
  209. except (httpx.TransportError, OSError, ExceptionGroup) as e:
  210. raise AirbnbAuthError(f'Airbnb connection failed — session may be expired, run: {_AUTH_HINT}') from e
  211. if r.status_code in (400, 401, 403):
  212. await self._ensure_refreshed()
  213. r = await _attempt()
  214. if r.status_code in (400, 401, 403):
  215. mark_stale('airbnb')
  216. raise AirbnbAuthError(f'Airbnb session expired (HTTP {r.status_code}) — run: {_AUTH_HINT}')
  217. r.raise_for_status()
  218. body = r.json()
  219. self._check_auth(body)
  220. return body
  221. async def _mutate(self, op: str, h: str, variables: dict, referer: str) -> dict:
  222. url = f'{_BASE}/{op}/{h}?operationName={op}&locale=en&currency=USD'
  223. payload = {'operationName': op, 'variables': variables,
  224. 'extensions': {'persistedQuery': {'version': 1, 'sha256Hash': h}}}
  225. async def _attempt() -> httpx.Response:
  226. return await self._http.post(
  227. url, json=payload,
  228. headers=self._headers(referer, {'Origin': 'https://www.airbnb.com'}),
  229. )
  230. try:
  231. r = await _attempt()
  232. except (httpx.TransportError, OSError, ExceptionGroup) as e:
  233. raise AirbnbAuthError(f'Airbnb connection failed — session may be expired, run: {_AUTH_HINT}') from e
  234. if r.status_code in (400, 401, 403):
  235. await self._ensure_refreshed()
  236. r = await _attempt()
  237. if r.status_code in (400, 401, 403):
  238. mark_stale('airbnb')
  239. raise AirbnbAuthError(f'Airbnb session expired (HTTP {r.status_code}) — run: {_AUTH_HINT}')
  240. r.raise_for_status()
  241. body = r.json()
  242. self._check_auth(body)
  243. return body
  244. async def _fetch_month_days(self, month: int, year: int) -> list[dict]:
  245. start, end = month_bounds(month, year)
  246. variables = {
  247. 'listingId': self._global_id,
  248. 'startDate': start,
  249. 'endDate': end,
  250. 'hostCalendarViewType': 'MONTH_VIEW',
  251. 'lensTypes': ['NOTE', 'PRICE', 'PROMOTION'],
  252. 'timeZone': self._tz,
  253. 'localizationContext': {'timeZone': self._tz, 'firstDayOfWeek': 0},
  254. 'hostCalendarSectionTypes': ['MAIN_VIEW'],
  255. 'readConsistency': 'EVENTUAL',
  256. }
  257. referer = f'https://www.airbnb.com/multicalendar/{self._listing_id}'
  258. def _extract_days(resp: dict) -> list[dict]:
  259. section = (
  260. resp.get('data', {}).get('presentation', {})
  261. .get('hostCalendar', {}).get('sections', {})
  262. .get('calendarGridViewSection')
  263. ) or {}
  264. return section.get('days', [])
  265. def _has_prices(days: list[dict]) -> bool:
  266. return any(d.get('priceData', {}).get('price') is not None for d in days)
  267. resp = await self._gql('getDLSHostCalendar', _HASHES['getDLSHostCalendar'], variables, referer)
  268. days = _extract_days(resp)
  269. if not days or not _has_prices(days):
  270. _log.warning('Airbnb: empty or priceless calendar for %d-%02d; retrying', year, month)
  271. await asyncio.sleep(1)
  272. resp = await self._gql('getDLSHostCalendar', _HASHES['getDLSHostCalendar'], variables, referer)
  273. days = _extract_days(resp)
  274. if not days or not _has_prices(days):
  275. _log.warning('Airbnb: still empty/priceless calendar for %d-%02d after retry', year, month)
  276. return days
  277. async def _get_month_days(self, month: int, year: int) -> list[dict]:
  278. key = (month, year)
  279. if key in self._raw_months:
  280. return self._raw_months[key]
  281. if key in self._months_inflight:
  282. return await self._months_inflight[key]
  283. task = asyncio.create_task(self._fetch_month_days(month, year))
  284. self._months_inflight[key] = task
  285. try:
  286. result = await task
  287. finally:
  288. self._months_inflight.pop(key, None)
  289. self._raw_months[key] = result
  290. return result
  291. async def get_calendar(self, date_from: str, date_to: str) -> dict[str, DayInfo]:
  292. if is_stale('airbnb'):
  293. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  294. month_list = months_in_range(date_from, date_to)
  295. all_days = await asyncio.gather(*[self._get_month_days(m, y) for m, y in month_list])
  296. for (month, year), days in zip(month_list, all_days):
  297. if (month, year) not in self._fetched_months:
  298. for day in days:
  299. d = day.get('day', '')
  300. if d:
  301. self._cache[d] = DayInfo(
  302. date=d,
  303. price=day.get('priceData', {}).get('price'),
  304. available=day.get('available', False),
  305. booked=day.get('reservationData') is not None,
  306. rooms_to_sell=None,
  307. )
  308. self._fetched_months.add((month, year))
  309. return {
  310. d: DayInfo(
  311. date=info.date,
  312. price=info.price,
  313. available=info.available,
  314. booked=info.booked,
  315. rooms_to_sell=info.rooms_to_sell,
  316. booked_net=self._booked_nets.get(d) if info.booked else None,
  317. )
  318. for d, info in self._cache.items()
  319. if date_from <= d <= date_to
  320. }
  321. async def get_reservations(self, date_from: str, date_to: str) -> list[Reservation]:
  322. if is_stale('airbnb'):
  323. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  324. month_list = months_in_range(date_from, date_to)
  325. all_days = await asyncio.gather(*[self._get_month_days(m, y) for m, y in month_list])
  326. booked: dict[str, str] = {}
  327. for days in all_days:
  328. for day in days:
  329. d = day.get('day', '')
  330. res_data = day.get('reservationData')
  331. if res_data and date_from <= d <= date_to:
  332. booked[d] = res_data.get('confirmationCode', '')
  333. if not booked:
  334. return []
  335. unique_codes = set(booked.values())
  336. _sem = asyncio.Semaphore(10)
  337. async def fetch_details(c: str) -> tuple[str, str | None, str | None, str | None, str | None, str | None]:
  338. async with _sem:
  339. det = await self._fetch_one_detail(c)
  340. sections = det.get('rootPlacement', [])
  341. whoscoming = next((s for s in sections if s.get('sectionId') == 'WHOSCOMING_SECTION'), None)
  342. wc_groups = (whoscoming or {}).get('sectionData', {}).get('reservationGroups', [])
  343. wc_guests = wc_groups[0].get('guests', []) if wc_groups else []
  344. facepile = next((s for s in sections if s.get('sectionId') == 'FACEPILE_SECTION'), None)
  345. fp_guests = (facepile or {}).get('sectionData', {}).get('guests', [])
  346. name = (wc_guests[0].get('name') if wc_guests else None) or (fp_guests[0].get('name') if fp_guests else None)
  347. checkinout = next((s for s in sections if s.get('sectionId') == 'CHECK_IN_CHECK_OUT_SECTION'), None)
  348. ci_out_data = (checkinout or {}).get('sectionData') or {}
  349. action = ci_out_data.get('checkInAction', {})
  350. ci_ts = action.get('checkInTime')
  351. co_ts = action.get('checkOutTime')
  352. ci = self._to_local_date(ci_ts) if ci_ts else None
  353. co = self._to_local_date(co_ts) if co_ts else None
  354. door_code = (ci_out_data.get('airkeyAction') or {}).get('guestPhoneNumberLastFourDigits')
  355. # thread_id is in footerPlacement FLOATINGFOOTER_SECTION, not rootPlacement
  356. footer_sections = det.get('footerPlacement', [])
  357. footer = next((s for s in footer_sections if s.get('sectionId') == 'FLOATINGFOOTER_SECTION'), None)
  358. buttons = ((footer or {}).get('sectionData') or {}).get('buttons', [])
  359. thread_id = None
  360. for btn in buttons:
  361. action = btn.get('buttonAction') or {}
  362. if action.get('__typename') == 'NavigateToMessageGuest':
  363. url = action.get('url', '')
  364. m = __import__('re').search(r'/thread/(\d+)', url)
  365. if m:
  366. thread_id = m.group(1)
  367. break
  368. if ci and co:
  369. self._booked_nets.update(_parse_booked_nets(det, ci, co))
  370. return c, name, ci, co, door_code, thread_id
  371. details_list = await asyncio.gather(*[fetch_details(c) for c in unique_codes])
  372. details = {c: (name, ci, co, door_code, thread_id) for c, name, ci, co, door_code, thread_id in details_list}
  373. return sorted(
  374. [
  375. Reservation(
  376. service='airbnb',
  377. reservation_id=c,
  378. check_in=ci,
  379. check_out=co,
  380. guest_name=name,
  381. door_code=door_code,
  382. thread_id=thread_id,
  383. service_data={k: v for k, v in {'door_code': door_code, 'thread_id': thread_id}.items() if v is not None},
  384. chat_id=thread_id,
  385. )
  386. for c, (name, ci, co, door_code, thread_id) in details.items()
  387. if ci and co
  388. ],
  389. key=lambda r: r.check_in,
  390. )
  391. async def get_booked_nets(self, date_from: str, date_to: str) -> dict[str, int | None]:
  392. """Return {date: net_dollars} for Airbnb-booked dates in range.
  393. Fetches StayHostingDetailsQuery for each reservation and apportions total
  394. host earnings proportionally across nights by per-night list price weight.
  395. Results are cached in _booked_nets; repeated calls (e.g. after get_reservations)
  396. hit the detail cache and make no additional network calls.
  397. """
  398. if is_stale('airbnb'):
  399. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  400. month_list = months_in_range(date_from, date_to)
  401. all_days = await asyncio.gather(*[self._get_month_days(m, y) for m, y in month_list])
  402. booked_codes: dict[str, str] = {} # date → confirmation code
  403. for days in all_days:
  404. for day in days:
  405. d = day.get('day', '')
  406. if d and date_from <= d <= date_to:
  407. code = (day.get('reservationData') or {}).get('confirmationCode', '')
  408. if code:
  409. booked_codes[d] = code
  410. if not booked_codes:
  411. return {}
  412. _sem = asyncio.Semaphore(10)
  413. async def fetch_nets(code: str) -> None:
  414. async with _sem:
  415. det = await self._fetch_one_detail(code)
  416. sections = det.get('rootPlacement', [])
  417. checkinout = next((s for s in sections if s.get('sectionId') == 'CHECK_IN_CHECK_OUT_SECTION'), None)
  418. ci_out_data = (checkinout or {}).get('sectionData') or {}
  419. action = ci_out_data.get('checkInAction', {})
  420. ci_ts = action.get('checkInTime')
  421. co_ts = action.get('checkOutTime')
  422. if ci_ts and co_ts:
  423. ci = self._to_local_date(ci_ts)
  424. co = self._to_local_date(co_ts)
  425. self._booked_nets.update(_parse_booked_nets(det, ci, co))
  426. await asyncio.gather(*[fetch_nets(code) for code in set(booked_codes.values())])
  427. return {d: self._booked_nets.get(d) for d in booked_codes} # int | None per date
  428. async def set_price(self, d: str, price: int) -> None:
  429. price = int(round(price))
  430. if is_stale('airbnb'):
  431. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  432. if (cached := self._cache.get(d)) and cached.price == price:
  433. return
  434. await self._mutate(
  435. 'EditPanelPricingSettingsMutation', _HASHES['EditPanelPricingSettingsMutation'],
  436. {'input': {
  437. 'listingId': self._listing_id,
  438. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  439. 'nightlyPriceAmount': price,
  440. 'turnOnSmartPricing': False,
  441. 'isCalendarV2': True,
  442. }},
  443. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}/nightly-price',
  444. )
  445. self.clear_cache()
  446. _log.info('airbnb set_price date=%s price=$%d', d, price)
  447. async def set_availability(self, d: str, available: bool) -> None:
  448. if is_stale('airbnb'):
  449. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  450. if (cached := self._cache.get(d)) and cached.available == available:
  451. return
  452. body = await self._mutate(
  453. 'EditPanelAvailabilityMutation', _HASHES['EditPanelAvailabilityMutation'],
  454. {'input': {
  455. 'listingId': self._listing_id,
  456. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  457. 'actionType': 'OPEN' if available else 'BLOCK',
  458. }, 'blockNotesEnabled': True},
  459. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}',
  460. )
  461. if errors := body.get('errors'):
  462. _log.error('airbnb set_availability date=%s errors=%s', d, errors)
  463. raise AirbnbAuthError(f'Airbnb set_availability failed for {d}: {errors[0].get("message", errors)}')
  464. self.clear_cache()
  465. _log.info('airbnb set_availability date=%s available=%s', d, available)
  466. def _to_local_date(self, ts: str) -> str:
  467. dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
  468. return dt.astimezone(ZoneInfo(self._tz)).date().isoformat()
  469. async def _fetch_one_detail(self, code: str) -> dict:
  470. if code in self._detail_cache:
  471. return self._detail_cache[code]
  472. try:
  473. resp = await self._gql(
  474. 'StayHostingDetailsQuery', _HASHES['StayHostingDetailsQuery'],
  475. {'viewerTimeZoneOffset': 0, 'requestSource': 'RESERVATION_TAB', 'confirmationCode': code},
  476. f'https://www.airbnb.com/hosting/reservations/details/{code}',
  477. )
  478. except httpx.TimeoutException:
  479. _log.warning('airbnb: StayHostingDetailsQuery timed out for %s — skipping', code)
  480. return {}
  481. det = (
  482. resp.get('data', {}).get('presentation', {})
  483. .get('hostingDetails', {}).get('stayHostingDetails', {})
  484. )
  485. self._detail_cache[code] = det
  486. return det
  487. def _global_thread_id(self, thread_id: str) -> str:
  488. return base64.b64encode(f'MessageThread:{thread_id}'.encode()).decode()
  489. async def get_thread(self, thread_id: str) -> AirbnbThread:
  490. """Fetch a conversation thread and its messages by numeric thread ID."""
  491. if is_stale('airbnb'):
  492. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  493. resp = await self._gql(
  494. 'ViaductGetThreadAndDataQuery', _HASHES['ViaductGetThreadAndDataQuery'],
  495. {
  496. 'globalThreadId': self._global_thread_id(thread_id),
  497. 'numRequestedMessages': 50,
  498. 'getThreadState': True,
  499. 'getParticipants': True,
  500. 'getLastReads': True,
  501. 'getInboxFields': True,
  502. 'getInboxOnlyFields': False,
  503. 'getMessageFields': True,
  504. 'getThreadOnlyFields': True,
  505. 'forceUgcTranslation': False,
  506. 'isNovaLite': False,
  507. 'mockThreadIdentifier': None,
  508. 'mockMessageTestIdentifier': None,
  509. 'mockListFooterSlot': None,
  510. 'forceReturnAllReadReceipts': False,
  511. 'originType': 'USER_INBOX',
  512. 'skipOldMessagePreviewFields': False,
  513. },
  514. f'https://www.airbnb.com/messages/{thread_id}',
  515. )
  516. thread_data = resp.get('data', {}).get('threadData', {})
  517. participants: dict[str, str] = {}
  518. for edge in thread_data.get('participants', {}).get('edges', []):
  519. node = edge.get('node', {})
  520. account_id = node.get('accountId', '')
  521. name = (node.get('enrichedParticipantInfo') or {}).get('name', '')
  522. if account_id and name:
  523. participants[account_id] = name
  524. messages = []
  525. for m in thread_data.get('messageData', {}).get('messages', []):
  526. aid = (m.get('account') or {}).get('accountId', '')
  527. messages.append(AirbnbMessage(
  528. id=m['id'],
  529. created_at_ms=m['createdAtMs'],
  530. body=(((m.get('hydratedContent') or {}).get('content') or {}).get('body')),
  531. body_translated=(((m.get('hydratedContent') or {}).get('content') or {}).get('bodyTranslated')),
  532. sender_account_id=aid,
  533. sender_name=participants.get(aid, 'Airbnb'),
  534. ))
  535. return AirbnbThread(thread_id=thread_id, messages=messages)
  536. async def send_message(self, thread_id: str, body: str) -> None:
  537. """Send a text message to an existing thread."""
  538. if is_stale('airbnb'):
  539. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  540. await self._mutate(
  541. 'CreateBulkMessagesMutation', _HASHES['CreateBulkMessagesMutation'],
  542. {
  543. 'messageThreadId': thread_id,
  544. 'messages': [{
  545. 'content': {'textContent': {'body': body}},
  546. 'uniqueIdentifier': str(uuid.uuid4()),
  547. 'loggingSource': {'sourceType': '', 'sourceId': ''},
  548. 'loggingExtras': {'entries': []},
  549. }],
  550. 'actAs': 'PARTICIPANT',
  551. 'businessJustification': {'feature': 'USER_INBOX'},
  552. 'originType': 'USER_INBOX',
  553. 'senderPlatform': 'WEB',
  554. 'skipOldMessagePreviewFields': False,
  555. },
  556. f'https://www.airbnb.com/messages/{thread_id}',
  557. )
  558. async def get_suggested_prices(self, date_from: str, date_to: str) -> dict[str, int]:
  559. """Airbnb's per-day smart-pricing suggestions (USD). Only includes days where shouldShowTip=True."""
  560. if is_stale('airbnb'):
  561. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  562. resp = await self._gql(
  563. 'getNightlyPriceTips', _HASHES['getNightlyPriceTips'],
  564. {
  565. 'listingId': self._global_id,
  566. 'dateRanges': [{'startDate': date_from, 'endDate': date_to}],
  567. },
  568. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  569. )
  570. tips = (
  571. resp.get('data', {}).get('presentation', {})
  572. .get('pricingGuidance', {}).get('nightlyPriceTip', {})
  573. .get('nightlyPriceTip', {}).get('discretePriceTips', [])
  574. )
  575. return {
  576. t['date']: t['priceTip']['intValue']
  577. for t in tips
  578. if t.get('shouldShowTip') and date_from <= t['date'] <= date_to
  579. }
  580. async def get_service_data(self, date_from: str, date_to: str) -> AirbnbData:
  581. suggested_prices, calendar_events = await asyncio.gather(
  582. self.get_suggested_prices(date_from, date_to),
  583. self.get_calendar_events(),
  584. )
  585. return AirbnbData(suggested_prices=suggested_prices, calendar_events=calendar_events)
  586. async def probe(self) -> None:
  587. from datetime import date
  588. today = date.today().isoformat()
  589. await self.get_calendar(today, today)
  590. async def get_calendar_events(self) -> list[CalendarEvent]:
  591. """Local events and holidays Airbnb shows on the host calendar (holidays, major events, etc.)."""
  592. if is_stale('airbnb'):
  593. raise AirbnbAuthError(f'Airbnb credentials are stale — run: {_AUTH_HINT}')
  594. resp = await self._gql(
  595. 'HostCalendarListingEventsQuery', _HASHES['HostCalendarListingEventsQuery'],
  596. {'listingId': self._global_id},
  597. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  598. )
  599. events = (
  600. resp.get('data', {}).get('presentation', {})
  601. .get('hostCalendarListingEvents', {}).get('events', [])
  602. )
  603. return [
  604. CalendarEvent(
  605. start_date=e['startDate'],
  606. end_date=e['endDate'],
  607. name=e['displayName'],
  608. type=e['type'],
  609. event_id=e['eventId'],
  610. )
  611. for e in events
  612. ]