Перейти к содержанию

API Reference

Auto-generated from source using mkdocstrings.

hse_lms

Unofficial SDK, CLI and MCP server for HSE SmartLMS (edu.hse.ru): courses, deadlines, grades, files, submissions.

Lms

Client for one user's account. Thread-safe: calls are serialized and rate-limited.

Auth modes, combine freely; the first that works is used:

  • Lms(cookie="MoodleSession=..."): a session copied from the browser;
  • Lms(username=..., password=...) or credentials from env, keyring or credentials.json;
  • a saved session (session_file, default ~/.config/hse-lms/session.json) reused across runs.

Parameters:

Name Type Description Default
cookie str | None

MoodleSession value or a name=value; ... cookie header copied from the browser.

None
username str | None

HSE login (e-mail). Overrides env, config and credentials.json.

None
password str | None

HSE password. Overrides env, keyring and credentials.json.

None
session_file Path | str | bool | None

where the session is kept. True = default path, None/False = memory only.

True
allow_password bool

False forbids the password step: only a live session or SSO renewal.

True
allow_write bool

True enables submit_assignment.

False
use_keyring bool

look up the password in the OS keyring.

True
min_interval float

minimum seconds between two requests.

0.7
timeout float

HTTP timeout in seconds.

30.0
timezone str

IANA zone for the datetimes the client returns.

'Europe/Moscow'
transport BaseTransport | None

custom httpx transport (tests use httpx.MockTransport).

