3
0

5 کامیت‌ها 243e6b82a0 ... 8862f8d8fd

نویسنده SHA1 پیام تاریخ
  ZiB 8862f8d8fd remove: unmaintained MCP server 2 هفته پیش
  ZiB c7ad494408 feat: authoritative per-reservation-ID status check 2 هفته پیش
  ZiB 0df95431fe fix: update stale Booking.com GraphQL client-version and timeout 2 هفته پیش
  ZiB fea850b546 fix: handle remembered-account screen in Airbnb auto-login 2 هفته پیش
  ZiB 23def3c05a fix: update stale Airbnb GQL hashes and client version 2 هفته پیش

+ 1 - 1
README.md

@@ -1,6 +1,6 @@
 # room-cal
 
-A self-hosted calendar management tool for short-term rental hosts. It syncs pricing, availability, reservations, and discounts between a local CalDAV calendar and external booking platforms (Airbnb, Booking.com). A FastAPI HTTP server exposes the data to a Vue-based web calendar, and a FastMCP server exposes health checks to AI assistants.
+A self-hosted calendar management tool for short-term rental hosts. It syncs pricing, availability, reservations, and discounts between a local CalDAV calendar and external booking platforms (Airbnb, Booking.com). A FastAPI HTTP server exposes the data to a Vue-based web calendar.
 
 ---
 

+ 1 - 1
docker/Dockerfile

@@ -34,7 +34,7 @@ RUN chmod +x /entrypoint.sh
 COPY room_cal/ ./room_cal/
 RUN mkdir /root/.local && ln -s /config /root/.local/room_cal \
     && cd room_cal/vue && npm run build \
-    && uv sync --group api --group mcp --no-dev --frozen
+    && uv sync --group api --no-dev --frozen
 
 # Exec
 ENTRYPOINT ["/usr/bin/tini", "--"]

+ 1 - 19
docker/README.md

@@ -1,7 +1,7 @@
 # Docker
 
 ## podman-compose
