_airbnb.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import asyncio
  2. import base64
  3. import json
  4. import random
  5. import re
  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 run_refresh_script
  14. from room_cal._utils import get_config
  15. from ._base import ServiceClientBase
  16. from ._month_cache import MonthCache, TTLCache
  17. from ._registry import register_service
  18. from ._utils import month_bounds, months_in_range
  19. from .types import CalendarEvent, DayInfo, ServiceAuthError, Reservation
  20. _log = logging.getLogger(__name__)
  21. @dataclass
  22. class AirbnbMessage:
  23. id: str # global ID (base64)
  24. created_at_ms: str
  25. body: str | None # None for non-text messages (photos, system events, etc.)
  26. body_translated: str | None # Airbnb AI translation; None when not provided
  27. sender_account_id: str
  28. sender_name: str | None = None # resolved from thread participants; None only if resolution failed
  29. @dataclass
  30. class AirbnbThread:
  31. thread_id: str # numeric string, matches Reservation.thread_id
  32. messages: list[AirbnbMessage]
  33. @dataclass
  34. class AirbnbData:
  35. suggested_prices: dict[str, int] # date → Airbnb smart-pricing suggestion (USD)
  36. calendar_events: list[CalendarEvent] # holidays and local demand events
  37. _BASE = 'https://www.airbnb.com/api/v3'
  38. _API_KEY = 'd306zoyjsyarp7ifhu67rjxn52tv0t20'
  39. _CLIENT_VERSION = 'd2b819536102fb310c3d35777257319aee1c7fc1'
  40. _HASHES = {
  41. 'getDLSHostCalendar': '5b153a16f8f392d6d4c6b5ee6259cf7f89ef972e0f79bf3f87753136af9a338c',
  42. 'EditPanelPricingSettingsMutation': 'e27fed4f08dd4ab4c0267c5d6c0a7e4920730deadf48f92feba9b0d08befafa4',
  43. 'EditPanelAvailabilityMutation': '1d321798756bddea88f11bcde6da336f70db64ee74dd8a9a30b91f4c7d6f1b64',
  44. 'StayHostingDetailsQuery': '3641e070c5e57e44ada3d40eca288f5b739ed851c3bf03fe441e13e85dc30f50',
  45. 'getNightlyPriceTips': '07538bf1a5afc8171f1e7443f0007d7f020142fc7ab60df065e7e1edd1a0b29f',
  46. 'HostCalendarListingEventsQuery': '8bfe5f5572a25fdaff5b5790604e1de3aec5f37731fc505684022d590d06e0a8',
  47. 'ViaductGetThreadAndDataQuery': 'be286f1a3810941029d1fd1f5be54df4f5cd146850636a648d6b19406caef21a',
  48. 'CreateBulkMessagesMutation': '2abb1990dbf812cba634f28842fccb09e2a4351b247ea2f87839c20cc91c296a',
  49. }
  50. def _parse_price(s: str) -> float | None:
  51. """Parse a formatted price string like '$143.56' → 143.56, or None on failure."""
  52. try:
  53. return float(s.replace('$', '').replace(',', '').strip())
  54. except (ValueError, AttributeError):
  55. return None
  56. def _detail_section(det: dict, section_id: str, placement: str = 'rootPlacement') -> dict:
  57. """Find a section by ID in a stayHostingDetails placement; {} when absent."""
  58. sections = det.get(placement, [])
  59. return next((s for s in sections if s.get('sectionId') == section_id), None) or {}
  60. def _parse_booked_nets(det: dict, check_in: str, check_out: str) -> dict[str, int]:
  61. """Return {YYYY-MM-DD: net_dollars} for each night of a reservation.
  62. Uses proportional apportionment: net_i = total_host_net * (list_i / sum(list)).
  63. Reads PAYMENTINFO_SECTION from stayHostingDetails (rootPlacement).
  64. Returns {} if the section is missing or the data is malformed.
  65. """
  66. pay = _detail_section(det, 'PAYMENTINFO_SECTION')
  67. if not pay:
  68. return {}
  69. eg = (pay.get('sectionData') or {}).get('hostEarningsGroup', {})
  70. total_net = _parse_price((eg.get('totalLineItem') or {}).get('formattedValue', ''))
  71. if total_net is None:
  72. return {}
  73. nights_item = next(
  74. (li for li in eg.get('lineItems', []) if (li.get('collapsibleLineItemGroup') or {}).get('collapsedLineItems')),
  75. None,
  76. )
  77. if not nights_item:
  78. return {}
  79. weights = [
  80. w for item in nights_item['collapsibleLineItemGroup']['collapsedLineItems']
  81. if (w := _parse_price(item.get('formattedValue', ''))) is not None
  82. ]
  83. ci = date.fromisoformat(check_in)
  84. co = date.fromisoformat(check_out)
  85. nights = [(ci + timedelta(days=i)).isoformat() for i in range((co - ci).days)]
  86. if not weights or len(nights) != len(weights):
  87. return {}
  88. total_weight = sum(weights)
  89. if total_weight == 0:
  90. return {}
  91. return {d: round(total_net * w / total_weight) for d, w in zip(nights, weights)}
  92. class AirbnbAuthError(ServiceAuthError):
  93. pass
  94. def _encode_listing_id(listing_id: str) -> str:
  95. return base64.b64encode(f'StayListing:{listing_id}'.encode()).decode()
  96. def _trace_id() -> str:
  97. return ''.join(random.choices(string.ascii_lowercase + string.digits, k=28))
  98. @register_service('airbnb')
  99. class _AirbnbClient(ServiceClientBase):
  100. service_name = 'AirBnB'
  101. auth_error_cls = AirbnbAuthError
  102. def __init__(self, cookies: str, listing_id: str, tz: str = 'America/Los_Angeles'):
  103. super().__init__()
  104. self._cookies = cookies
  105. self._listing_id = listing_id
  106. self._global_id = _encode_listing_id(listing_id)
  107. self._tz = tz
  108. # Tracks months where we've seen at least one booked day; survives clear_cache() so we can
  109. # detect when a freshly-fetched month drops from N booked days to 0 (stale replica signal).
  110. self._had_bookings: set[tuple[int, int]] = set()
  111. self._months: MonthCache[list[dict]] = MonthCache(
  112. lambda m, y: self._fetch_month_days(m, y),
  113. suspect=self._suspect_days,
  114. revalidate=self._revalidate_month,
  115. on_fetch=self._note_bookings,
  116. on_evict=self._evict_derived,
  117. label='Airbnb',
  118. log=_log,
  119. )
  120. self._details: TTLCache[dict] = TTLCache()
  121. # per-client cap on concurrent detail fetches; tuned against the live API
  122. self._detail_sem = asyncio.Semaphore(10)
  123. self._http = httpx.AsyncClient(timeout=10.0)
  124. self._booked_nets: dict[str, int] = {}
  125. @classmethod
  126. def from_env(cls) -> '_AirbnbClient':
  127. env = cls._read_env()
  128. cls._require_env(env, 'AIRBNB_COOKIES')
  129. listing_id = get_config().services['airbnb'].room_id
  130. if not listing_id:
  131. raise ValueError('airbnb.room_id must be set in config.json')
  132. return cls(cookies=env['AIRBNB_COOKIES'], listing_id=listing_id)
  133. def clear_cache(self) -> None:
  134. super().clear_cache()
  135. self._details.clear()
  136. self._booked_nets.clear()
  137. def _apply_env(self, env: dict[str, str]) -> None:
  138. self._cookies = env.get('AIRBNB_COOKIES', self._cookies)
  139. @staticmethod
  140. def refresh_credentials() -> None:
  141. run_refresh_script('refresh-airbnb', service_name='Airbnb',
  142. auth_error_cls=AirbnbAuthError, extra_env={'HEADLESS': '1'})
  143. def _headers(self, referer: str, extra: dict | None = None) -> dict[str, str]:
  144. h = {
  145. 'Cookie': self._cookies,
  146. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:152.0) Gecko/20100101 Firefox/152.0',
  147. 'Accept': '*/*',
  148. 'Accept-Language': 'en-US,en;q=0.9',
  149. 'Content-Type': 'application/json',
  150. 'Referer': referer,
  151. 'Sec-Fetch-Mode': 'cors',
  152. 'Sec-Fetch-Dest': 'empty',
  153. 'Sec-Fetch-Site': 'same-origin',
  154. 'X-Airbnb-API-Key': _API_KEY,
  155. 'X-Airbnb-GraphQL-Platform': 'web',
  156. 'X-Airbnb-GraphQL-Platform-Client': 'minimalist-niobe',
  157. 'X-Airbnb-Supports-Airlock-V2': 'true',
  158. 'X-Niobe-Short-Circuited': 'true',
  159. 'X-Client-Version': _CLIENT_VERSION,
  160. 'X-CSRF-Token': '',
  161. 'X-CSRF-Without-Token': '1',
  162. 'x-airbnb-client-trace-id': _trace_id(),
  163. 'x-client-request-id': _trace_id(),
  164. 'x-airbnb-network-log-link': _trace_id(),
  165. }
  166. if extra:
  167. h.update(extra)
  168. return h
  169. def _auth_shaped(self, r: httpx.Response) -> bool:
  170. # Airbnb also signals session expiry as GQL errors on HTTP 200; route those
  171. # through the base's refresh → retry-once → stale sequence too.
  172. if super()._auth_shaped(r):
  173. return True
  174. if r.status_code != 200:
  175. return False
  176. try:
  177. body = r.json()
  178. except ValueError:
  179. return False
  180. return any(
  181. e.get('extensions', {}).get('response', {}).get('status') in (400, 401, 403)
  182. for e in body.get('errors', [])
  183. )
  184. async def _gql(self, op: str, h: str, variables: dict, referer: str) -> dict:
  185. url = f'{_BASE}/{op}/{h}'
  186. params = {
  187. 'operationName': op,
  188. 'locale': 'en',
  189. 'currency': 'USD',
  190. 'variables': json.dumps(variables),
  191. 'extensions': json.dumps({'persistedQuery': {'version': 1, 'sha256Hash': h}}),
  192. }
  193. async def _attempt() -> httpx.Response:
  194. return await self._http.get(url, params=params, headers=self._headers(referer))
  195. r = await self._request(_attempt, op=op)
  196. return r.json()
  197. async def _mutate(self, op: str, h: str, variables: dict, referer: str) -> dict:
  198. url = f'{_BASE}/{op}/{h}?operationName={op}&locale=en&currency=USD'
  199. payload = {'operationName': op, 'variables': variables,
  200. 'extensions': {'persistedQuery': {'version': 1, 'sha256Hash': h}}}
  201. async def _attempt() -> httpx.Response:
  202. return await self._http.post(
  203. url, json=payload,
  204. headers=self._headers(referer, {'Origin': 'https://www.airbnb.com'}),
  205. )
  206. r = await self._request(_attempt, op=op)
  207. return r.json()
  208. async def _fetch_month_days(self, month: int, year: int) -> list[dict]:
  209. start, end = month_bounds(month, year)
  210. variables = {
  211. 'listingId': self._global_id,
  212. 'startDate': start,
  213. 'endDate': end,
  214. 'hostCalendarViewType': 'MONTH_VIEW',
  215. 'lensTypes': ['NOTE', 'PRICE', 'PROMOTION'],
  216. 'timeZone': self._tz,
  217. 'localizationContext': {'timeZone': self._tz, 'firstDayOfWeek': 0},
  218. 'hostCalendarSectionTypes': ['MAIN_VIEW'],
  219. 'readConsistency': 'EVENTUAL',
  220. }
  221. referer = f'https://www.airbnb.com/multicalendar/{self._listing_id}'
  222. resp = await self._gql('getDLSHostCalendar', _HASHES['getDLSHostCalendar'], variables, referer)
  223. section = (
  224. resp.get('data', {}).get('presentation', {})
  225. .get('hostCalendar', {}).get('sections', {})
  226. .get('calendarGridViewSection')
  227. ) or {}
  228. return section.get('days', [])
  229. def _suspect_days(self, key: tuple[int, int], days: list[dict]) -> bool:
  230. return not days or not any(d.get('priceData', {}).get('price') is not None for d in days)
  231. def _revalidate_month(self, key: tuple[int, int], cached: list[dict]) -> bool:
  232. # If we've seen bookings for this month before but the cache now shows none,
  233. # the data is likely from a stale eventual-consistency replica — force a refetch.
  234. if key in self._had_bookings and not any(d.get('reservationData') for d in cached):
  235. month, year = key
  236. _log.warning(
  237. 'Airbnb: %d-%02d cache shows 0 booked days but month had bookings; forcing refetch',
  238. year, month,
  239. )
  240. return False
  241. return True
  242. def _note_bookings(self, key: tuple[int, int], result: list[dict], revalidation_failed: bool) -> None:
  243. if any(d.get('reservationData') for d in result):
  244. self._had_bookings.add(key)
  245. elif revalidation_failed:
  246. # Forced refetch confirmed no bookings — stop guarding this month
  247. self._had_bookings.discard(key)
  248. def _month_day_infos(self, days: list[dict]) -> dict[str, DayInfo]:
  249. return {
  250. d: DayInfo(
  251. date=d,
  252. price=day.get('priceData', {}).get('price'),
  253. available=day.get('available', False),
  254. booked=day.get('reservationData') is not None,
  255. )
  256. for day in days
  257. if (d := day.get('day', ''))
  258. }
  259. async def get_reservations(self, date_from: str, date_to: str) -> list[Reservation]:
  260. self._check_fresh()
  261. month_list = months_in_range(date_from, date_to)
  262. all_days = await asyncio.gather(*[self._months.get(m, y) for m, y in month_list])
  263. booked: dict[str, str] = {}
  264. for days in all_days:
  265. for day in days:
  266. d = day.get('day', '')
  267. res_data = day.get('reservationData')
  268. if res_data and date_from <= d <= date_to:
  269. booked[d] = res_data.get('confirmationCode', '')
  270. if not booked:
  271. return []
  272. unique_codes = set(booked.values())
  273. async def fetch_details(c: str) -> tuple[str, str | None, str | None, str | None, str | None, str | None]:
  274. det = await self._fetch_one_detail(c)
  275. wc_groups = (_detail_section(det, 'WHOSCOMING_SECTION').get('sectionData') or {}).get('reservationGroups', [])
  276. wc_guests = wc_groups[0].get('guests', []) if wc_groups else []
  277. fp_guests = (_detail_section(det, 'FACEPILE_SECTION').get('sectionData') or {}).get('guests', [])
  278. name = (wc_guests[0].get('name') if wc_guests else None) or (fp_guests[0].get('name') if fp_guests else None)
  279. ci, co = self._detail_checkin_checkout(det)
  280. ci_out_data = _detail_section(det, 'CHECK_IN_CHECK_OUT_SECTION').get('sectionData') or {}
  281. door_code = (ci_out_data.get('airkeyAction') or {}).get('guestPhoneNumberLastFourDigits')
  282. # thread_id is in footerPlacement FLOATINGFOOTER_SECTION, not rootPlacement
  283. footer = _detail_section(det, 'FLOATINGFOOTER_SECTION', 'footerPlacement')
  284. buttons = (footer.get('sectionData') or {}).get('buttons', [])
  285. thread_id = None
  286. for btn in buttons:
  287. action = btn.get('buttonAction') or {}
  288. if action.get('__typename') == 'NavigateToMessageGuest':
  289. url = action.get('url', '')
  290. m = re.search(r'/thread/(\d+)', url)
  291. if m:
  292. thread_id = m.group(1)
  293. break
  294. if ci and co:
  295. self._booked_nets.update(_parse_booked_nets(det, ci, co))
  296. return c, name, ci, co, door_code, thread_id
  297. details_list = await asyncio.gather(*[fetch_details(c) for c in unique_codes])
  298. details = {c: (name, ci, co, door_code, thread_id) for c, name, ci, co, door_code, thread_id in details_list}
  299. return sorted(
  300. [
  301. Reservation(
  302. service='airbnb',
  303. reservation_id=c,
  304. check_in=ci,
  305. check_out=co,
  306. guest_name=name,
  307. door_code=door_code,
  308. thread_id=thread_id,
  309. service_data={k: v for k, v in {'door_code': door_code, 'thread_id': thread_id}.items() if v is not None},
  310. chat_id=thread_id,
  311. )
  312. for c, (name, ci, co, door_code, thread_id) in details.items()
  313. if ci and co
  314. ],
  315. key=lambda r: r.check_in,
  316. )
  317. async def get_booked_nets(self, date_from: str, date_to: str) -> dict[str, int | None]:
  318. """Return {date: net_dollars} for Airbnb-booked dates in range.
  319. Fetches StayHostingDetailsQuery for each reservation and apportions total
  320. host earnings proportionally across nights by per-night list price weight.
  321. Results are cached in _booked_nets; repeated calls (e.g. after get_reservations)
  322. hit the detail cache and make no additional network calls.
  323. """
  324. self._check_fresh()
  325. month_list = months_in_range(date_from, date_to)
  326. all_days = await asyncio.gather(*[self._months.get(m, y) for m, y in month_list])
  327. booked_codes: dict[str, str] = {} # date → confirmation code
  328. for days in all_days:
  329. for day in days:
  330. d = day.get('day', '')
  331. if d and date_from <= d <= date_to:
  332. code = (day.get('reservationData') or {}).get('confirmationCode', '')
  333. if code:
  334. booked_codes[d] = code
  335. if not booked_codes:
  336. return {}
  337. async def fetch_nets(code: str) -> None:
  338. det = await self._fetch_one_detail(code)
  339. ci, co = self._detail_checkin_checkout(det)
  340. if ci and co:
  341. self._booked_nets.update(_parse_booked_nets(det, ci, co))
  342. await asyncio.gather(*[fetch_nets(code) for code in set(booked_codes.values())])
  343. return {d: self._booked_nets.get(d) for d in booked_codes} # int | None per date
  344. async def set_price(self, d: str, price: int) -> None:
  345. price = int(round(price))
  346. self._check_fresh()
  347. if (cached := self._cache.get(d)) and cached.price == price:
  348. return
  349. await self._mutate(
  350. 'EditPanelPricingSettingsMutation', _HASHES['EditPanelPricingSettingsMutation'],
  351. {'input': {
  352. 'listingId': self._listing_id,
  353. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  354. 'nightlyPriceAmount': price,
  355. 'turnOnSmartPricing': False,
  356. 'isCalendarV2': True,
  357. }},
  358. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}/nightly-price',
  359. )
  360. self.clear_cache()
  361. _log.info('airbnb set_price date=%s price=$%d', d, price)
  362. async def set_availability(self, d: str, available: bool) -> None:
  363. self._check_fresh()
  364. if (cached := self._cache.get(d)) and cached.available == available:
  365. return
  366. body = await self._mutate(
  367. 'EditPanelAvailabilityMutation', _HASHES['EditPanelAvailabilityMutation'],
  368. {'input': {
  369. 'listingId': self._listing_id,
  370. 'selectedDateRanges': [{'startDate': d, 'endDate': d}],
  371. 'actionType': 'OPEN' if available else 'BLOCK',
  372. }, 'blockNotesEnabled': True},
  373. f'https://www.airbnb.com/multicalendar/{self._listing_id}/edit-selected-dates/{d}/{d}',
  374. )
  375. if errors := body.get('errors'):
  376. _log.error('airbnb set_availability date=%s errors=%s', d, errors)
  377. raise AirbnbAuthError(f'Airbnb set_availability failed for {d}: {errors[0].get("message", errors)}')
  378. self.clear_cache()
  379. _log.info('airbnb set_availability date=%s available=%s', d, available)
  380. def _to_local_date(self, ts: str) -> str:
  381. dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
  382. return dt.astimezone(ZoneInfo(self._tz)).date().isoformat()
  383. def _detail_checkin_checkout(self, det: dict) -> tuple[str | None, str | None]:
  384. """Local check-in/check-out dates from a detail's CHECK_IN_CHECK_OUT_SECTION."""
  385. data = _detail_section(det, 'CHECK_IN_CHECK_OUT_SECTION').get('sectionData') or {}
  386. action = data.get('checkInAction', {})
  387. ci_ts = action.get('checkInTime')
  388. co_ts = action.get('checkOutTime')
  389. return (self._to_local_date(ci_ts) if ci_ts else None,
  390. self._to_local_date(co_ts) if co_ts else None)
  391. async def _fetch_one_detail(self, code: str) -> dict:
  392. if (cached := self._details.get(code)) is not None:
  393. return cached
  394. try:
  395. async with self._detail_sem:
  396. resp = await self._gql(
  397. 'StayHostingDetailsQuery', _HASHES['StayHostingDetailsQuery'],
  398. {'viewerTimeZoneOffset': 0, 'requestSource': 'RESERVATION_TAB', 'confirmationCode': code},
  399. f'https://www.airbnb.com/hosting/reservations/details/{code}',
  400. )
  401. except httpx.TimeoutException:
  402. _log.warning('airbnb: StayHostingDetailsQuery timed out for %s — skipping', code)
  403. return {}
  404. det = (
  405. resp.get('data', {}).get('presentation', {})
  406. .get('hostingDetails', {}).get('stayHostingDetails', {})
  407. )
  408. self._details.set(code, det)
  409. return det
  410. def _detail_is_canceled(self, det: dict) -> bool | None:
  411. """Read cancellation status from a detail's WHOSCOMING_SECTION, if present."""
  412. wc_groups = (_detail_section(det, 'WHOSCOMING_SECTION').get('sectionData') or {}).get('reservationGroups', [])
  413. if not wc_groups:
  414. return None
  415. return bool(wc_groups[0].get('isCanceled'))
  416. async def check_reservation_status(self, reservation_id: str) -> bool | None:
  417. """Return True if `reservation_id` is confirmed canceled, None if status can't be determined.
  418. Queries StayHostingDetailsQuery directly by confirmation code — independent of the
  419. calendar/MonthCache, and reuses the same _details TTL cache get_booked_nets/get_reservations
  420. populate, so a prior fetch of the same reservation costs no extra network call. Any failure
  421. (stale credentials, timeout, unparseable response) falls back to None rather than raising —
  422. callers treat this as a best-effort check, not a required one.
  423. """
  424. try:
  425. self._check_fresh()
  426. det = await self._fetch_one_detail(reservation_id)
  427. if not det:
  428. return None
  429. return self._detail_is_canceled(det)
  430. except Exception:
  431. _log.warning('airbnb: check_reservation_status failed for %s', reservation_id, exc_info=True)
  432. return None
  433. def _global_thread_id(self, thread_id: str) -> str:
  434. return base64.b64encode(f'MessageThread:{thread_id}'.encode()).decode()
  435. async def get_thread(self, thread_id: str) -> AirbnbThread:
  436. """Fetch a conversation thread and its messages by numeric thread ID."""
  437. self._check_fresh()
  438. resp = await self._gql(
  439. 'ViaductGetThreadAndDataQuery', _HASHES['ViaductGetThreadAndDataQuery'],
  440. {
  441. 'globalThreadId': self._global_thread_id(thread_id),
  442. 'numRequestedMessages': 50,
  443. 'getThreadState': True,
  444. 'getParticipants': True,
  445. 'getLastReads': True,
  446. 'getInboxFields': True,
  447. 'getInboxOnlyFields': False,
  448. 'getMessageFields': True,
  449. 'getThreadOnlyFields': True,
  450. 'forceUgcTranslation': False,
  451. 'isNovaLite': False,
  452. 'mockThreadIdentifier': None,
  453. 'mockMessageTestIdentifier': None,
  454. 'mockListFooterSlot': None,
  455. 'forceReturnAllReadReceipts': False,
  456. 'originType': 'USER_INBOX',
  457. 'skipOldMessagePreviewFields': False,
  458. },
  459. f'https://www.airbnb.com/messages/{thread_id}',
  460. )
  461. thread_data = resp.get('data', {}).get('threadData', {})
  462. participants: dict[str, str] = {}
  463. for edge in thread_data.get('participants', {}).get('edges', []):
  464. node = edge.get('node', {})
  465. account_id = node.get('accountId', '')
  466. name = (node.get('enrichedParticipantInfo') or {}).get('name', '')
  467. if account_id and name:
  468. participants[account_id] = name
  469. messages = []
  470. for m in thread_data.get('messageData', {}).get('messages', []):
  471. aid = (m.get('account') or {}).get('accountId', '')
  472. messages.append(AirbnbMessage(
  473. id=m['id'],
  474. created_at_ms=m['createdAtMs'],
  475. body=(((m.get('hydratedContent') or {}).get('content') or {}).get('body')),
  476. body_translated=(((m.get('hydratedContent') or {}).get('content') or {}).get('bodyTranslated')),
  477. sender_account_id=aid,
  478. sender_name=participants.get(aid, 'Airbnb'),
  479. ))
  480. return AirbnbThread(thread_id=thread_id, messages=messages)
  481. async def send_message(self, thread_id: str, body: str) -> None:
  482. """Send a text message to an existing thread."""
  483. self._check_fresh()
  484. await self._mutate(
  485. 'CreateBulkMessagesMutation', _HASHES['CreateBulkMessagesMutation'],
  486. {
  487. 'messageThreadId': thread_id,
  488. 'messages': [{
  489. 'content': {'textContent': {'body': body}},
  490. 'uniqueIdentifier': str(uuid.uuid4()),
  491. 'loggingSource': {'sourceType': '', 'sourceId': ''},
  492. 'loggingExtras': {'entries': []},
  493. }],
  494. 'actAs': 'PARTICIPANT',
  495. 'businessJustification': {'feature': 'USER_INBOX'},
  496. 'originType': 'USER_INBOX',
  497. 'senderPlatform': 'WEB',
  498. 'skipOldMessagePreviewFields': False,
  499. },
  500. f'https://www.airbnb.com/messages/{thread_id}',
  501. )
  502. async def get_suggested_prices(self, date_from: str, date_to: str) -> dict[str, int]:
  503. """Airbnb's per-day smart-pricing suggestions (USD). Only includes days where shouldShowTip=True."""
  504. self._check_fresh()
  505. resp = await self._gql(
  506. 'getNightlyPriceTips', _HASHES['getNightlyPriceTips'],
  507. {
  508. 'listingId': self._global_id,
  509. 'dateRanges': [{'startDate': date_from, 'endDate': date_to}],
  510. },
  511. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  512. )
  513. tips = (
  514. resp.get('data', {}).get('presentation', {})
  515. .get('pricingGuidance', {}).get('nightlyPriceTip', {})
  516. .get('nightlyPriceTip', {}).get('discretePriceTips', [])
  517. )
  518. return {
  519. t['date']: t['priceTip']['intValue']
  520. for t in tips
  521. if t.get('shouldShowTip') and date_from <= t['date'] <= date_to
  522. }
  523. async def get_service_data(self, date_from: str, date_to: str) -> AirbnbData:
  524. suggested_prices, calendar_events = await asyncio.gather(
  525. self.get_suggested_prices(date_from, date_to),
  526. self.get_calendar_events(),
  527. )
  528. return AirbnbData(suggested_prices=suggested_prices, calendar_events=calendar_events)
  529. async def get_calendar_events(self) -> list[CalendarEvent]:
  530. """Local events and holidays Airbnb shows on the host calendar (holidays, major events, etc.)."""
  531. self._check_fresh()
  532. resp = await self._gql(
  533. 'HostCalendarListingEventsQuery', _HASHES['HostCalendarListingEventsQuery'],
  534. {'listingId': self._global_id},
  535. f'https://www.airbnb.com/multicalendar/{self._listing_id}',
  536. )
  537. events = (
  538. resp.get('data', {}).get('presentation', {})
  539. .get('hostCalendarListingEvents', {}).get('events', [])
  540. )
  541. return [
  542. CalendarEvent(
  543. start_date=e['startDate'],
  544. end_date=e['endDate'],
  545. name=e['displayName'],
  546. type=e['type'],
  547. event_id=e['eventId'],
  548. )
  549. for e in events
  550. ]
  551. # ── har_audit.py drift manifest ─────────────────────────────────────────────
  552. # Auditable identifiers for scripts/har_audit.py. References _API_KEY,
  553. # _CLIENT_VERSION, _HASHES above rather than duplicating literals — this is
  554. # the only copy.
  555. DRIFT_MANIFEST = {
  556. 'domain': 'www.airbnb.com',
  557. 'api_key': _API_KEY,
  558. 'client_version': _CLIENT_VERSION,
  559. 'ops': {
  560. 'getDLSHostCalendar': {
  561. 'hash': _HASHES['getDLSHostCalendar'],
  562. 'hint': 'load the multicalendar page',
  563. },
  564. 'EditPanelPricingSettingsMutation': {
  565. 'hash': _HASHES['EditPanelPricingSettingsMutation'],
  566. 'hint': 'change a price on any date in the multicalendar',
  567. },
  568. 'EditPanelAvailabilityMutation': {
  569. 'hash': _HASHES['EditPanelAvailabilityMutation'],
  570. 'hint': 'block or unblock a date in the multicalendar',
  571. },
  572. 'StayHostingDetailsQuery': {
  573. 'hash': _HASHES['StayHostingDetailsQuery'],
  574. 'hint': 'open any reservation detail page',
  575. },
  576. 'getNightlyPriceTips': {
  577. 'hash': _HASHES['getNightlyPriceTips'],
  578. 'hint': 'load the multicalendar page (fires automatically)',
  579. },
  580. 'HostCalendarListingEventsQuery': {
  581. 'hash': _HASHES['HostCalendarListingEventsQuery'],
  582. 'hint': 'load the multicalendar page (fires automatically)',
  583. },
  584. 'ViaductGetThreadAndDataQuery': {
  585. 'hash': _HASHES['ViaductGetThreadAndDataQuery'],
  586. 'hint': 'open any guest message thread',
  587. },
  588. 'CreateBulkMessagesMutation': {
  589. 'hash': _HASHES['CreateBulkMessagesMutation'],
  590. 'hint': 'send a message in any thread',
  591. },
  592. },
  593. }