None
Source code in hse_lms/client.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
class Lms:
    """Client for one user's account. Thread-safe: calls are serialized and rate-limited.

    Auth modes, combine freely; the first that works is used:

    * ``Lms(cookie="MoodleSession=...")``: a session copied from the browser;
    * ``Lms(username=..., password=...)`` or credentials from env, keyring or ``credentials.json``;
    * a saved session (``session_file``, default ``~/.config/hse-lms/session.json``) reused across runs.

    Args:
        cookie: ``MoodleSession`` value or a ``name=value; ...`` cookie header copied from the browser.
        username: HSE login (e-mail). Overrides env, config and ``credentials.json``.
        password: HSE password. Overrides env, keyring and ``credentials.json``.
        session_file: where the session is kept. ``True`` = default path, ``None``/``False`` = memory only.
        allow_password: ``False`` forbids the password step: only a live session or SSO renewal.
        allow_write: ``True`` enables `submit_assignment`.
        use_keyring: look up the password in the OS keyring.
        min_interval: minimum seconds between two requests.
        timeout: HTTP timeout in seconds.
        timezone: IANA zone for the datetimes the client returns.
        transport: custom httpx transport (tests use ``httpx.MockTransport``).
    """

    def __init__(
        self,
        *,
        cookie: str | None = None,
        username: str | None = None,
        password: str | None = None,
        session_file: Path | str | bool | None = True,
        allow_password: bool = True,
        allow_write: bool = False,
        use_keyring: bool = True,
        min_interval: float = 0.7,
        timeout: float = 30.0,
        timezone: str = "Europe/Moscow",
        transport: httpx.BaseTransport | None = None,
    ) -> None:
        path: Path | None
        if session_file is True:
            path = config_dir() / "session.json"
        elif session_file:
            path = Path(session_file).expanduser()
        else:
            path = None
        self.store = SessionStore(path)
        self.creds = CredentialProvider(username, password, use_keyring=use_keyring)
        self.allow_password = allow_password
        self.allow_write = allow_write
        self.min_interval = min_interval
        self.tz = ZoneInfo(timezone)
        self.http = httpx.Client(
            follow_redirects=False,
            timeout=timeout,
            transport=transport,
            headers={"User-Agent": f"hse-lms-mcp/{__version__} (+https://github.com/AlexeyShalaev/hse-lms-mcp)"},
        )
        self.store.load(self.http.cookies)
        for name, value in parse_cookie(cookie or "").items():
            self.http.cookies.set(name, value, domain=LMS_HOST, path="/")
        self.sesskey: str | None = None
        self.userid: int | None = None
        self.login_path: str | None = None
        self._password_rejected = False
        self._last = 0.0
        self._lock = threading.RLock()
        self._cm_types: dict[int, str] = {}

    def __enter__(self) -> Lms:
        return self

    def __exit__(
        self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
    ) -> None:
        self.close()

    def close(self) -> None:
        """Close the HTTP connection pool."""
        self.http.close()

    def __repr__(self) -> str:
        return f"Lms(userid={self.userid!r}, login_path={self.login_path!r}, allow_write={self.allow_write})"

    # ---------------------------------------------------------------- transport

    def _wait(self) -> None:
        dt = time.monotonic() - self._last
        if dt < self.min_interval:
            time.sleep(self.min_interval - dt)
        self._last = time.monotonic()

    def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
        self._wait()
        return self.http.request(method, url, **kwargs)

    def _next(self, url: str, r: httpx.Response) -> str:
        """Location of a redirect inside edu.hse.ru, or raise."""
        loc = urljoin(url, str(r.headers.get("location", "")))
        if _is_login_path(urlparse(loc).path):
            raise SessionExpiredError("LMS redirected to the login page")
        if not _host_ok(loc, {LMS_HOST}):
            raise UnsafeRedirectError(_describe(loc))
        return loc

    def get(self, path: str, max_redirects: int = 5) -> httpx.Response:
        """GET a page of edu.hse.ru, following redirects only inside edu.hse.ru."""
        url = urljoin(BASE_URL, path)
        if not _host_ok(url, {LMS_HOST}):
            raise UnsafeRedirectError(_describe(url))
        for _ in range(max_redirects + 1):
            r = self._request("GET", url)
            if r.status_code not in _REDIRECT:
                return r
            url = self._next(url, r)
        raise UnsafeRedirectError("too many redirects")

    def ajax(self, method: str, args: dict[str, Any]) -> Any:
        """Call a Moodle AJAX web service (``lib/ajax/service.php``) under the browser session."""
        r = self._request(
            "POST",
            f"{BASE_URL}/lib/ajax/service.php",
            params={"sesskey": self.sesskey or "", "info": method},
            json=[{"index": 0, "methodname": method, "args": args}],
            headers={"X-Requested-With": "XMLHttpRequest"},
        )
        if r.status_code in _REDIRECT:
            raise SessionExpiredError("AJAX call was redirected")
        try:
            item = r.json()[0]
        except (ValueError, KeyError, IndexError) as e:
            raise SessionExpiredError("AJAX returned a non-JSON page") from e
        if item.get("error"):
            exc = item.get("exception") or {}
            code = exc.get("errorcode")
            if code == "servicenotavailable":
                raise MethodNotAvailableError(method)
            if code in ("servicerequireslogin", "invalidsesskey", "requireloginerror"):
                raise SessionExpiredError(code)
            raise LmsError(f"{method}: {code}: {exc.get('message')}")
        return item["data"]

    def _fetch(self, url: str, max_redirects: int = 5) -> _Fetched:
        """GET a file URL inside edu.hse.ru. Retries a body that looks truncated."""
        url = urljoin(BASE_URL, url)
        for attempt in range(_FETCH_ATTEMPTS):
            r = self._request("GET", url)
            for _ in range(max_redirects):
                if r.status_code not in _REDIRECT:
                    break
                loc = urljoin(url, str(r.headers.get("location", "")))
                if _is_login_path(urlparse(loc).path):
                    raise SessionExpiredError("LMS redirected to the login page")
                if not _host_ok(loc, {LMS_HOST}):
                    return _Fetched(kind="external", url=_describe(loc))
                url = loc
                r = self._request("GET", url)
            if r.status_code in _REDIRECT:
                raise UnsafeRedirectError("too many redirects")
            if r.status_code != 200:
                raise LmsError(f"HTTP {r.status_code} for {_describe(url)}")
            if "text/html" in r.headers.get("content-type", ""):
                return _Fetched(kind="html", url=url, html=r.text)
            cd = r.headers.get("content-disposition", "")
            m = re.search(r"filename\*=UTF-8''([^;]+)", cd) or re.search(r'filename="?([^";]+)"?', cd)
            name = _safe_name(unquote(m.group(1)) if m else parsing.file_name(url))
            if not _looks_truncated(r.content, name) or attempt == _FETCH_ATTEMPTS - 1:
                return _Fetched(kind="file", url=url, name=name, content=r.content)
        raise AssertionError("unreachable")

    # -------------------------------------------------------------------- login

    def _read_my(self) -> None:
        r = self.get("/my/")
        key = parsing.sesskey(r.text)
        if not key:
            raise SessionExpiredError("no sesskey on /my/")
        self.sesskey, self.userid = key, parsing.userid(r.text)

    def login(self, password_prompt: Callable[[str], str | None] | None = None) -> SessionInfo:
        """Make sure there is a live session: reuse it, renew it via SSO, or log in with the password.

        Args:
            password_prompt: asked for the password when no stored one is found (CLI uses getpass).

        Raises:
            SessionExpiredError: the session is dead and there are no credentials (or passwords are disallowed).
            LoginError: Keycloak rejected the password or asked for something the client cannot do.
            UnsafeRedirectError: the login chain left edu.hse.ru / saml.hse.ru.
        """
        with self._lock:
            try:
                self._read_my()
                self.login_path = "session"
            except SessionExpiredError:
                for c in list(self.http.cookies.jar):
                    if c.name.startswith("MoodleSession"):
                        self.http.cookies.jar.clear(c.domain, c.path, c.name)
                self.login_path = self._sso(password_prompt)
                self._read_my()
            self.store.save(self.http.cookies)
            return SessionInfo(userid=self.userid, login_path=self.login_path)

    def _password(self, password_prompt: Callable[[str], str | None] | None) -> tuple[str, str]:
        if self._password_rejected:
            raise LoginError("the password was already rejected in this process; not retrying (lockout risk)")
        user = self.creds.username()
        pw = self.creds.password(user) if user else None
        if not pw and user and password_prompt and self.allow_password:
            pw = password_prompt(user)
        if not self.allow_password or not user or not pw:
            raise SessionExpiredError(
                "session expired and no credentials to log in again: pass a fresh cookie "
                "or set HSE_LMS_USERNAME / HSE_LMS_PASSWORD (or run `hse-lms login --setup`)"
            )
        return user, pw

    def _sso(self, password_prompt: Callable[[str], str | None] | None) -> str:
        url, method, data = f"{BASE_URL}/auth/oidckc/", "GET", None
        used_password = False
        for _ in range(12):
            r = self._request(method, url, data=data)
            if r.status_code in _REDIRECT:
                loc = urljoin(url, str(r.headers.get("location", "")))
                if not _host_ok(loc, {LMS_HOST, SSO_HOST}):
                    raise UnsafeRedirectError(_describe(loc))
                p = urlparse(loc)
                if p.hostname == LMS_HOST and not p.path.startswith(("/login/", "/auth/")):
                    return "password" if used_password else "sso"
                url, method, data = loc, "GET", None
                continue
            if r.status_code != 200:
                raise LoginError(f"HTTP {r.status_code} at {_describe(url)}")
            page = parsing.soup(r.text)
            back = next(
                (
                    f
                    for f in page.find_all("form")
                    if urlparse(urljoin(url, str(f.get("action", "")))).hostname == LMS_HOST
                ),
                None,
            )
            if back is not None:  # Keycloak form_post page: code and state go back to edu.hse.ru
                url, method = urljoin(url, str(back["action"])), "POST"
                data = {str(i["name"]): str(i.get("value", "")) for i in back.find_all("input") if i.get("name")}
                if not _host_ok(url, {LMS_HOST}):
                    raise UnsafeRedirectError(_describe(url))
                continue
            form = page.select_one("form#kc-form-login")
            if form is None:
                title = page.title.get_text(strip=True) if page.title else "?"
                raise LoginError(f"unexpected login page {title!r} at {_describe(url)}: second factor or captcha?")
            if used_password:
                self._password_rejected = True
                err = page.select_one("#input-error, .kc-feedback-text, .alert-error, .pf-c-alert__title")
                raise LoginError("Keycloak rejected the password: " + (parsing.text(err) if err else "no message"))
            user, pw = self._password(password_prompt)
            url = urljoin(url, str(form["action"]))
            if not _host_ok(url, {SSO_HOST}):
                raise UnsafeRedirectError(f"login form posts to {_describe(url)}")
            method, data, used_password = "POST", {"username": user, "password": pw, "credentialId": ""}, True
        raise UnsafeRedirectError("too many steps in SSO")

    # ------------------------------------------------------------------ reading

    def _dt(self, ts: int | None) -> datetime | None:
        return datetime.fromtimestamp(ts, self.tz) if ts else None

    @_session
    def whoami(self) -> SessionInfo:
        """Check the session (logging in again if needed) and return who is logged in."""
        return SessionInfo(userid=self.userid, login_path=self.login_path or "session")

    @_session
    def courses(self, classification: str = "inprogress") -> list[Course]:
        """Courses you are enrolled in.

        Args:
            classification: ``inprogress``, ``all``, ``future``, ``past``, ``favourites`` or ``hidden``.
        """
        offset, raw = 0, []
        while True:
            d = self.ajax(
                "core_course_get_enrolled_courses_by_timeline_classification",
                {"offset": offset, "limit": 12, "classification": classification, "sort": "fullname"},
            )
            raw += d["courses"]
            if not d["courses"] or d["nextoffset"] == offset:
                break
            offset = d["nextoffset"]
        return [
            Course(
                id=c["id"],
                fullname=c["fullname"],
                shortname=c.get("shortname", ""),
                category=c.get("coursecategory"),
                progress=c.get("progress") if c.get("hasprogress") else None,
                start=self._dt(c.get("startdate")),
                end=self._dt(c.get("enddate")),
                favourite=bool(c.get("isfavourite")),
                hidden=bool(c.get("hidden")),
                url=c.get("viewurl") or f"{BASE_URL}/course/view.php?id={c['id']}",
            )
            for c in raw
        ]

    @_session
    def course_state(self, course_id: int) -> dict[str, Any]:
        """Raw ``core_courseformat_get_state``: course, sections and modules as Moodle returns them."""
        raw = self.ajax("core_courseformat_get_state", {"courseid": int(course_id)})
        state: dict[str, Any] = json.loads(raw) if isinstance(raw, str) else raw
        return state

    @_session
    def course(self, course_id: int, include_text: bool = False) -> CourseContents:
        """Sections of a course with their visible modules.

        Args:
            course_id: course id from `courses`.
            include_text: also read label texts and section summaries (one extra page load).
        """
        st = self.course_state(course_id)
        labels: dict[int, str] = {}
        summaries: dict[int, str] = {}
        if include_text:
            labels, summaries = parsing.labels_and_summaries(self.get(f"/course/view.php?id={int(course_id)}").text)
        cms = {str(c["id"]): c for c in st["cm"]}
        sections = []
        for s in sorted(st["section"], key=lambda s: s["number"]):
            modules = []
            for cmid in s["cmlist"]:
                c = cms.get(str(cmid))
                if not c or not c.get("uservisible"):
                    continue
                kind = c.get("module") or (c.get("plugin") or "").removeprefix("mod_")
                self._cm_types[int(c["id"])] = kind
                url = c.get("url") or ""
                modules.append(
                    Module(
                        cmid=int(c["id"]),
                        name=c["name"],
                        type=kind,
                        url=url if url and "undefined" not in url else None,
                        visible=bool(c.get("visible", True)),
                        restricted=bool(c.get("hascmrestrictions")),
                        text=labels.get(int(c["id"])),
                    )
                )
            sections.append(
                Section(
                    id=int(s["id"]),
                    number=s["number"],
                    title=s["title"],
                    visible=bool(s.get("visible", True)),
                    restricted=bool(s.get("hasrestrictions")),
                    summary=summaries.get(s["number"]),
                    modules=modules,
                )
            )
        return CourseContents(course_id=int(course_id), sections=sections)

    @_session
    def deadlines(self, days_back: int = 0, days_ahead: int = 60, limit: int = 50) -> list[Deadline]:
        """Dated events (due dates, quiz closing times) from the LMS calendar across all courses."""
        now = int(time.time())
        d = self.ajax(
            "core_calendar_get_action_events_by_timesort",
            {"limitnum": limit, "timesortfrom": now - 86400 * days_back, "timesortto": now + 86400 * days_ahead},
        )
        out = []
        for e in d["events"]:
            url = e.get("url")
            cmid = (parse_qs(urlparse(url).query).get("id") or [""])[0] if url else ""
            action = e.get("action") or {}
            out.append(
                Deadline(
                    name=e["name"],
                    course_id=e["course"]["id"],
                    course=e["course"]["fullname"],
                    type=e.get("modulename"),
                    cmid=int(cmid) if cmid.isdigit() else None,
                    due=datetime.fromtimestamp(e["timesort"], self.tz),
                    overdue=bool(e.get("overdue")),
                    actionable=bool(action.get("actionable")),
                    action=action.get("name"),
                    url=url,
                )
            )
        return out

    def _module_by_redirect(self, cmid: int, kind: str) -> ModuleDetail | str:
        """url and resource modules: a redirect tells where they point. Returns the page HTML otherwise."""
        r = self._request("GET", f"{BASE_URL}/mod/{kind}/view.php?id={cmid}")
        if r.status_code in _REDIRECT:
            loc = urljoin(BASE_URL, str(r.headers.get("location", "")))
            if _is_login_path(urlparse(loc).path):
                raise SessionExpiredError("LMS redirected to the login page")
            inside = _host_ok(loc, {LMS_HOST})
            if inside and urlparse(loc).path.startswith("/course/view.php"):
                return ModuleDetail(
                    cmid=cmid, type=kind, description="The LMS sent you back to the course page: no access yet."
                )
            if kind == "resource" and inside:
                name = parsing.file_name(loc)
                return ModuleDetail(cmid=cmid, type=kind, title=name, files=[FileRef(name=name, url=loc)])
            return ModuleDetail(cmid=cmid, type=kind, target_url=loc)
        if r.status_code != 200:
            raise LmsError(f"HTTP {r.status_code} for module {cmid}")
        if "text/html" not in r.headers.get("content-type", ""):
            name = parsing.file_name(str(r.url))
            return ModuleDetail(cmid=cmid, type=kind, title=name, files=[FileRef(name=name, url=str(r.url))])
        return r.text

    @_session
    def module(self, cmid: int, type: str | None = None) -> ModuleDetail:
        """Contents of one activity: description, dates, files and, by type, submission status, page text,
        quiz info or link target.

        Args:
            cmid: course module id, the ``id=`` of ``/mod/<type>/view.php``.
            type: ``assign``, ``quiz``, ``page``, ``url``, ``folder``, ``resource``, ``forum``... Optional for
                modules this client already saw in `course`.

        Raises:
            ValueError: the type is unknown.
        """
        cmid = int(cmid)
        kind = type or self._cm_types.get(cmid)
        if not kind:
            raise ValueError("module type unknown: pass type (assign, quiz, page, url, folder, resource, forum)")
        if kind in ("url", "resource"):
            got = self._module_by_redirect(cmid, kind)
            if isinstance(got, ModuleDetail):
                return got
            html = got
        else:
            html = self.get(f"/mod/{kind}/view.php?id={cmid}").text
        info = parsing.common(html, BASE_URL)
        detail = ModuleDetail(
            cmid=cmid,
            type=kind,
            title=info.title,
            dates=info.dates,
            description=info.description,
            files=info.files,
        )
        if kind == "assign":
            detail.submission = parsing.submission_status(html, BASE_URL)
        elif kind == "quiz":
            detail.quiz_info = parsing.quiz_info(html)
        elif kind == "page":
            detail.text = parsing.page_body(html)
        elif kind == "url":
            detail.target_url = parsing.url_target(html)
        return detail

    def assignment(self, cmid: int) -> ModuleDetail:
        """Shortcut for ``module(cmid, "assign")``."""
        return self.module(cmid, "assign")

    @_session
    def grades(self, course_id: int) -> list[GradeItem]:
        """Your grade report for a course (``/grade/report/user``)."""
        return parsing.grades(self.get(f"/grade/report/user/index.php?id={int(course_id)}").text)

    @_session
    def forum(self, cmid: int, limit: int = 10, posts_per_discussion: int = 20) -> list[Discussion]:
        """Latest discussions of a forum with their posts. Each discussion costs one request."""
        topics = parsing.forum_discussions(self.get(f"/mod/forum/view.php?id={int(cmid)}").text)
        out = []
        for did, title in topics[:limit]:
            d = parsing.discussion(did, title, self.get(f"/mod/forum/discuss.php?d={did}").text, BASE_URL)
            d.posts = d.posts[:posts_per_discussion]
            out.append(d)
        return out

    def _check_url(self, url: str) -> str:
        full = urljoin(BASE_URL, url)
        if not _host_ok(full, {LMS_HOST}):
            raise UnsafeRedirectError(f"not an edu.hse.ru URL: {_describe(full)}")
        return full

    @_session
    def read_file(self, target: str | int) -> tuple[str, bytes]:
        """``(file name, content)`` of a ``pluginfile.php`` URL or of a resource module (by cmid), in memory.

        Raises:
            ValueError: the target is a page with zero or several files.
            UnsafeRedirectError: the URL or its redirects leave edu.hse.ru.
        """
        url = f"/mod/resource/view.php?id={int(target)}" if str(target).isdigit() else self._check_url(str(target))
        got = self._fetch(url)
        if got.kind == "html":
            links = parsing.file_refs(parsing.soup(got.html), BASE_URL, own_submission=False)
            if len(links) != 1:
                shown = ", ".join(f.url for f in links[:10])
                raise ValueError(f"{url} is a page with {len(links)} files, pass one of their URLs: {shown}")
            got = self._fetch(links[0].url)
        if got.kind != "file":
            raise UnsafeRedirectError(f"points outside edu.hse.ru: {got.url}")
        return got.name, got.content

    def download(self, target: str | int, dest_dir: Path | str = ".") -> Path:
        """Save a file into ``dest_dir``: a ``pluginfile.php`` URL or the cmid of a resource module.

        Returns:
            The saved path; the name comes from the server, stripped of directories.
        """
        name, content = self.read_file(target)
        dest = Path(dest_dir).expanduser() / name
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_bytes(content)
        return dest

    # ------------------------------------------------------------------ writing

    @_session
    def submit_assignment(self, cmid: int, files: Iterable[FileInput]) -> SubmitResult:
        """Upload files as your submission and save it. Needs ``allow_write=True``.

        Refuses an assignment that already has submitted files (replacing is not supported yet). Checks the
        number, size and extensions of the files against the assignment settings first, and after saving
        downloads every file back and compares SHA-256.

        Raises:
            WriteNotAllowedError: the client is read-only.
            SubmissionError: Moodle refused, or a file did not come back intact.
        """
        if not self.allow_write:
            raise WriteNotAllowedError("this client is read-only; create it with allow_write=True to submit")
        items = _load_files(files)
        view = f"/mod/assign/view.php?id={int(cmid)}"
        before = parsing.submission_status(self.get(view).text, BASE_URL)
        if before is None:
            raise SubmissionError("no submission status on the page: not an assignment or no access")
        if before.files:
            names = ", ".join(f.name for f in before.files)
            raise SubmissionError(f"the submission already has files: {names}; replacing is not supported yet")
        form = _SubmissionForm.read(self.get(f"{view}&action=editsubmission").text)
        form.check(items)
        for name, body in items:
            self._upload(form, name, body)
        r = self._request(
            "POST", f"{BASE_URL}/mod/assign/view.php", data={**form.hidden, "submitbutton": "Save changes"}
        )
        if r.status_code not in _REDIRECT:
            errors = parsing.form_errors(r.text)
            raise SubmissionError(
                "the form was not accepted: " + ("; ".join(errors) if errors else f"HTTP {r.status_code}")
            )
        self._next(f"{BASE_URL}/mod/assign/view.php", r)
        after = parsing.submission_status(self.get(view).text, BASE_URL) or SubmissionStatus()
        sent = {name: hashlib.sha256(body).hexdigest() for name, body in items}
        verified = [
            f.name
            for f in after.files
            if f.name in sent and hashlib.sha256(self.read_file(f.url)[1]).hexdigest() == sent[f.name]
        ]
        missing = sorted(set(sent) - set(verified))
        if missing:
            raise SubmissionError("saved, but these files did not come back intact: " + ", ".join(missing))
        return SubmitResult(cmid=int(cmid), uploaded=list(sent), verified=verified, status=after)

    def _upload(self, form: _SubmissionForm, name: str, body: bytes) -> None:
        r = self._request(
            "POST",
            f"{BASE_URL}/repository/repository_ajax.php",
            params={"action": "upload"},
            data={
                "sesskey": self.sesskey or "",
                "repo_id": form.repo_id,
                "itemid": form.hidden["files_filemanager"],
                "author": "",
                "savepath": "/",
                "title": name,
                "ctx_id": form.context_id,
                "client_id": form.client_id,
                "env": "filemanager",
                "accepted_types[]": form.accepted_types or ["*"],
                "maxbytes": str(form.maxbytes),
                "areamaxbytes": str(form.areamaxbytes),
                "license": form.license,
            },
            files={"repo_upload_file": (name, body, mimetypes.guess_type(name)[0] or "application/octet-stream")},
            timeout=max(120.0, self.http.timeout.read or 30.0),
        )
        try:
            j = r.json()
        except ValueError as e:
            raise SubmissionError(f"{name}: upload returned HTTP {r.status_code}, not JSON") from e
        if j.get("error") or j.get("event") == "fileexists" or not (j.get("file") or j.get("url")):
            raise SubmissionError(f"{name}: upload refused: {j.get('error') or j.get('event') or 'unknown'}")

