#!/usr/bin/env python3 """Wyby admin portal client (headless, read-only). Logs in to https://admin.wyby.ch via the IdentityServer authorization-code flow with PKCE (same as the React SPA) and keeps the authenticated cookie session. Bookings are read from the scheduler API used by the admin portal's "Buchungsübersicht" calendar: GET /api/Lessor/Organization/GetWallpaperData?startDate=...&endDate=... which returns rental objects with their upcoming transactions. The access PIN communicated to renters is the last 6 digits of the transaction Number. Read-only: this client never writes to wyby. """ from __future__ import annotations import base64 import hashlib import logging import re import secrets from dataclasses import dataclass from datetime import datetime import requests logger = logging.getLogger(__name__) # redirect_uri must match the SPA's registered value exactly (trailing slash!) REDIRECT_URI = "https://admin.wyby.ch/#origamClientCallback/" CLIENT_ID = "origamWebClient" SCOPE = "openid IdentityServerApi offline_access" # statuses to include (default: confirmed bookings as observed in the portal) DEFAULT_STATUS_IDS = ("a198f429-6e7d-4a46-b94f-08164c47e1a0",) @dataclass class Booking: number: str pin: str start_date: datetime.date # first rental day end_date: datetime.date # last rental day (inclusive) label: str # " " (wyby interface pattern) object_id: str object_name: str customer: str def extract_login_fields(html: str) -> dict[str, str]: """ReturnUrl and antiforgery token from the IdentityServer login page.""" fields = {} m = re.search(r'id="ReturnUrl"[^>]*value="([^"]+)"', html) if m: fields["ReturnUrl"] = m.group(1).replace("&", "&") m = re.search(r'name="__RequestVerificationToken"[^>]*value="([^"]+)"', html) if m: fields["__RequestVerificationToken"] = m.group(1) return fields def _rental_day( iso: str | None, exclusive_midnight: bool = False ) -> datetime.date | None: """Date part of an ISO timestamp; exclusive midnight counts as previous day.""" if not iso: return None dt = datetime.fromisoformat(str(iso)) day = dt.date() if exclusive_midnight and dt.time().hour == 0 and dt.time().minute == 0: day = day.fromordinal(day.toordinal() - 1) return day class WybyClient: def __init__( self, base: str = "https://admin.wyby.ch", user: str = "", password: str = "", status_ids: tuple[str, ...] = DEFAULT_STATUS_IDS, ): self.base = base.rstrip("/") self.user = user self.password = password self.status_ids = tuple(status_ids) self.session = requests.Session() self.session.headers["User-Agent"] = "glutz-maintenances-wyby-sync" self.logged_in = False # --- login -------------------------------------------------------- def login(self) -> None: """Authorization-code flow with PKCE; keeps the session cookies.""" verifier = ( base64.urlsafe_b64encode(secrets.token_bytes(64)).rstrip(b"=").decode() ) challenge = ( base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) .rstrip(b"=") .decode() ) r = self.session.get( f"{self.base}/connect/authorize", params={ "client_id": CLIENT_ID, "response_type": "code", "scope": SCOPE, "redirect_uri": REDIRECT_URI, "code_challenge": challenge, "code_challenge_method": "S256", "state": "sync", }, timeout=30, ) fields = extract_login_fields(r.text) if "ReturnUrl" not in fields or "__RequestVerificationToken" not in fields: raise RuntimeError(f"wyby login page unexpected (HTTP {r.status_code})") r = self.session.post( f"{self.base}/Account/Login", data={ **fields, "Username": self.user, "Password": self.password, "button": "login", }, timeout=30, ) if "Anmelden" in r.text and "passInput" in r.text: raise RuntimeError("wyby login failed (wrong credentials?)") logger.info("wyby login OK") self.logged_in = True def _ensure_login(self) -> None: if not self.logged_in: self.login() # --- data --------------------------------------------------------- def wallpaper(self, start, end) -> list[Booking]: """Bookings for rental objects in the given date range (yyyy-mm-dd).""" self._ensure_login() r = self.session.get( f"{self.base}/api/Lessor/Organization/GetWallpaperData", params={"startDate": start, "endDate": end}, timeout=60, ) if r.status_code == 401: # session expired -> one retry with fresh login logger.info("wyby session expired, re-login") self.logged_in = False self.login() r = self.session.get( f"{self.base}/api/Lessor/Organization/GetWallpaperData", params={"startDate": start, "endDate": end}, timeout=60, ) r.raise_for_status() return self.parse_wallpaper(r.json()) def parse_wallpaper(self, data: dict) -> list[Booking]: bookings: list[Booking] = [] unknown_status = set() for obj in data.get("ROOT", {}).get("RentalObject", []): for tx in obj.get("RentalTransaction", []): status = tx.get("refRentalTransactionStatusId") if self.status_ids and status not in self.status_ids: unknown_status.add(status) continue start = _rental_day(tx.get("RentingStartDate")) or _rental_day( tx.get("AllotmentRentingEndDate"), exclusive_midnight=True ) end = ( _rental_day( tx.get("AllotmentRentingEndDate"), exclusive_midnight=True ) or start ) number = str(tx.get("Number") or "") if not start or not end or not number: logger.warning( "SKIP transaction with incomplete data: %r", tx.get("Id") ) continue pin = number[-6:] bookings.append( Booking( number=number, pin=pin, start_date=start, end_date=end, label=f"{tx.get('CustomerName')} {tx.get('CustomerFirstName')} {pin}", object_id=str(obj.get("Id")), object_name=str(obj.get("Name")), customer=f"{tx.get('CustomerFirstName')} {tx.get('CustomerName')}", ) ) for status in sorted(unknown_status): logger.warning( "wyby transactions with unknown status %s skipped " "(extend WYBY_STATUS_IDS if this is wrong)", status, ) return bookings