2026-10-24 20:01:40 +03:00
|
|
|
"""Client for the REST API. Reuses the normal session cookie + CSRF flow."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
import requests
|
|
|
|
|
|
|
|
|
|
SESSION_COOKIE = "session"
|
|
|
|
|
CSRF_COOKIE = "csrf"
|
|
|
|
|
CSRF_HEADER = "X-CSRF-Token"
|
|
|
|
|
DEFAULT_MEETINGS_LIMIT = 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ApiError(Exception):
|
|
|
|
|
def __init__(self, message: str, status: int | None = None) -> None:
|
|
|
|
|
super().__init__(message)
|
|
|
|
|
self.status = status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AuthError(ApiError):
|
|
|
|
|
"""Raised when credentials are rejected or the session is invalid."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class Meeting:
|
|
|
|
|
id: int
|
|
|
|
|
title: str
|
|
|
|
|
intent: str
|
|
|
|
|
room: str
|
|
|
|
|
scheduled_at: datetime | None
|
|
|
|
|
created_by: int
|
|
|
|
|
created_by_name: str
|
|
|
|
|
created_at: datetime | None
|
2026-10-25 10:01:20 +03:00
|
|
|
# Whether the meeting should be announced. Defaults to True so meetings from
|
|
|
|
|
# older API responses (which lack the field) are still announced.
|
|
|
|
|
has_notification: bool = True
|
2026-10-24 20:01:40 +03:00
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
def from_json(cls, data: dict[str, Any]) -> "Meeting":
|
|
|
|
|
return cls(
|
|
|
|
|
id=int(data.get("id", 0)),
|
|
|
|
|
title=str(data.get("title") or ""),
|
|
|
|
|
intent=str(data.get("intent") or ""),
|
|
|
|
|
room=str(data.get("room") or ""),
|
|
|
|
|
scheduled_at=_parse_rfc3339(data.get("scheduledAt")),
|
|
|
|
|
created_by=int(data.get("createdBy", 0) or 0),
|
|
|
|
|
created_by_name=str(data.get("createdByName") or ""),
|
|
|
|
|
created_at=_parse_rfc3339(data.get("createdAt")),
|
2026-10-25 10:01:20 +03:00
|
|
|
has_notification=bool(data.get("hasNotification", True)),
|
2026-10-24 20:01:40 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_rfc3339(value: Any) -> datetime | None:
|
|
|
|
|
if not value or not isinstance(value, str):
|
|
|
|
|
return None
|
|
|
|
|
text = value.strip()
|
|
|
|
|
if text.endswith("Z"):
|
|
|
|
|
text = text[:-1] + "+00:00"
|
|
|
|
|
try:
|
|
|
|
|
parsed = datetime.fromisoformat(text)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return None
|
|
|
|
|
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class GoChatApi:
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
base_url: str,
|
|
|
|
|
*,
|
|
|
|
|
timeout: float = 20.0,
|
|
|
|
|
session_token: str = "",
|
|
|
|
|
csrf_token: str = "",
|
|
|
|
|
proxy: str = "",
|
|
|
|
|
) -> None:
|
|
|
|
|
self.base_url = base_url.rstrip("/")
|
|
|
|
|
self.timeout = timeout
|
|
|
|
|
self._http = requests.Session()
|
|
|
|
|
self._http.headers.update(
|
|
|
|
|
{"Accept": "application/json", "User-Agent": "meetings-bot/1.0"}
|
|
|
|
|
)
|
|
|
|
|
if proxy:
|
|
|
|
|
self._http.proxies.update({"http": proxy, "https": proxy})
|
2026-10-24 20:19:25 +03:00
|
|
|
# Cookies are tracked ourselves (see _send) so they are sent even when
|
|
|
|
|
# the server marks them Secure while we talk plain HTTP.
|
|
|
|
|
self._cookies: dict[str, str] = {}
|
2026-10-24 20:01:40 +03:00
|
|
|
self.restore_session(session_token, csrf_token)
|
|
|
|
|
|
|
|
|
|
def restore_session(self, session_token: str, csrf_token: str) -> None:
|
|
|
|
|
if session_token:
|
2026-10-24 20:19:25 +03:00
|
|
|
self._cookies[SESSION_COOKIE] = session_token
|
2026-10-24 20:01:40 +03:00
|
|
|
if csrf_token:
|
2026-10-24 20:19:25 +03:00
|
|
|
self._cookies[CSRF_COOKIE] = csrf_token
|
2026-10-24 20:01:40 +03:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def session_token(self) -> str:
|
2026-10-24 20:19:25 +03:00
|
|
|
return self._cookies.get(SESSION_COOKIE, "")
|
2026-10-24 20:01:40 +03:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def csrf_token(self) -> str:
|
2026-10-24 20:19:25 +03:00
|
|
|
return self._cookies.get(CSRF_COOKIE, "")
|
2026-10-24 20:01:40 +03:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def has_session(self) -> bool:
|
|
|
|
|
return bool(self.session_token)
|
|
|
|
|
|
2026-10-24 20:19:25 +03:00
|
|
|
def _capture(self, response: requests.Response) -> None:
|
|
|
|
|
for name in (SESSION_COOKIE, CSRF_COOKIE):
|
|
|
|
|
value = response.cookies.get(name)
|
|
|
|
|
if value:
|
|
|
|
|
self._cookies[name] = value
|
|
|
|
|
|
|
|
|
|
def _send(
|
|
|
|
|
self,
|
|
|
|
|
method: str,
|
|
|
|
|
path: str,
|
|
|
|
|
*,
|
|
|
|
|
json_body: dict | None = None,
|
|
|
|
|
params: dict | None = None,
|
|
|
|
|
headers: dict[str, str] | None = None,
|
|
|
|
|
) -> requests.Response:
|
|
|
|
|
request_headers = dict(headers or {})
|
|
|
|
|
if json_body is not None:
|
|
|
|
|
request_headers["Content-Type"] = "application/json"
|
|
|
|
|
cookie_header = "; ".join(f"{k}={v}" for k, v in self._cookies.items() if v)
|
|
|
|
|
# Keep the jar empty so requests does not override our explicit Cookie
|
|
|
|
|
# header (which would drop Secure cookies on plain HTTP).
|
|
|
|
|
self._http.cookies.clear()
|
|
|
|
|
if cookie_header:
|
|
|
|
|
request_headers["Cookie"] = cookie_header
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
response = self._http.request(
|
|
|
|
|
method,
|
|
|
|
|
f"{self.base_url}{path}",
|
|
|
|
|
json=json_body,
|
|
|
|
|
params=params,
|
|
|
|
|
headers=request_headers,
|
|
|
|
|
timeout=self.timeout,
|
|
|
|
|
)
|
|
|
|
|
except requests.RequestException as exc:
|
|
|
|
|
raise ApiError(f"request to {path} failed: {exc}") from exc
|
|
|
|
|
|
|
|
|
|
self._capture(response)
|
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
def _ensure_csrf(self) -> None:
|
|
|
|
|
"""Seed the csrf cookie via a GET when we do not have one yet.
|
|
|
|
|
|
|
|
|
|
State-changing requests are rejected unless the X-CSRF-Token header
|
|
|
|
|
matches the csrf cookie, and the cookie only appears after some request.
|
|
|
|
|
"""
|
|
|
|
|
if self.csrf_token:
|
|
|
|
|
return
|
|
|
|
|
self._send("GET", "/api/config")
|
|
|
|
|
|
2026-10-24 20:01:40 +03:00
|
|
|
def _request(
|
|
|
|
|
self,
|
|
|
|
|
method: str,
|
|
|
|
|
path: str,
|
|
|
|
|
*,
|
|
|
|
|
json_body: dict | None = None,
|
|
|
|
|
params: dict | None = None,
|
|
|
|
|
expect_json: bool = True,
|
|
|
|
|
) -> Any:
|
|
|
|
|
headers: dict[str, str] = {}
|
2026-10-24 20:19:25 +03:00
|
|
|
if method not in ("GET", "HEAD"):
|
|
|
|
|
self._ensure_csrf()
|
|
|
|
|
if self.csrf_token:
|
|
|
|
|
headers[CSRF_HEADER] = self.csrf_token
|
2026-10-24 20:01:40 +03:00
|
|
|
|
2026-10-24 20:19:25 +03:00
|
|
|
response = self._send(method, path, json_body=json_body, params=params, headers=headers)
|
2026-10-24 20:01:40 +03:00
|
|
|
|
|
|
|
|
if response.status_code == 204:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
payload: Any = None
|
|
|
|
|
if expect_json:
|
|
|
|
|
try:
|
|
|
|
|
payload = response.json()
|
|
|
|
|
except ValueError:
|
|
|
|
|
payload = None
|
|
|
|
|
|
|
|
|
|
if response.status_code >= 400:
|
|
|
|
|
message = payload.get("error") if isinstance(payload, dict) else None
|
|
|
|
|
message = message or response.text.strip() or response.reason or "request failed"
|
|
|
|
|
if response.status_code == 401:
|
|
|
|
|
raise AuthError(message, status=401)
|
|
|
|
|
raise ApiError(message, status=response.status_code)
|
|
|
|
|
|
|
|
|
|
return payload
|
|
|
|
|
|
|
|
|
|
def signin(self, login: str, password: str, remember: bool = True) -> None:
|
|
|
|
|
self._request(
|
|
|
|
|
"POST",
|
|
|
|
|
"/api/auth/signin",
|
|
|
|
|
json_body={"login": login, "password": password, "remember": remember},
|
|
|
|
|
)
|
|
|
|
|
if not self.has_session:
|
|
|
|
|
raise AuthError("sign in succeeded but no session cookie was returned")
|
|
|
|
|
|
|
|
|
|
def still_authenticated(self) -> bool:
|
|
|
|
|
if not self.has_session:
|
|
|
|
|
return False
|
|
|
|
|
try:
|
|
|
|
|
self._request("GET", "/api/profile")
|
|
|
|
|
return True
|
|
|
|
|
except AuthError:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def list_meetings(self, limit: int = DEFAULT_MEETINGS_LIMIT, offset: int = 0) -> list[Meeting]:
|
|
|
|
|
"""Return all meetings visible to the signed-in user (paged)."""
|
|
|
|
|
meetings: list[Meeting] = []
|
|
|
|
|
page_limit = max(1, min(limit, DEFAULT_MEETINGS_LIMIT))
|
|
|
|
|
current_offset = max(0, offset)
|
|
|
|
|
while True:
|
|
|
|
|
data = self._request(
|
|
|
|
|
"GET", "/api/meetings", params={"limit": page_limit, "offset": current_offset}
|
|
|
|
|
)
|
|
|
|
|
if not isinstance(data, list):
|
|
|
|
|
break
|
|
|
|
|
meetings.extend(Meeting.from_json(item) for item in data)
|
|
|
|
|
if len(data) < page_limit:
|
|
|
|
|
break
|
|
|
|
|
current_offset += page_limit
|
|
|
|
|
return meetings
|