ajax(method, args)

Call a Moodle AJAX web service (lib/ajax/service.php) under the browser session.

Source code in hse_lms/client.py
def ajax(self, method: str, args: dict[str, Any]) -> Any:
    """Call a Moodle AJAX web service (``lib/ajax/service.php``) under the browser session."""
    r = self._request(
        "POST",
        f"{BASE_URL}/lib/ajax/service.php",
        params={"sesskey": self.sesskey or "", "info": method},
        json=[{"index": 0, "methodname": method, "args": args}],
        headers={"X-Requested-With": "XMLHttpRequest"},
    )
    if r.status_code in _REDIRECT:
        raise SessionExpiredError("AJAX call was redirected")
    try:
        item = r.json()[0]
    except (ValueError, KeyError, IndexError) as e:
        raise SessionExpiredError("AJAX returned a non-JSON page") from e
    if item.get("error"):
        exc = item.get("exception") or {}
        code = exc.get("errorcode")
        if code == "servicenotavailable":
            raise MethodNotAvailableError(method)
        if code in ("servicerequireslogin", "invalidsesskey", "requireloginerror"):
            raise SessionExpiredError(code)
        raise LmsError(f"{method}: {code}: {exc.get('message')}")
    return item["data"]

assignment(cmid)

Shortcut for module(cmid, "assign").

