Эх сурвалжийг харах

service_api: small cleanups

- _scripts uses the shared data_home() instead of its own copy
- ServiceClientBase._env_file delegates to credentials._env_path (one
  definition of '<key>.env in data home')
- _airbnb: top-level 'import re' instead of inline __import__ hack
- _booking: drop _msg_gql's vestigial attempt param (logging-only)
ZiB 3 сар өмнө
parent
commit
1c34dede48

+ 2 - 1
room_cal/service_api/_airbnb.py

@@ -2,6 +2,7 @@ import asyncio
 import base64
 import json
 import random
+import re
 import string
 import uuid
 from datetime import date, datetime, timedelta
@@ -363,7 +364,7 @@ class _AirbnbClient(ServiceClientBase):
         action = btn.get('buttonAction') or {}
         if action.get('__typename') == 'NavigateToMessageGuest':
           url = action.get('url', '')
-          m = __import__('re').search(r'/thread/(\d+)', url)
+          m = re.search(r'/thread/(\d+)', url)
           if m:
             thread_id = m.group(1)
             break

+ 3 - 3
room_cal/service_api/_base.py

@@ -18,8 +18,8 @@ from datetime import date
 
 import httpx
 
-from room_cal._utils import data_home, read_env
-from .credentials import clear_stale, is_stale, mark_stale
+from room_cal._utils import read_env
+from .credentials import _env_path, clear_stale, is_stale, mark_stale
 from .types import ServiceAuthError
 
 _log = logging.getLogger(__name__)
@@ -47,7 +47,7 @@ class ServiceClientBase:
 
   @classmethod
   def _env_file(cls):
-    return data_home() / f'{cls.service_key}.env'
+    return _env_path(cls.service_key)
 
   @classmethod
   def _read_env(cls) -> dict[str, str]:

+ 4 - 4
room_cal/service_api/_booking.py

@@ -353,7 +353,7 @@ class _BookingClient(ServiceClientBase):
       'Cookie': self._cookies,
     }
 
-  async def _msg_gql(self, operation_name: str, query: str, variables: dict, *, attempt: int = 1) -> dict:
+  async def _msg_gql(self, operation_name: str, query: str, variables: dict) -> dict:
     async def _do_request() -> httpx.Response:
       # params built per call so a retry after _ensure_refreshed uses the reloaded session
       params = {
@@ -372,7 +372,7 @@ class _BookingClient(ServiceClientBase):
     r = await self._request(_do_request, op=operation_name)
     raw = r.json()
     if raw.get('errors'):
-      _log.warning('booking _msg_gql %s attempt=%d gql errors: %s', operation_name, attempt, json.dumps(raw['errors']))
+      _log.warning('booking _msg_gql %s gql errors: %s', operation_name, json.dumps(raw['errors']))
       msgs = ', '.join(e.get('message', '') for e in raw['errors'])
       raise RuntimeError(f'GraphQL error: {msgs}')
     return raw
@@ -576,7 +576,7 @@ class _BookingClient(ServiceClientBase):
     }}
     _log.info('booking send_message res=%s idempotency=%s content_len=%d', reservation_id, idempotency, len(body))
     try:
-      raw = await self._msg_gql('postFreeTextMessage', _POST_FREE_TEXT_MUTATION, payload, attempt=1)
+      raw = await self._msg_gql('postFreeTextMessage', _POST_FREE_TEXT_MUTATION, payload)
       msg = ((raw.get('data') or {}).get('chatMessage') or {}).get('postFreeTextMessage') or {}
       result = msg.get('message') or {}
       _log.info('booking send_message ok res=%s msg_id=%s created=%s', reservation_id, result.get('messageId'), result.get('created'))
@@ -588,7 +588,7 @@ class _BookingClient(ServiceClientBase):
       # re-priming 2FA — force the full refresh (SMS challenge included).
       _log.warning('booking send_message ISE on attempt 1 res=%s idempotency=%s — re-triggering credential refresh', reservation_id, idempotency)
       await self._ensure_refreshed(full=True)
-      raw = await self._msg_gql('postFreeTextMessage', _POST_FREE_TEXT_MUTATION, payload, attempt=2)
+      raw = await self._msg_gql('postFreeTextMessage', _POST_FREE_TEXT_MUTATION, payload)
       msg = ((raw.get('data') or {}).get('chatMessage') or {}).get('postFreeTextMessage') or {}
       result = msg.get('message') or {}
       _log.info('booking send_message ok (after 2FA retry) res=%s msg_id=%s created=%s', reservation_id, result.get('messageId'), result.get('created'))

+ 2 - 7
room_cal/service_api/_scripts.py

@@ -7,23 +7,18 @@ import threading
 from collections.abc import Callable
 from pathlib import Path
 
-from room_cal._utils import get_config, internal_token
+from room_cal._utils import data_home, get_config, internal_token
 from .types import ServiceAuthError
 
 _log = logging.getLogger(__name__)
 
 
-def _data_home() -> Path:
-  override = os.environ.get('ROOM_CAL_DATA_HOME')
-  return Path(override) if override else Path.home() / '.local' / 'room_cal'
-
-
 def _ts_dir() -> Path:
   return Path(__file__).parent / 'typescript'
 
 
 def _npm_env() -> dict:
-  dh = _data_home()
+  dh = data_home()
   env = os.environ.copy()
   env.setdefault('ROOM_CAL_DATA_HOME', str(dh))
   env.setdefault('PLAYWRIGHT_BROWSERS_PATH', str(dh / '.playwright-browsers'))