-### API & MCP
+### API
 
 ```bash
 podman-compose -f room_cal/docker/compose.yaml up -d
@@ -50,14 +50,6 @@ podman run --rm -it -p 8000:8000 -v ./config:/config $IMG_NAME /entrypoint.sh ca
 
 Serves only the `/calc/*` endpoints and the `calc.html` UI at `/`. No Store, CalDAV, or service-API credentials needed — only the `services` and `global.taxes` sections of `config.json` are read.
 
-### MCP
-
-```bash
-podman run --rm -it -p 8001:8001 -v ./config:/config $IMG_NAME /entrypoint.sh mcp
-```
-
-The `./config` volume must contain `config.json` (start with a copy of `room_cal/config.json`). CalDAV credentials go in `config.json` under `store.caldav` — there is no separate `caldav.env`. Service API credential files (`airbnb.env`, `booking.env`) live there too, once generated, so it needs a writeable mount
-
 Placing a `uvicorn_log.json` in `./config` overrides the default log config
 
 ## Environment variables
@@ -88,13 +80,3 @@ Default entrypoint. Variable defaults are baked in; override with environment va
 ### Calc service
 
 Pass `calc` as the first argument to `entrypoint.sh`. Uses the same `API_HOST`, `API_PORT`, and `LOG_LEVEL` variables as the API service. Only `services` and `global.taxes` are read from `config.json` — no store, auth, or service-API config required.
-
-### MCP service
-
-Pass `mcp` as the first argument to `entrypoint.sh`. Variable defaults are baked in; override with environment variables if needed
-
-| Variable | Default | Notes |
-|----------|---------|-------|
-| `FASTMCP_HOST` | `0.0.0.0` | MCP server bind address |
-| `FASTMCP_PORT` | `8001` | MCP server bind port |
-| `FASTMCP_LOG_LEVEL` | `INFO` | MCP log level |

+ 0 - 12
docker/compose.yaml

@@ -30,15 +30,3 @@ services:
     environment:
       - TZ=${TZ:-}
       - API_PORT=${CALC_PORT:-8002}
-
-  mcp:
-    build:
-      context: ..
-      dockerfile: docker/Dockerfile
-    command: ["/entrypoint.sh", "mcp"]
-    ports:
-      - "${MCP_PORT:-8001}:${MCP_PORT:-8001}"
-    volumes:
-      - ./config:/config
-    environment:
-      - TZ=${TZ:-}

+ 0 - 14
docker/entrypoint.sh

@@ -19,20 +19,6 @@ export ROOM_CAL_API_URL
 
 SERVICE="${1:-api}"
 
-# MCP
-if [ "$SERVICE" = "mcp" ]; then
-  : "${FASTMCP_HOST:=0.0.0.0}"
-  : "${FASTMCP_PORT:=8001}"
-  : "${FASTMCP_LOG_LEVEL:=INFO}"
-  : "${FASTMCP_ENABLE_RICH_LOGGING:=false}"
-  : "${FASTMCP_ENABLE_RICH_TRACEBACKS:=false}"
-  export FASTMCP_TRANSPORT=http
-  export FASTMCP_HOST FASTMCP_PORT FASTMCP_LOG_LEVEL
-  export FASTMCP_ENABLE_RICH_LOGGING FASTMCP_ENABLE_RICH_TRACEBACKS
-
-  exec room-mcp
-fi
-
 # Shared API config
 : "${API_HOST:=0.0.0.0}"
 : "${API_PORT:=8000}"

+ 1 - 5
pyproject.toml

@@ -19,19 +19,15 @@ refresh-airbnb = "room_cal.service_api._scripts:refresh_airbnb_cli"
 refresh-booking = "room_cal.service_api._scripts:refresh_booking_cli"
 room-cal = "room_cal.actions._cli:main"
 room-api = "room_cal.api._server:main"
-room-mcp = "room_cal.mcp._server:main"
 
 [dependency-groups]
 api = [
   "fastapi>=0.115",
   "uvicorn[standard]>=0.30",
-]
-mcp = [
-  "fastmcp>=2.0",
+  "pyjwt[crypto]>=2.0",
 ]
 dev = [
   {include-group = "api"},
-  {include-group = "mcp"},
   "pytest",
   "pytest-asyncio",
   "pytest-xdist",

+ 73 - 8
room_cal/actions/fetch_reservations.py

@@ -27,6 +27,42 @@ def _source_matches(stored: dict, domain: str, key: str, id_: str) -> bool:
   )
 
 
+# Delay before the confirmation re-query, mirroring MonthCache's empty/priceless
+# suspect-retry delay — long enough for a stale read-replica lag to clear.
+_CONFIRM_RETRY_DELAY = 1.0
+
+
+async def _confirm_missing(
+  api: 'ServiceAPI',
+  svc: str,
+  date_from: date,
+  date_to: date,
+  missing_ids: set[str],
+) -> bool:
+  """Re-query a service's reservation list before trusting that stored IDs are gone.
+
+  In slow season a service legitimately having 0-1 bookings for a window is no
+  longer rare, so "returned none, N stored" can't be treated as inherently
+  suspicious on its own. A fresh re-query of the same endpoint — not the
+  calendar, which can be reading from the same cached month payload the first
+  get_reservations call was parsed from (Airbnb) or its own eventual-consistency
+  window (Booking) — catches a read that landed on a stale replica or lost a
+  race with the service's own write path, without introducing a second,
+  unverified data source.
+  """
+  try:
+    client = api.client(svc)
+  except (KeyError, AttributeError):
+    return False
+  await asyncio.sleep(_CONFIRM_RETRY_DELAY)
+  try:
+    reservations = await client.get_reservations(date_from.isoformat(), date_to.isoformat())
+  except Exception:
+    return False
+  still_present = {r.reservation_id for r in reservations} & missing_ids
+  return not still_present
+
+
 async def _remove_reservation_closures(
   closed: Closed,
   checkin_date: date,
@@ -86,6 +122,7 @@ async def fetch_reservations(
     if svc:
       stored_by_service[svc] = stored_by_service.get(svc, 0) + 1
   guarded_services: set[str] = set()
+  guarded_ids: set[str] = set()
   for svc, count in stored_by_service.items():
     if svc in errored_services:
       _log.error(
@@ -94,19 +131,47 @@ async def fetch_reservations(
       )
       guarded_services.add(svc)
     elif svc not in returned_services:
-      _log.error(
-        'fetch_reservations: %r returned 0 reservations but %d are stored; '
-        'skipping deletion(s) — verify service is healthy',
-        svc, count,
-      )
-      guarded_services.add(svc)
+      missing_ids = {
+        rid for rid, (_, data) in existing_by_id.items() if data.get('service') == svc
+      }
+      # Per-ID authoritative check first (StayHostingDetailsQuery's isCanceled for Airbnb,
+      # reservationDetails' is_cancelled for Booking) — a service legitimately having 0-1
+      # bookings in a window is no longer rare in slow season, so "returned none" alone can't
+      # justify blanket-guarding the whole service. hasattr-dispatched: a client without the
+      # capability (api.check_reservation_status returns None for every id) falls straight
+      # through to the bulk re-query fallback below, unchanged from before.
+      check_status = getattr(api, 'check_reservation_status', None)
+      confirmed_canceled: set[str] = set()
+      unresolved: set[str] = set()
+      for rid in missing_ids:
+        status = await check_status(svc, rid) if check_status else None
+        if status:
+          confirmed_canceled.add(rid)
+        else:
+          unresolved.add(rid)
+      if unresolved and await _confirm_missing(api, svc, start_date, end_date, unresolved):
+        confirmed_canceled |= unresolved
+        unresolved = set()
+      if confirmed_canceled:
+        _log.info(
+          'fetch_reservations: %r returned 0 reservations; %d of %d stored reservation(s) '
+          'confirmed genuinely gone — proceeding with deletion(s)',
+          svc, len(confirmed_canceled), count,
+        )
+      if unresolved:
+        _log.error(
+          'fetch_reservations: %r returned 0 reservations; %d of %d stored reservation(s) '
+          'could not be confirmed gone — skipping deletion(s) — verify service is healthy',
+          svc, len(unresolved), count,
+        )
+        guarded_ids.update(unresolved)
 
   # Mass-deletion guard: cancel a service's deletions when a single run would
   # remove more than _MAX_DELETIONS_PER_RUN reservations.
   pending_deletions: dict[str, int] = {}
   for rid, (_, data) in existing_by_id.items():
     svc = data.get('service', '')
-    if svc in guarded_services or rid in service_ids:
+    if svc in guarded_services or rid in guarded_ids or rid in service_ids:
       continue
     pending_deletions[svc] = pending_deletions.get(svc, 0) + 1
   for svc, count in pending_deletions.items():
@@ -121,7 +186,7 @@ async def fetch_reservations(
   changed = False
 
   for rid, (event, data) in existing_by_id.items():
-    if data.get('service') in guarded_services:
+    if data.get('service') in guarded_services or rid in guarded_ids:
       continue
     if rid not in service_ids:
       changed = True

+ 0 - 304
room_cal/mcp/__init__.py

@@ -1,304 +0,0 @@
-import asyncio
-from datetime import date
-from fastmcp import FastMCP
-from room_cal._utils import services as _services, service_name as _service_name, safe_json_loads, iter_dates
-from room_cal._health import store_check, credentials_checks
-from room_cal.pricing import CalPrice
-from room_cal.pricing.calc import (
-  net_to_list, list_to_net, list_to_retail,
-  retail_to_list, net_to_retail, retail_to_net,
-)
-from room_cal.reservations import Reservation
-from room_cal.closed import Closed
-from room_cal.discount import Discount
-
-mcp = FastMCP('room_cal')
-
-_CALC_FROM = {
-  'net_to_list': 'net',   'net_to_retail': 'net',
-  'list_to_net': 'list',  'list_to_retail': 'list',
-  'retail_to_list': 'retail', 'retail_to_net': 'retail',
-}
-_API_SOURCE = {'domain': 'mcp', 'id': ''}
-
-
-@mcp.tool()
-async def health_check() -> dict:
-  """Check store connectivity and service credential validity. Returns {store_connected, credentials}."""
-  store_result, creds = await asyncio.gather(
-    store_check(),
-    credentials_checks(),
-  )
-  return {
-    'store_connected': store_result.to_dict(),
-    'credentials': {k: v.to_dict() for k, v in creds.items()},
-  }
-
-
-@mcp.tool()
-async def list_services() -> list[dict]:
-  return [{'key': s, 'name': _service_name(s)} for s in _services()]
-
-
-@mcp.tool()
-async def convert_price(transformation: str, service: str, amount: int) -> dict:
-  """Convert a price. transformation: net_to_list, list_to_net, list_to_retail, retail_to_list, net_to_retail, retail_to_net. Returns {net, list, retail}."""
-  from_type = _CALC_FROM.get(transformation)
-  if from_type is None:
-    raise ValueError(f'Unknown transformation: {transformation!r}')
-  if from_type == 'net':
-    return {'net': amount, 'list': net_to_list(service, amount), 'retail': net_to_retail(service, amount)}
-  if from_type == 'list':
-    return {'net': list_to_net(service, amount), 'list': amount, 'retail': list_to_retail(service, amount)}
-  return {'net': retail_to_net(service, amount), 'list': retail_to_list(service, amount), 'retail': amount}
-
-
-@mcp.tool()
-async def get_prices(start_date: str, end_date: str) -> dict:
-  """Get price dicts for a date range (YYYY-MM-DD). Returns a dict keyed by date string; None for dates with no price set."""
-  price_range = await CalPrice().get(date.fromisoformat(start_date), date.fromisoformat(end_date))
-  return {k: v.to_dict() if v else None for k, v in price_range.items()}
-
-
-@mcp.tool()
-async def set_price(target_date: str, value: float) -> None:
-  """Set the net price for a date (YYYY-MM-DD)."""
-  await CalPrice().set(date.fromisoformat(target_date), value)
-
-
-
-
-@mcp.tool()
-async def patch_reservation(uid: str, checkin_date: str, fields: dict[str, str] | None = None,
-                            checkin_time: str | None = None, checkout_time: str | None = None) -> dict:
-  """Patch a stored reservation. checkin_date (YYYY-MM-DD) is required to locate the event.
-
-  `fields` is merged directly into the reservation's stored data — wifi_key, wifi_ssid,
-  door_code, or any other custom field — except the sync-owned identity fields
-  (reservation_id, service, service_data, chat_id, guest_name), which are rejected.
-  `checkin_time`/`checkout_time` are 'HH:MM' strings that adjust only the time-of-day
-  of checkin/checkout; the date is never changed. Returns the updated reservation dict.
-  """
-  result = await Reservation().patch(
-    uid, date.fromisoformat(checkin_date),
-    fields=fields, checkin_time=checkin_time, checkout_time=checkout_time,
-  )
-  if result is None:
-    raise ValueError(f'reservation {uid!r} not found on {checkin_date}')
-  return result
-
-
-@mcp.tool()
-async def get_reservation(target_date: str) -> dict | None:
-  """Get the reservation covering a date (checkin ≤ date < checkout), or null."""
-  d = date.fromisoformat(target_date)
-  for ev in await Reservation().list(d, d):
-    if ev['start'].date() <= d < ev['end'].date():
-      xd = safe_json_loads(ev['x_data']) or {}
-      xd['checkin_date'] = ev['start'].date().isoformat()
-      xd['checkout_date'] = ev['end'].date().isoformat()
-      return xd
-  return None
-
-
-@mcp.tool()
-async def get_reservations_range(start_date: str, end_date: str) -> dict:
-  """Get reservations for each date in a range. Returns {date: dict or null}."""
-  start = date.fromisoformat(start_date)
-  end = date.fromisoformat(end_date)
-  events = await Reservation().list(start, end)
-  result: dict[str, dict | None] = {str(d): None for d in iter_dates(start, end)}
-  for ev in events:
-    checkin = ev['start'].date()
-    checkout = ev['end'].date()
-    xd = safe_json_loads(ev['x_data']) or {}
-    xd['checkin_date'] = checkin.isoformat()
-    xd['checkout_date'] = checkout.isoformat()
-    for d in iter_dates(start, end):
-      if checkin <= d < checkout:
-        result[str(d)] = xd
-  return result
-
-
-@mcp.tool()
-async def get_closed(target_date: str) -> list[str]:
-  """Get closed service keys for a date. Empty list means open."""
-  return await Closed().get(date.fromisoformat(target_date)) or []
-
-
-@mcp.tool()
-async def get_closed_range(start_date: str, end_date: str) -> dict:
-  """Get closed services for each date in a range. Returns {date: [service, ...]}."""
-  start = date.fromisoformat(start_date)
-  end = date.fromisoformat(end_date)
-  events = await Closed().list(start, end)
-  by_date: dict[str, list] = {str(d): [] for d in iter_dates(start, end)}
-  for ev in events:
-    d = ev['start'].date()
-    if start <= d <= end:
-      xd = safe_json_loads(ev['x_data'])
-      by_date[str(d)] = (xd or {}).get('closed_services', [])
-  return by_date
-
-
-@mcp.tool()
-async def set_closed(target_date: str, services: list[str]) -> None:
-  """Block a date for the given services. Empty list unblocks the date."""
-  await Closed().set(date.fromisoformat(target_date), services, source=_API_SOURCE)
-
-
-@mcp.tool()
-async def get_discount(target_date: str) -> dict | None:
-  """Get discount for a date, or null if none set."""
-  return await Discount().get(date.fromisoformat(target_date))
-
-
-@mcp.tool()
-async def get_discounts_range(start_date: str, end_date: str) -> dict:
-  """Get discounts for each date in a range. Returns {date: {type, value} or null}."""
-  start = date.fromisoformat(start_date)
-  end = date.fromisoformat(end_date)
-  events = await Discount().list(start, end)
-  by_date: dict[str, dict | None] = {str(d): None for d in iter_dates(start, end)}
-  for ev in events:
-    d = ev['start'].date()
-    if start <= d <= end:
-      xd = safe_json_loads(ev['x_data'])
-      if xd:
-        by_date[str(d)] = {'type': xd.get('type'), 'value': xd.get('value')}
-  return by_date
-
-
-@mcp.tool()
-async def set_discount(target_date: str, discount_type: str, value: int) -> None:
-  """Set a discount. discount_type: 'percent' or 'flat'."""
-  await Discount().set(
-    date.fromisoformat(target_date), discount_type, value, source=_API_SOURCE
-  )
-
-
-@mcp.tool()
-async def delete_discount(target_date: str) -> None:
-  """Remove the discount on a date."""
-  await Discount().delete_on(date.fromisoformat(target_date))
-
-
-@mcp.tool()
-async def refresh_credentials(service: str | None = None) -> dict:
-  """Trigger automatic credential refresh via Playwright. service: optional key (e.g. 'booking', 'airbnb'); omit to refresh all. Booking.com includes messaging 2FA and may take 2+ minutes. Returns {refreshed: [...], errors: {key: reason}}."""
-  from room_cal.service_api import ServiceAPI
-  from room_cal.service_api.types import ServiceAuthError
-  keys = [service] if service else _services()
-  api = ServiceAPI.get()
-
-  async def _do(key: str) -> tuple[str, str | None]:
-    try:
-      await api.refresh_credentials(key)
-      return key, None
-    except (ServiceAuthError, Exception) as e:
-      return key, str(e)
-
-  results = await asyncio.gather(*[_do(k) for k in keys])
-  return {
-    'refreshed': [k for k, err in results if err is None],
-    'errors': {k: err for k, err in results if err is not None},
-  }
-
-
-@mcp.tool()
-async def reload_caches() -> dict:
-  """Clear all in-memory CalDAV event caches so the next request re-fetches from the server. Returns {cleared_calendars}."""
-  from room_cal.store import clear_caches
-  count = clear_caches()
-  return {'cleared_calendars': count}
-
-
-@mcp.tool()
-async def get_chat_thread(service_key: str, chat_id: str) -> dict:
-  """Fetch recent messages for a reservation thread. Returns {chat_id, messages: [{id, created_at, body, sender}], is_reply_needed?}."""
-  from room_cal.service_api import ServiceAPI
-  from room_cal.service_api.types import ServiceAuthError
-  api = ServiceAPI.get()
-  try:
-    client = api.chat_client(service_key)
-  except KeyError:
-    raise ValueError(f'unknown service: {service_key!r}')
-  except TypeError:
-    raise ValueError(f'{service_key!r} does not support chat')
-  try:
-    thread = await client.get_thread(chat_id)
-  except ServiceAuthError as e:
-    raise RuntimeError(f'auth error: {e}')
-  chat_id_out = getattr(thread, 'thread_id', None) or getattr(thread, 'reservation_id', None)
-  result: dict = {
-    'chat_id': chat_id_out,
-    'messages': [
-      {
-        'id': m.id,
-        'created_at': getattr(m, 'created_at_ms', None) or getattr(m, 'created_at', None),
-        'body': m.body,
-        'sender': getattr(m, 'sender_name', None) or getattr(m, 'sender', None),
-      }
-      for m in thread.messages
-    ],
-  }
-  if hasattr(thread, 'is_reply_needed'):
-    result['is_reply_needed'] = thread.is_reply_needed
-  return result
-
-
-@mcp.tool()
-async def send_chat_message(service_key: str, chat_id: str, body: str) -> None:
-  """Send a text message to a guest conversation thread."""
-  from room_cal.service_api import ServiceAPI
-  from room_cal.service_api.types import ServiceAuthError
-  api = ServiceAPI.get()
-  try:
-    client = api.chat_client(service_key)
-  except KeyError:
-    raise ValueError(f'unknown service: {service_key!r}')
-  except TypeError:
-    raise ValueError(f'{service_key!r} does not support chat')
-  try:
-    await client.send_message(chat_id, body)
-  except ServiceAuthError as e:
-    raise RuntimeError(f'auth error: {e}')
-
-
-import importlib
-import pkgutil
-import room_cal.actions as _actions_pkg
-
-_ACTIONS: dict[str, tuple[str, str, list[str]]] = {}
-for _info in pkgutil.iter_modules(_actions_pkg.__path__):
-  if _info.name.startswith('_'):
-    continue
-  _mod = importlib.import_module(f'room_cal.actions.{_info.name}')
-  _spec = getattr(_mod, 'ACTION_SPEC', None)
-  if _spec:
-    _route_name, _allowed_keys = _spec
-    _ACTIONS[_route_name] = (f'room_cal.actions.{_info.name}', _info.name, _allowed_keys)
-
-@mcp.tool()
-async def run_action(
-  action: str,
-  start_date: str,
-  end_date: str | None = None,
-  feed_name: str | None = None,
-  title: str | None = None,
-  service: str | None = None,
-  weekday: int | None = None,
-  weekend: int | None = None,
-) -> object:
-  """Run a room_cal action over a date range. action must be one of the names in _ACTIONS (auto-discovered from room_cal.actions). Optional kwargs: feed_name, title (fetch-feed); service (fetch-prices); weekday, weekend (fill-prices)."""
-  from datetime import date as _date
-  if action not in _ACTIONS:
-    raise ValueError(f'Unknown action: {action!r}')
-  module_path, fn_name, allowed_keys = _ACTIONS[action]
-  mod = importlib.import_module(module_path)
-  fn = getattr(mod, fn_name)
-  start = _date.fromisoformat(start_date)
-  end = _date.fromisoformat(end_date) if end_date else start
-  all_kwargs = {'feed_name': feed_name, 'title': title, 'service': service, 'weekday': weekday, 'weekend': weekend}
-  kwargs = {k: v for k, v in all_kwargs.items() if k in allowed_keys and v is not None}
-  return await fn(start, end, **kwargs)

+ 0 - 5
room_cal/mcp/_server.py

@@ -1,5 +0,0 @@
-from room_cal.mcp import mcp
-
-
-def main() -> None:
-  mcp.run()

+ 32 - 6
room_cal/service_api/_airbnb.py

@@ -47,16 +47,16 @@ class AirbnbData:
 
 _BASE = 'https://www.airbnb.com/api/v3'
 _API_KEY = 'd306zoyjsyarp7ifhu67rjxn52tv0t20'
-_CLIENT_VERSION = '4e93a4878415297ab95d22665c666b6602dcfcbb'
+_CLIENT_VERSION = 'd2b819536102fb310c3d35777257319aee1c7fc1'
 _HASHES = {
-  'getDLSHostCalendar':               '048e22675ffa53121628d2d07b519b9b71f5dab342a1ceb75aa72d8814a00ea7',
+  'getDLSHostCalendar':               '5b153a16f8f392d6d4c6b5ee6259cf7f89ef972e0f79bf3f87753136af9a338c',
   'EditPanelPricingSettingsMutation': 'e27fed4f08dd4ab4c0267c5d6c0a7e4920730deadf48f92feba9b0d08befafa4',
-  'EditPanelAvailabilityMutation':    '2e056e7f98f8dc410a294c649adf719452980eb4d8ea95540fb1297af2637f67',
-  'StayHostingDetailsQuery':          '6da83b8bc9ae1b434f13938a55435118347b0e8ceb838e04c1feb84ecb587e6d',
+  'EditPanelAvailabilityMutation':    '1d321798756bddea88f11bcde6da336f70db64ee74dd8a9a30b91f4c7d6f1b64',
+  'StayHostingDetailsQuery':          '3641e070c5e57e44ada3d40eca288f5b739ed851c3bf03fe441e13e85dc30f50',
   'getNightlyPriceTips':              '07538bf1a5afc8171f1e7443f0007d7f020142fc7ab60df065e7e1edd1a0b29f',
   'HostCalendarListingEventsQuery':   '8bfe5f5572a25fdaff5b5790604e1de3aec5f37731fc505684022d590d06e0a8',
-  'ViaductGetThreadAndDataQuery':     'dd7478b376ad0a9709c7201b7e43cf402df011ec9d2fe4c1dff2ac418bcd9fb3',
-  'CreateBulkMessagesMutation':       '94ac2c4bd07edace539dbf2b9665d9030b6dee479db345ba8a8bbc234b3bbfa3',
+  'ViaductGetThreadAndDataQuery':     'be286f1a3810941029d1fd1f5be54df4f5cd146850636a648d6b19406caef21a',
+  'CreateBulkMessagesMutation':       '2abb1990dbf812cba634f28842fccb09e2a4351b247ea2f87839c20cc91c296a',
 }
 
 
@@ -474,6 +474,32 @@ class _AirbnbClient(ServiceClientBase):
     self._details.set(code, det)
     return det
 
+  def _detail_is_canceled(self, det: dict) -> bool | None:
+    """Read cancellation status from a detail's WHOSCOMING_SECTION, if present."""
+    wc_groups = (_detail_section(det, 'WHOSCOMING_SECTION').get('sectionData') or {}).get('reservationGroups', [])
+    if not wc_groups:
+      return None
+    return bool(wc_groups[0].get('isCanceled'))
+
+  async def check_reservation_status(self, reservation_id: str) -> bool | None:
+    """Return True if `reservation_id` is confirmed canceled, None if status can't be determined.
+
+    Queries StayHostingDetailsQuery directly by confirmation code — independent of the
+    calendar/MonthCache, and reuses the same _details TTL cache get_booked_nets/get_reservations
+    populate, so a prior fetch of the same reservation costs no extra network call. Any failure
+    (stale credentials, timeout, unparseable response) falls back to None rather than raising —
+    callers treat this as a best-effort check, not a required one.
+    """
+    try:
+      self._check_fresh()
+      det = await self._fetch_one_detail(reservation_id)
+      if not det:
+        return None
+      return self._detail_is_canceled(det)
+    except Exception:
+      _log.warning('airbnb: check_reservation_status failed for %s', reservation_id, exc_info=True)
+      return None
+
   def _global_thread_id(self, thread_id: str) -> str:
     return base64.b64encode(f'MessageThread:{thread_id}'.encode()).decode()
 

+ 38 - 3
room_cal/service_api/_booking.py

@@ -30,9 +30,9 @@ _SENDER_LABELS: dict[str, str] = {'GUEST': 'Guest', 'PARTNER': 'Host'}
 
 # Sync with scripts/har_audit.py via DRIFT_MANIFEST below — these are the only
 # copies; the manifest references them rather than duplicating the literals.
-_GQL_CLIENT_VERSION = 'EQSXMHMY'
-_GQL_TIMEOUT_MS = '15000'
-_MSG_CLIENT_VERSION = 'ABJaNSUc'
+_GQL_CLIENT_VERSION = 'cfJLLJeC'
+_GQL_TIMEOUT_MS = '60000'
+_MSG_CLIENT_VERSION = 'EQDFPbZe'
 
 _UPDATE_MUTATION = """mutation updateRoomDateMutation($input: PartnerAvailabilityUpdateInput) {
   partnerAvailabilityMutations {
@@ -518,6 +518,41 @@ class _BookingClient(ServiceClientBase):
       for rid, r_data in reservations.items()
     ]
 
+  async def check_reservation_status(self, reservation_id: str) -> bool | None:
+    """Return True if `reservation_id` is confirmed canceled, None if status can't be determined.
+
+    Queries reservationDetails directly by ID — independent of get_reservations/the calendar.
+    Uses the messaging-inbox referer; the x-booking-as-token some other page attaches to this
+    same endpoint isn't required (confirmed via a HAR where the token-less call succeeded
+    identically), and every refresh already primes the messaging session before booking.env is
+    written, so the token-less path is always available at runtime. Any failure (stale
+    credentials, timeout, unparseable response) falls back to None rather than raising —
+    callers treat this as a best-effort check, not a required one.
+    """
+    try:
+      self._check_fresh()
+      async def _attempt() -> httpx.Response:
+        referer = self._messaging_referer()
+        params = {
+          'ses': self._session,
+          'hotel_id': str(self._hotel_id),
+          'lang': self._lang,
+          'res_id': reservation_id,
+        }
+        return await self._http.get(
+          f'{_BASE}/fresa/extranet/messaging/inbox/reservationDetails',
+          params=params,
+          headers=self._rest_headers(referer),
+        )
+      r = await self._request(_attempt, op='reservationDetails')
+      data = r.json().get('data') or {}
+      if 'is_cancelled' not in data:
+        return None
+      return bool(data.get('is_cancelled'))
+    except Exception:
+      _log.warning('booking: check_reservation_status failed for %s', reservation_id, exc_info=True)
+      return None
+
   async def get_thread(self, reservation_id: str) -> BookingThread:
     """Fetch a conversation thread and its messages by reservation ID."""
     self._check_fresh()

+ 12 - 0
room_cal/service_api/client.py

@@ -299,6 +299,18 @@ class ServiceAPI:
     result.sort(key=lambda x: x['start_date'])
     return result
 
+  async def check_reservation_status(self, service: str, reservation_id: str) -> bool | None:
+    """Return True if `reservation_id` on `service` is confirmed canceled, None otherwise.
+
+    None covers both "the client doesn't implement this capability" and "it tried and
+    couldn't determine" — callers should treat both the same way (fall back to another
+    signal), not distinguish them.
+    """
+    client = self._clients.get(service)
+    if client is None or not hasattr(client, 'check_reservation_status'):
+      return None
+    return await client.check_reservation_status(reservation_id)  # type: ignore[attr-defined]
+
   async def diff_remote_sync(self, start_date: date, end_date: date) -> dict[str, list[dict]]:
     """Return per-service integrity issues without making any changes."""
     ds_from, ds_to = start_date.isoformat(), end_date.isoformat()

+ 21 - 6
room_cal/service_api/typescript/airbnb/refresh-cookies.ts

@@ -57,19 +57,34 @@ async function performLogin(page: Page, email: string, password: string): Promis
   await page.waitForLoadState('domcontentloaded');
 
   // Detect warm (password page shown immediately) vs cold (email input first).
-  const flow = await Promise.race([
+  let flow: 'warm' | 'cold' | 'remembered' | null = await Promise.race([
     page.waitForSelector('#password', { timeout: 15_000 }).then(() => 'warm' as const),
     page.waitForSelector('#phone-or-email', { timeout: 15_000 }).then(() => 'cold' as const),
   ]).catch(() => null);
 
   if (!flow) {
-    loginDisabledReason = 'neither email input nor password field appeared on signup_login';
-    throw new Error(`[airbnb] ${loginDisabledReason}`);
+    // Neither field appeared — check for the remembered-account screen: the device is
+    // recognized, so #phone-or-email is skipped entirely and the same submit button that
+    // the cold flow fills-then-clicks is shown ready to click immediately. Everything after
+    // the click is identical to the cold flow (Try another way → password option).
+    const submitBtn = page.locator('button[type="submit"]');
+    const remembered = await submitBtn.isVisible().catch(() => false)
+      && !(await page.locator('#phone-or-email').isVisible().catch(() => false));
+    if (remembered) {
+      flow = 'remembered';
+    } else {
+      loginDisabledReason = 'neither email input nor password field appeared on signup_login';
+      throw new Error(`[airbnb] ${loginDisabledReason}`);
+    }
   }
 
-  if (flow === 'cold') {
-    console.error('[airbnb] Auto-login: cold session — filling email...');
-    await page.locator('#phone-or-email').fill(email);
+  if (flow === 'cold' || flow === 'remembered') {
+    if (flow === 'cold') {
+      console.error('[airbnb] Auto-login: cold session — filling email...');
+      await page.locator('#phone-or-email').fill(email);
+    } else {
+      console.error('[airbnb] Auto-login: remembered-account session — skipping email entry...');
+    }
     await page.locator('button[type="submit"]').click();
 
     const tryAnother = page.getByRole('button', { name: /try another way/i });

+ 150 - 0
tests/test_check_reservation_status.py

@@ -0,0 +1,150 @@
+"""Unit tests for the check_reservation_status capability (both clients) and
+ServiceAPI.check_reservation_status's hasattr dispatch.
+
+Deep response-parsing lives here per client; the cross-client contract
+(True = confirmed canceled, None = couldn't determine, never raises) is what
+fetch_reservations.py's guard (tests/test_reservation_guards.py) relies on.
+"""
+import httpx
+import pytest
+
+from room_cal.service_api.client import ServiceAPI
+
+
+def _mock_transport(responses: list) -> httpx.MockTransport:
+  it = iter(responses)
+
+  def handler(request: httpx.Request) -> httpx.Response:
+    item = next(it)
+    if isinstance(item, BaseException):
+      raise item
+    return item
+
+  return httpx.MockTransport(handler)
+
+
+def _airbnb_client():
+  from room_cal.service_api._airbnb import _AirbnbClient
+  return _AirbnbClient(cookies='test', listing_id='12345678')
+
+
+def _booking_client():
+  from room_cal.service_api._booking import _BookingClient
+  return _BookingClient(
+    cookies='test', session='ses1', csrf_token='csrf1',
+    hotel_id=1, account_id=1, room_id=1, rate_id='rate1',
+  )
+
+
+def _stay_hosting_details_response(is_canceled: bool) -> httpx.Response:
+  return httpx.Response(200, json={
+    'data': {
+      'presentation': {
+        'hostingDetails': {
+          'stayHostingDetails': {
+            'rootPlacement': [
+              {
+                'sectionId': 'WHOSCOMING_SECTION',
+                'sectionData': {'reservationGroups': [{'isCanceled': is_canceled}]},
+              },
+            ],
+          },
+        },
+      },
+    },
+  })
+
+
+class TestAirbnbCheckReservationStatus:
+  async def test_canceled(self):
+    client = _airbnb_client()
+    client._http = httpx.AsyncClient(transport=_mock_transport([_stay_hosting_details_response(True)]))
+    assert await client.check_reservation_status('HMXKNXCSSS') is True
+
+  async def test_not_canceled(self):
+    client = _airbnb_client()
+    client._http = httpx.AsyncClient(transport=_mock_transport([_stay_hosting_details_response(False)]))
+    assert await client.check_reservation_status('HMFARE3JC4') is False
+
+  async def test_no_data_returns_none(self):
+    """A confirmation code with no matching detail (e.g. typo) can't be determined."""
+    client = _airbnb_client()
+    client._http = httpx.AsyncClient(
+      transport=_mock_transport([httpx.Response(200, json={'data': {'presentation': {}}})]))
+    assert await client.check_reservation_status('BOGUS') is None
+
+  async def test_timeout_returns_none_not_raise(self):
+    client = _airbnb_client()
+    client._http = httpx.AsyncClient(transport=_mock_transport([httpx.TimeoutException('slow')]))
+    assert await client.check_reservation_status('HMFARE3JC4') is None
+
+  async def test_reuses_details_cache(self):
+    """A reservation already fetched (e.g. by get_booked_nets) makes no extra network call."""
+    client = _airbnb_client()
+    client._details.set('HMXKNXCSSS', {
+      'rootPlacement': [
+        {'sectionId': 'WHOSCOMING_SECTION', 'sectionData': {'reservationGroups': [{'isCanceled': True}]}},
+      ],
+    })
+    client._http = httpx.AsyncClient(transport=_mock_transport([]))  # any call fails the test
+    assert await client.check_reservation_status('HMXKNXCSSS') is True
+
+
+class TestBookingCheckReservationStatus:
+  async def test_canceled(self):
+    client = _booking_client()
+    client._http = httpx.AsyncClient(
+      transport=_mock_transport([httpx.Response(200, json={'success': 1, 'data': {'is_cancelled': 1}})]))
+    assert await client.check_reservation_status('5124584185') is True
+
+  async def test_not_canceled(self):
+    client = _booking_client()
+    client._http = httpx.AsyncClient(
+      transport=_mock_transport([httpx.Response(200, json={'success': 1, 'data': {'is_cancelled': 0}})]))
+    assert await client.check_reservation_status('5162718780') is False
+
+  async def test_missing_field_returns_none(self):
+    client = _booking_client()
+    client._http = httpx.AsyncClient(
+      transport=_mock_transport([httpx.Response(200, json={'success': 1, 'data': {}})]))
+    assert await client.check_reservation_status('0000000000') is None
+
+  async def test_transport_error_returns_none_not_raise(self):
+    client = _booking_client()
+    client._http = httpx.AsyncClient(transport=_mock_transport([httpx.ConnectError('down')]))
+    assert await client.check_reservation_status('5124584185') is None
+
+  async def test_no_as_token_header_sent(self):
+    """The call relies on the post-messaging-prime session, not a page-bootstrapped token."""
+    client = _booking_client()
+    captured: list[httpx.Request] = []
+
+    def handler(request: httpx.Request) -> httpx.Response:
+      captured.append(request)
+      return httpx.Response(200, json={'success': 1, 'data': {'is_cancelled': 0}})
+
+    client._http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
+    await client.check_reservation_status('5162718780')
+    assert len(captured) == 1
+    assert 'x-booking-as-token' not in {h.lower() for h in captured[0].headers.keys()}
+    assert 'hotel_account_id' not in captured[0].url.params
+
+
+class TestServiceAPIDispatch:
+  async def test_unknown_service_returns_none(self):
+    api = ServiceAPI(clients={})
+    assert await api.check_reservation_status('airbnb', 'ANY') is None
+
+  async def test_client_without_capability_returns_none(self):
+    class _NoCapabilityClient:
+      pass
+    api = ServiceAPI(clients={'airbnb': _NoCapabilityClient()})
+    assert await api.check_reservation_status('airbnb', 'ANY') is None
+
+  async def test_dispatches_to_client_method(self):
+    class _StubClient:
+      async def check_reservation_status(self, reservation_id):
+        return reservation_id == 'CANCELED-ID'
+    api = ServiceAPI(clients={'airbnb': _StubClient()})
+    assert await api.check_reservation_status('airbnb', 'CANCELED-ID') is True
+    assert await api.check_reservation_status('airbnb', 'OTHER-ID') is False

+ 0 - 77
tests/test_mcp.py

@@ -1,77 +0,0 @@
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-from datetime import date
-
-from room_cal.mcp import mcp, convert_price, run_action
-
-
-def test_mcp_is_fastmcp():
-  from fastmcp import FastMCP
-  assert isinstance(mcp, FastMCP)
-
-
-@pytest.mark.asyncio
-async def test_convert_price_from_net():
-  result = await convert_price('net_to_list', 'airbnb', 100)
-  assert set(result.keys()) == {'net', 'list', 'retail'}
-  assert result['net'] == 100
-  assert result['list'] > result['net']
-
-
-@pytest.mark.asyncio
-async def test_convert_price_from_list():
-  result = await convert_price('list_to_net', 'airbnb', 150)
-  assert set(result.keys()) == {'net', 'list', 'retail'}
-  assert result['list'] == 150
-  assert result['net'] < result['list']
-
-
-@pytest.mark.asyncio
-async def test_convert_price_from_retail():
-  result = await convert_price('retail_to_list', 'airbnb', 200)
-  assert set(result.keys()) == {'net', 'list', 'retail'}
-  assert result['retail'] == 200
-
-
-@pytest.mark.asyncio
-async def test_convert_price_unknown_transformation():
-  with pytest.raises(ValueError, match='Unknown transformation'):
-    await convert_price('bad_transform', 'airbnb', 100)
-
-
-@pytest.mark.asyncio
-async def test_run_action_unknown_raises():
-  with pytest.raises(ValueError, match='Unknown action'):
-    await run_action('bad-action', '2026-01-01')
-
-
-@pytest.mark.asyncio
-async def test_run_action_end_date_defaults_to_start():
-  mock_fn = AsyncMock(return_value=[])
-  mock_mod = MagicMock()
-  mock_mod.fetch_prices = mock_fn
-  with patch('importlib.import_module', return_value=mock_mod):
-    await run_action('fetch-prices', '2026-01-15')
-  mock_fn.assert_called_once_with(date(2026, 1, 15), date(2026, 1, 15))
-
-
-@pytest.mark.asyncio
-async def test_run_action_kwargs_filtering_allows_allowed_keys():
-  mock_fn = AsyncMock(return_value=[])
-  mock_mod = MagicMock()
-  mock_mod.fetch_feed = mock_fn
-  with patch('importlib.import_module', return_value=mock_mod):
-    # fetch-feed allows feed_name and title, but not service
-    await run_action('fetch-feed', '2026-01-15', end_date='2026-01-20', feed_name='Fire', title='T', service='airbnb')
-  mock_fn.assert_called_once_with(date(2026, 1, 15), date(2026, 1, 20), feed_name='Fire', title='T')
-
-
-@pytest.mark.asyncio
-async def test_run_action_kwargs_filtering_excludes_none():
-  mock_fn = AsyncMock(return_value=[])
-  mock_mod = MagicMock()
-  mock_mod.fetch_feed = mock_fn
-  with patch('importlib.import_module', return_value=mock_mod):
-    # feed_name=None should be excluded even though it's in allowed_keys
-    await run_action('fetch-feed', '2026-01-15', feed_name=None)
-  mock_fn.assert_called_once_with(date(2026, 1, 15), date(2026, 1, 15))

+ 29 - 0
tests/test_reservation_guards.py

@@ -55,6 +55,15 @@ class _PartialAPI(_BaseAPI):
     return self._res
 
 
+class _StatusCheckAPI(_BaseAPI):
+  """Simulates a client implementing the check_reservation_status capability."""
+  def __init__(self, statuses: dict[str, bool | None]):
+    self._statuses = statuses
+
+  async def check_reservation_status(self, service, reservation_id):
+    return self._statuses.get(reservation_id)
+
+
 class _NoopClosed:
   """Stand-in for Closed so guard tests don't write closure events to the real store."""
   def __init__(self, *a, **k): pass
@@ -238,6 +247,26 @@ class TestFetchReservationsGuard:
     result = await fetch_reservations(_CHECKIN, _CHECKOUT, api=_BaseAPI())
     assert result.data == []
 
+  async def test_status_check_confirms_cancellation_despite_zero_return(self):
+    """check_reservation_status confirming True lets deletion proceed even with 0 returned."""
+    rid = 'TEST-GUARD-STATUS-CONFIRMED-001'
+    await _seed('airbnb', rid)
+    try:
+      await fetch_reservations(_CHECKIN, _CHECKOUT, api=_StatusCheckAPI({rid: True}))
+      assert not await _exists(rid), "status check confirming canceled must allow deletion"
+    finally:
+      await _delete(rid)
+
+  async def test_status_check_ambiguous_falls_back_to_guard(self):
+    """check_reservation_status returning None (ambiguous) still guards, like no capability at all."""
+    rid = 'TEST-GUARD-STATUS-AMBIGUOUS-001'
+    await _seed('airbnb', rid)
+    try:
+      await fetch_reservations(_CHECKIN, _CHECKOUT, api=_StatusCheckAPI({rid: None}))
+      assert await _exists(rid), "ambiguous status must not authorize deletion"
+    finally:
+      await _delete(rid)
+
 
 # ── fetch_reservations mass-deletion guard integration tests ──────────────────
 

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 117 - 696
uv.lock


برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است