Source code in hse_lms/client.py
def assignment(self, cmid: int) -> ModuleDetail:
    """Shortcut for ``module(cmid, "assign")``."""
    return self.module(cmid, "assign")

close()

Close the HTTP connection pool.

Source code in hse_lms/client.py
def close(self) -> None:
    """Close the HTTP connection pool."""
    self.http.close()

course(course_id, include_text=False)

Sections of a course with their visible modules.

Parameters:

Name Type Description Default
course_id int

course id from courses.

required
include_text bool

also read label texts and section summaries (one extra page load).

False
Source code in hse_lms/client.py
@_session
def course(self, course_id: int, include_text: bool = False) -> CourseContents:
    """Sections of a course with their visible modules.

    Args:
        course_id: course id from `courses`.
        include_text: also read label texts and section summaries (one extra page load).
    """
    st = self.course_state(course_id)
    labels: dict[int, str] = {}
    summaries: dict[int, str] = {}
    if include_text:
        labels, summaries = parsing.labels_and_summaries(self.get(f"/course/view.php?id={int(course_id)}").text)
    cms = {str(c["id"]): c for c in st["cm"]}
    sections = []
    for s in sorted(st["section"], key=lambda s: s["number"]):
        modules = []
        for cmid in s["cmlist"]:
            c = cms.get(str(cmid))
            if not c or not c.get("uservisible"):
                continue
            kind = c.get("module") or (c.get("plugin") or "").removeprefix("mod_")
            self._cm_types[int(c["id"])] = kind
            url = c.get("url") or ""
            modules.append(
                Module(
                    cmid=int(c["id"]),
                    name=c["name"],
                    type=kind,
                    url=url if url and "undefined" not in url else None,
                    visible=bool(c.get("visible", True)),
                    restricted=bool(c.get("hascmrestrictions")),
                    text=labels.get(int(c["id"])),
                )
            )
        sections.append(
            Section(
                id=int(s["id"]),
                number=s["number"],
                title=s["title"],
                visible=bool(s.get("visible", True)),
                restricted=bool(s.get("hasrestrictions")),
                summary=summaries.get(s["number"]),
                modules=modules,
            )
        )
    return CourseContents(course_id=int(course_id), sections=sections)

