"""The partner API of Рисмик from your server (Python 3.9+, standard library only). from rismik_partner import Client, verify_webhook wb = Client(api_key=os.environ["WB_API_KEY"]) lesson = wb.create_lesson(title="Дроби, 5 класс", external_id="course-7/lesson-3") link = wb.create_link(lesson["id"], user_id=str(user.id), name=user.name, role="student") # link["url"] goes into the page of that person only: it is their identity in the lesson. # a webhook (Django: request.body, Flask: request.get_data()) if not verify_webhook(secret, request.headers.get("X-Whiteboard-Signature"), raw_body): return HttpResponse(status=400) The API key stays on the server: never send it to a browser. """ from __future__ import annotations import hashlib import hmac import json import time import urllib.error import urllib.parse import urllib.request from typing import Any, Optional, Union __all__ = ["Client", "WhiteboardApiError", "verify_webhook", "parse_webhook", "DEFAULT_BASE_URL"] __version__ = "0.1.0" DEFAULT_BASE_URL = "https://api.rismik.ru" class WhiteboardApiError(Exception): def __init__(self, message: str, status: int, code: Optional[str], detail: Any) -> None: super().__init__(message) self.status = status self.code = code self.detail = detail class Client: def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 15.0) -> None: if not api_key.startswith("wbk_"): raise ValueError("api_key: a key looks like wbk_…") self._key = api_key self._base = base_url.rstrip("/") self._timeout = timeout def _request(self, method: str, path: str, body: Optional[dict] = None, raw: bool = False) -> Any: data = None if body is None else json.dumps({k: v for k, v in body.items() if v is not None}).encode() request = urllib.request.Request( f"{self._base}/api/partner/v1{path}", data=data, method=method, headers={ "Authorization": f"Bearer {self._key}", "Accept": "application/json", **({"Content-Type": "application/json"} if data is not None else {}), "User-Agent": f"rismik-partner-python/{__version__}", }, ) try: with urllib.request.urlopen(request, timeout=self._timeout) as response: # noqa: S310 - https API payload = response.read() if raw: return payload return json.loads(payload) if payload else None except urllib.error.HTTPError as exc: text = exc.read() try: detail = json.loads(text) except ValueError: detail = text.decode(errors="replace") info = detail.get("detail") if isinstance(detail, dict) else None code = info.get("code") if isinstance(info, dict) else None message = info.get("message") if isinstance(info, dict) else f"HTTP {exc.code}" raise WhiteboardApiError(message or f"HTTP {exc.code}", exc.code, code, detail) from None # lessons def create_lesson( self, title: str, external_id: Optional[str] = None, mode: str = "full", subject_mode: Optional[str] = None ) -> dict: return self._request( "POST", "/lessons", {"title": title, "external_id": external_id, "mode": mode, "subject_mode": subject_mode} ) def get_lesson(self, lesson_id: str) -> dict: return self._request("GET", f"/lessons/{urllib.parse.quote(lesson_id)}") def find_lesson(self, external_id: str) -> Optional[dict]: found = self._request("GET", "/lessons?" + urllib.parse.urlencode({"external_id": external_id})) return found[0] if found else None def archive_lesson(self, lesson_id: str) -> None: self._request("DELETE", f"/lessons/{urllib.parse.quote(lesson_id)}") def create_link( self, lesson_id: str, *, user_id: str, name: str, role: str, ttl_minutes: Optional[int] = None ) -> dict: """A personal link (role "teacher" or "student"); give it to that person only.""" return self._request( "POST", f"/lessons/{urllib.parse.quote(lesson_id)}/links", {"user": {"id": user_id, "name": name, "role": role}, "ttl_minutes": ttl_minutes}, ) def join_links(self, lesson_id: str, *, renew: bool = False) -> dict: """Shared links: pupil_url (and embed_code for a site), host_url for the teacher; renew cuts the old off.""" return self._request("POST", f"/lessons/{urllib.parse.quote(lesson_id)}/join-links", {"renew": renew}) def snapshot(self, lesson_id: str) -> dict: return self._request("GET", f"/lessons/{urllib.parse.quote(lesson_id)}/snapshot") def preview(self, lesson_id: str) -> bytes: return self._request("GET", f"/lessons/{urllib.parse.quote(lesson_id)}/preview", raw=True) # minutes def balance(self) -> dict: return self._request("GET", "/balance") def usage(self, date_from: Optional[str] = None, date_to: Optional[str] = None) -> dict: query = {k: v for k, v in (("from", date_from), ("to", date_to)) if v} return self._request("GET", "/usage" + ("?" + urllib.parse.urlencode(query) if query else "")) # webhooks def set_webhook(self, url: str) -> dict: """{"url", "secret"}: the signing secret is shown once — keep it.""" return self._request("PUT", "/webhook", {"url": url}) def delete_webhook(self) -> None: self._request("DELETE", "/webhook") def test_webhook(self) -> dict: return self._request("POST", "/webhook/test") def verify_webhook( secret: str, header: Optional[str], body: Union[bytes, str], *, tolerance: int = 300, now: Optional[int] = None, ) -> bool: """X-Whiteboard-Signature check: the time window and the HMAC of the raw body.""" if not header: return False try: fields = dict(part.strip().split("=", 1) for part in header.split(",")) stamp = int(fields["t"]) except (KeyError, ValueError): return False if abs((now if now is not None else int(time.time())) - stamp) > tolerance: return False raw = body.encode() if isinstance(body, str) else body expected = hmac.new(secret.encode(), f"{stamp}.".encode() + raw, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, fields.get("v1", "")) def parse_webhook(secret: str, header: Optional[str], body: Union[bytes, str], **kwargs: Any) -> Optional[dict]: """The event ({"id", "type", "created_at", "data"}), or None for a request that is not ours.""" if not verify_webhook(secret, header, body, **kwargs): return None return json.loads(body)