course_state(course_id)

Raw core_courseformat_get_state: course, sections and modules as Moodle returns them.

Source code in hse_lms/client.py
@_session
def course_state(self, course_id: int) -> dict[str, Any]:
    """Raw ``core_courseformat_get_state``: course, sections and modules as Moodle returns them."""
    raw = self.ajax("core_courseformat_get_state", {"courseid": int(course_id)})
    state: dict[str, Any] = json.loads(raw) if isinstance(raw, str) else raw
    return state

courses(classification='inprogress')

Courses you are enrolled in.

Parameters:

Name Type Description Default
classification str

inprogress, all, future, past, favourites or hidden.

'inprogress'
Source code in hse_lms/client.py
@_session
def courses(self, classification: str = "inprogress") -> list[Course]:
    """Courses you are enrolled in.

    Args:
        classification: ``inprogress``, ``all``, ``future``, ``past``, ``favourites`` or ``hidden``.
    """
    offset, raw = 0, []
    while True:
        d = self.ajax(
            "core_course_get_enrolled_courses_by_timeline_classification",
            {"offset": offset, "limit": 12, "classification": classification, "sort": "fullname"},
        )
        raw += d["courses"]
        if not d["courses"] or d["nextoffset"] == offset:
            break
        offset = d["nextoffset"]
    return [
        Course(
            id=c["id"],
            fullname=c["fullname"],
            shortname=c.get("shortname", ""),
            category=c.get("coursecategory"),
            progress=c.get("progress") if c.get("hasprogress") else None,
            start=self._dt(c.get("startdate")),
            end=self._dt(c.get("enddate")),
            favourite=bool(c.get("isfavourite")),
            hidden=bool(c.get("hidden")),
            url=c.get("viewurl") or f"{BASE_URL}/course/view.php?id={c['id']}",
        )
        for c in raw
    ]

deadlines(days_back=0, days_ahead=60, limit=50)

Dated events (due dates, quiz closing times) from the LMS calendar across all courses.

Source code in hse_lms/client.py
@_session
def deadlines(self, days_back: int = 0, days_ahead: int = 60, limit: int = 50) -> list[Deadline]:
    """Dated events (due dates, quiz closing times) from the LMS calendar across all courses."""
    now = int(time.time())
    d = self.ajax(
        "core_calendar_get_action_events_by_timesort",
        {"limitnum": limit, "timesortfrom": now - 86400 * days_back, "timesortto": now + 86400 * days_ahead},
    )
    out = []
    for e in d["events"]:
        url = e.get("url")
        cmid = (parse_qs(urlparse(url).query).get("id") or [""])[0] if url else ""
        action = e.get("action") or {}
        out.append(
            Deadline(
                name=e["name"],
                course_id=e["course"]["id"],
                course=e["course"]["fullname"],
                type=e.get("modulename"),
                cmid=int(cmid) if cmid.isdigit() else None,
                due=datetime.fromtimestamp(e["timesort"], self.tz),
                overdue=bool(e.get("overdue")),
                actionable=bool(action.get("actionable")),
                action=action.get("name"),
                url=url,
            )
        )
    return out

download(target, dest_dir='.')

Save a file into dest_dir: a pluginfile.php URL or the cmid of a resource module.

Returns:

Type Description
Path

The saved path; the name comes from the server, stripped of directories.

Source code in hse_lms/client.py
def download(self, target: str | int, dest_dir: Path | str = ".") -> Path:
    """Save a file into ``dest_dir``: a ``pluginfile.php`` URL or the cmid of a resource module.

    Returns:
        The saved path; the name comes from the server, stripped of directories.
    """
    name, content = self.read_file(target)
    dest = Path(dest_dir).expanduser() / name
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_bytes(content)
    return dest

forum(cmid, limit=10, posts_per_discussion=20)

Latest discussions of a forum with their posts. Each discussion costs one request.

Source code in hse_lms/client.py
@_session
def forum(self, cmid: int, limit: int = 10, posts_per_discussion: int = 20) -> list[Discussion]:
    """Latest discussions of a forum with their posts. Each discussion costs one request."""
    topics = parsing.forum_discussions(self.get(f"/mod/forum/view.php?id={int(cmid)}").text)
    out = []
    for did, title in topics[:limit]:
        d = parsing.discussion(did, title, self.get(f"/mod/forum/discuss.php?d={did}").text, BASE_URL)
        d.posts = d.posts[:posts_per_discussion]
        out.append(d)
    return out

get(path, max_redirects=5)

GET a page of edu.hse.ru, following redirects only inside edu.hse.ru.

Source code in hse_lms/client.py
def get(self, path: str, max_redirects: int = 5) -> httpx.Response:
    """GET a page of edu.hse.ru, following redirects only inside edu.hse.ru."""
    url = urljoin(BASE_URL, path)
    if not _host_ok(url, {LMS_HOST}):
        raise UnsafeRedirectError(_describe(url))
    for _ in range(max_redirects + 1):
        r = self._request("GET", url)
        if r.status_code not in _REDIRECT:
            return r
        url = self._next(url, r)
    raise UnsafeRedirectError("too many redirects")

grades(course_id)

Your grade report for a course (/grade/report/user).

Source code in hse_lms/client.py
@_session
def grades(self, course_id: int) -> list[GradeItem]:
    """Your grade report for a course (``/grade/report/user``)."""
    return parsing.grades(self.get(f"/grade/report/user/index.php?id={int(course_id)}").text)

login(password_prompt=None)

Make sure there is a live session: reuse it, renew it via SSO, or log in with the password.

Parameters:

Name Type Description Default
password_prompt Callable[[str], str | None] | None

asked for the password when no stored one is found (CLI uses getpass).

None

Raises:

Type Description
SessionExpiredError

the session is dead and there are no credentials (or passwords are disallowed).

LoginError

Keycloak rejected the password or asked for something the client cannot do.

UnsafeRedirectError

the login chain left edu.hse.ru / saml.hse.ru.

Source code in hse_lms/client.py
def login(self, password_prompt: Callable[[str], str | None] | None = None) -> SessionInfo:
    """Make sure there is a live session: reuse it, renew it via SSO, or log in with the password.

    Args:
        password_prompt: asked for the password when no stored one is found (CLI uses getpass).

    Raises:
        SessionExpiredError: the session is dead and there are no credentials (or passwords are disallowed).
        LoginError: Keycloak rejected the password or asked for something the client cannot do.
        UnsafeRedirectError: the login chain left edu.hse.ru / saml.hse.ru.
    """
    with self._lock:
        try:
            self._read_my()
            self.login_path = "session"
        except SessionExpiredError:
            for c in list(self.http.cookies.jar):
                if c.name.startswith("MoodleSession"):
                    self.http.cookies.jar.clear(c.domain, c.path, c.name)
            self.login_path = self._sso(password_prompt)
            self._read_my()
        self.store.save(self.http.cookies)
        return SessionInfo(userid=self.userid, login_path=self.login_path)

module(cmid, type=None)

Contents of one activity: description, dates, files and, by type, submission status, page text, quiz info or link target.

Parameters:

Name Type Description Default
cmid int

course module id, the id= of /mod/<type>/view.php.

required
type str | None

assign, quiz, page, url, folder, resource, forum... Optional for modules this client already saw in course.

None

Raises:

Type Description
ValueError

the type is unknown.

Source code in hse_lms/client.py
@_session
def module(self, cmid: int, type: str | None = None) -> ModuleDetail:
    """Contents of one activity: description, dates, files and, by type, submission status, page text,
    quiz info or link target.

    Args:
        cmid: course module id, the ``id=`` of ``/mod/<type>/view.php``.
        type: ``assign``, ``quiz``, ``page``, ``url``, ``folder``, ``resource``, ``forum``... Optional for
            modules this client already saw in `course`.

    Raises:
        ValueError: the type is unknown.
    """
    cmid = int(cmid)
    kind = type or self._cm_types.get(cmid)
    if not kind:
        raise ValueError("module type unknown: pass type (assign, quiz, page, url, folder, resource, forum)")
    if kind in ("url", "resource"):
        got = self._module_by_redirect(cmid, kind)
        if isinstance(got, ModuleDetail):
            return got
        html = got
    else:
        html = self.get(f"/mod/{kind}/view.php?id={cmid}").text
    info = parsing.common(html, BASE_URL)
    detail = ModuleDetail(
        cmid=cmid,
        type=kind,
        title=info.title,
        dates=info.dates,
        description=info.description,
        files=info.files,
    )
    if kind == "assign":
        detail.submission = parsing.submission_status(html, BASE_URL)
    elif kind == "quiz":
        detail.quiz_info = parsing.quiz_info(html)
    elif kind == "page":
        detail.text = parsing.page_body(html)
    elif kind == "url":
        detail.target_url = parsing.url_target(html)
    return detail

read_file(target)

(file name, content) of a pluginfile.php URL or of a resource module (by cmid), in memory.

Raises:

Type Description
ValueError

the target is a page with zero or several files.

UnsafeRedirectError

the URL or its redirects leave edu.hse.ru.

Source code in hse_lms/client.py
@_session
def read_file(self, target: str | int) -> tuple[str, bytes]:
    """``(file name, content)`` of a ``pluginfile.php`` URL or of a resource module (by cmid), in memory.

    Raises:
        ValueError: the target is a page with zero or several files.
        UnsafeRedirectError: the URL or its redirects leave edu.hse.ru.
    """
    url = f"/mod/resource/view.php?id={int(target)}" if str(target).isdigit() else self._check_url(str(target))
    got = self._fetch(url)
    if got.kind == "html":
        links = parsing.file_refs(parsing.soup(got.html), BASE_URL, own_submission=False)
        if len(links) != 1:
            shown = ", ".join(f.url for f in links[:10])
            raise ValueError(f"{url} is a page with {len(links)} files, pass one of their URLs: {shown}")
        got = self._fetch(links[0].url)
    if got.kind != "file":
        raise UnsafeRedirectError(f"points outside edu.hse.ru: {got.url}")
    return got.name, got.content

submit_assignment(cmid, files)

Upload files as your submission and save it. Needs allow_write=True.

Refuses an assignment that already has submitted files (replacing is not supported yet). Checks the number, size and extensions of the files against the assignment settings first, and after saving downloads every file back and compares SHA-256.

Raises:

Type Description
WriteNotAllowedError

the client is read-only.

SubmissionError

Moodle refused, or a file did not come back intact.

Source code in hse_lms/client.py
@_session
def submit_assignment(self, cmid: int, files: Iterable[FileInput]) -> SubmitResult:
    """Upload files as your submission and save it. Needs ``allow_write=True``.

    Refuses an assignment that already has submitted files (replacing is not supported yet). Checks the
    number, size and extensions of the files against the assignment settings first, and after saving
    downloads every file back and compares SHA-256.

    Raises:
        WriteNotAllowedError: the client is read-only.
        SubmissionError: Moodle refused, or a file did not come back intact.
    """
    if not self.allow_write:
        raise WriteNotAllowedError("this client is read-only; create it with allow_write=True to submit")
    items = _load_files(files)
    view = f"/mod/assign/view.php?id={int(cmid)}"
    before = parsing.submission_status(self.get(view).text, BASE_URL)
    if before is None:
        raise SubmissionError("no submission status on the page: not an assignment or no access")
    if before.files:
        names = ", ".join(f.name for f in before.files)
        raise SubmissionError(f"the submission already has files: {names}; replacing is not supported yet")
    form = _SubmissionForm.read(self.get(f"{view}&action=editsubmission").text)
    form.check(items)
    for name, body in items:
        self._upload(form, name, body)
    r = self._request(
        "POST", f"{BASE_URL}/mod/assign/view.php", data={**form.hidden, "submitbutton": "Save changes"}
    )
    if r.status_code not in _REDIRECT:
        errors = parsing.form_errors(r.text)
        raise SubmissionError(
            "the form was not accepted: " + ("; ".join(errors) if errors else f"HTTP {r.status_code}")
        )
    self._next(f"{BASE_URL}/mod/assign/view.php", r)
    after = parsing.submission_status(self.get(view).text, BASE_URL) or SubmissionStatus()
    sent = {name: hashlib.sha256(body).hexdigest() for name, body in items}
    verified = [
        f.name
        for f in after.files
        if f.name in sent and hashlib.sha256(self.read_file(f.url)[1]).hexdigest() == sent[f.name]
    ]
    missing = sorted(set(sent) - set(verified))
    if missing:
        raise SubmissionError("saved, but these files did not come back intact: " + ", ".join(missing))
    return SubmitResult(cmid=int(cmid), uploaded=list(sent), verified=verified, status=after)

whoami()

Check the session (logging in again if needed) and return who is logged in.

Source code in hse_lms/client.py
@_session
def whoami(self) -> SessionInfo:
    """Check the session (logging in again if needed) and return who is logged in."""
    return SessionInfo(userid=self.userid, login_path=self.login_path or "session")

LmsError

Bases: Exception

Base class for all hse_lms errors.

Source code in hse_lms/errors.py
class LmsError(Exception):
    """Base class for all hse_lms errors."""

LoginError

Bases: LmsError

Keycloak rejected the password, asked for a second factor or captcha, or showed an unknown page.

Source code in hse_lms/errors.py
class LoginError(LmsError):
    """Keycloak rejected the password, asked for a second factor or captcha, or showed an unknown page."""

MethodNotAvailableError

Bases: LmsError

The AJAX method is not exposed to browser sessions on edu.hse.ru (servicenotavailable).

Source code in hse_lms/errors.py
class MethodNotAvailableError(LmsError):
    """The AJAX method is not exposed to browser sessions on edu.hse.ru (servicenotavailable)."""

SessionExpiredError

Bases: LmsError

The LMS session is dead and the client is not allowed (or not able) to log in again.

Source code in hse_lms/errors.py
class SessionExpiredError(LmsError):
    """The LMS session is dead and the client is not allowed (or not able) to log in again."""

SubmissionError

Bases: LmsError

Moodle refused the upload or the form, or the uploaded file did not come back intact.

Source code in hse_lms/errors.py
class SubmissionError(LmsError):
    """Moodle refused the upload or the form, or the uploaded file did not come back intact."""

UnsafeRedirectError

Bases: LmsError

A URL or redirect left the allowed hosts (edu.hse.ru, saml.hse.ru), switched to http or to another port.

Source code in hse_lms/errors.py
class UnsafeRedirectError(LmsError):
    """A URL or redirect left the allowed hosts (edu.hse.ru, saml.hse.ru), switched to http or to another port."""

WriteNotAllowedError

Bases: LmsError

A write operation (submitting an assignment) was called on a client created without allow_write=True.

Source code in hse_lms/errors.py
class WriteNotAllowedError(LmsError):
    """A write operation (submitting an assignment) was called on a client created without allow_write=True."""