chuvsu-js 5.4.1 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +32 -3
  2. package/dist/common/http.d.ts +3 -1
  3. package/dist/common/http.js +9 -2
  4. package/dist/{tt/utils → common}/lesson-type.d.ts +4 -2
  5. package/dist/{tt/utils → common}/lesson-type.js +17 -2
  6. package/dist/core.d.ts +13 -5
  7. package/dist/core.js +7 -2
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/lk/client.d.ts +23 -1
  11. package/dist/lk/client.js +95 -0
  12. package/dist/lk/parse/grade-value.d.ts +4 -0
  13. package/dist/lk/parse/grade-value.js +16 -0
  14. package/dist/lk/parse/portfolio-content.d.ts +10 -0
  15. package/dist/lk/parse/portfolio-content.js +116 -0
  16. package/dist/lk/parse/portfolio-grades.d.ts +8 -0
  17. package/dist/lk/parse/portfolio-grades.js +41 -0
  18. package/dist/lk/parse/portfolio-performance.d.ts +2 -0
  19. package/dist/lk/parse/portfolio-performance.js +44 -0
  20. package/dist/lk/parse/portfolio.d.ts +6 -0
  21. package/dist/lk/parse/portfolio.js +64 -0
  22. package/dist/lk/parse/webinar-lesson.d.ts +7 -0
  23. package/dist/lk/parse/webinar-lesson.js +28 -0
  24. package/dist/lk/parse/webinars.d.ts +3 -0
  25. package/dist/lk/parse/webinars.js +67 -0
  26. package/dist/lk/portfolio-types.d.ts +113 -0
  27. package/dist/lk/portfolio-types.js +1 -0
  28. package/dist/lk/types.d.ts +29 -0
  29. package/dist/{tt → lk}/webinars.d.ts +3 -1
  30. package/dist/lk/webinars.js +52 -0
  31. package/dist/parsers.d.ts +3 -1
  32. package/dist/parsers.js +3 -1
  33. package/dist/tt/client.d.ts +1 -11
  34. package/dist/tt/client.js +1 -45
  35. package/dist/tt/domain/types.d.ts +1 -1
  36. package/dist/tt/observations.js +2 -1
  37. package/dist/tt/parse/index.d.ts +0 -1
  38. package/dist/tt/parse/index.js +0 -1
  39. package/dist/tt/types.d.ts +0 -21
  40. package/dist/tt/utils/index.d.ts +0 -1
  41. package/dist/tt/utils/index.js +0 -1
  42. package/dist/webinar/client.d.ts +52 -0
  43. package/dist/webinar/client.js +184 -0
  44. package/dist/webinar/ddp.d.ts +31 -0
  45. package/dist/webinar/ddp.js +208 -0
  46. package/dist/webinar/events.d.ts +6 -0
  47. package/dist/webinar/events.js +38 -0
  48. package/dist/webinar/gateway.d.ts +30 -0
  49. package/dist/webinar/gateway.js +114 -0
  50. package/dist/webinar/media-protocol.d.ts +9 -0
  51. package/dist/webinar/media-protocol.js +24 -0
  52. package/dist/webinar/media-types.d.ts +10 -0
  53. package/dist/webinar/media-types.js +1 -0
  54. package/dist/webinar/media.d.ts +21 -0
  55. package/dist/webinar/media.js +76 -0
  56. package/dist/webinar/parse.d.ts +14 -0
  57. package/dist/webinar/parse.js +113 -0
  58. package/dist/webinar/playback.d.ts +32 -0
  59. package/dist/webinar/playback.js +188 -0
  60. package/dist/webinar/socket.d.ts +3 -0
  61. package/dist/webinar/socket.js +18 -0
  62. package/dist/webinar/state.d.ts +4 -0
  63. package/dist/webinar/state.js +98 -0
  64. package/dist/webinar/types.d.ts +148 -0
  65. package/dist/webinar/types.js +12 -0
  66. package/docs/student-portal.md +151 -0
  67. package/docs/testing.md +13 -0
  68. package/docs/v5-migration.md +25 -2
  69. package/docs/webinar.md +145 -0
  70. package/package.json +2 -2
  71. package/dist/tt/parse/webinars.d.ts +0 -2
  72. package/dist/tt/parse/webinars.js +0 -97
  73. package/dist/tt/webinars.js +0 -39
@@ -0,0 +1,148 @@
1
+ /** Participant credentials. Pass only to the authenticated student's browser. */
2
+ export interface WebinarSession {
3
+ server: {
4
+ origin: string;
5
+ version: string;
6
+ build: number | null;
7
+ };
8
+ protocol: "ddp";
9
+ mediaBackend: "kurento";
10
+ sessionToken: string;
11
+ authToken: string;
12
+ externalUserId: string;
13
+ user: {
14
+ id: string;
15
+ name: string;
16
+ role: string;
17
+ };
18
+ meeting: {
19
+ id: string;
20
+ name: string;
21
+ voiceBridge: string;
22
+ };
23
+ connections: {
24
+ state: string;
25
+ media: string;
26
+ };
27
+ iceServers: RTCIceServer[];
28
+ features: {
29
+ chat: boolean;
30
+ notes: boolean;
31
+ audio: boolean;
32
+ video: boolean;
33
+ screen: boolean;
34
+ raiseHand: boolean;
35
+ presentationDownload: boolean;
36
+ };
37
+ notesUrl: string | null;
38
+ publicChatId: string;
39
+ chatPageSize: number;
40
+ maxMessageLength: number;
41
+ }
42
+ export interface WebinarUser {
43
+ id: string;
44
+ name: string;
45
+ role: string;
46
+ presenter: boolean;
47
+ moderator: boolean;
48
+ locked: boolean;
49
+ raisedHand: boolean;
50
+ emoji: string;
51
+ audio: {
52
+ joined: boolean;
53
+ listenOnly: boolean;
54
+ muted: boolean;
55
+ speaking: boolean;
56
+ };
57
+ }
58
+ export interface WebinarChat {
59
+ id: string;
60
+ name: string;
61
+ private: boolean;
62
+ userIds: string[];
63
+ }
64
+ export interface WebinarMessage {
65
+ id: string;
66
+ chatId: string;
67
+ senderId: string;
68
+ senderName: string | null;
69
+ timestamp: number;
70
+ /** Plain text: render as text, never as HTML. */
71
+ text: string;
72
+ }
73
+ export interface WebinarSlide {
74
+ id: string;
75
+ presentationId: string;
76
+ number: number;
77
+ current: boolean;
78
+ svgUrl: string | null;
79
+ thumbnailUrl: string | null;
80
+ textUrl: string | null;
81
+ text: string;
82
+ viewport: {
83
+ x: number;
84
+ y: number;
85
+ width: number;
86
+ height: number;
87
+ } | null;
88
+ }
89
+ export interface WebinarPresentation {
90
+ id: string;
91
+ name: string;
92
+ current: boolean;
93
+ downloadable: boolean;
94
+ slides: WebinarSlide[];
95
+ }
96
+ export interface WebinarMediaStream {
97
+ id: string;
98
+ kind: "camera" | "screen";
99
+ userId: string | null;
100
+ hasAudio: boolean;
101
+ }
102
+ export interface WebinarNotes {
103
+ revision: number;
104
+ readUrl: string | null;
105
+ editUrl: string | null;
106
+ }
107
+ export interface WebinarSnapshot {
108
+ users: WebinarUser[];
109
+ chats: WebinarChat[];
110
+ messages: WebinarMessage[];
111
+ presentations: WebinarPresentation[];
112
+ streams: WebinarMediaStream[];
113
+ notes: WebinarNotes | null;
114
+ ended: boolean;
115
+ }
116
+ export type WebinarEvent = {
117
+ type: "change";
118
+ collection: string;
119
+ } | {
120
+ type: "message";
121
+ message: WebinarMessage;
122
+ } | {
123
+ type: "disconnected";
124
+ } | {
125
+ type: "error";
126
+ error: Error;
127
+ };
128
+ /** Minimal native/Undici WebSocket contract, shared by both runtimes. */
129
+ export interface WebinarSocket {
130
+ readonly readyState: number;
131
+ send(data: string): void;
132
+ close(code?: number, reason?: string): void;
133
+ addEventListener(type: "open" | "close" | "error", listener: () => void): void;
134
+ addEventListener(type: "message", listener: (event: {
135
+ data: unknown;
136
+ }) => void): void;
137
+ }
138
+ export type WebinarSocketFactory = (url: string) => WebinarSocket;
139
+ export interface WebinarClientOptions {
140
+ socketFactory?: WebinarSocketFactory;
141
+ timeout?: number;
142
+ }
143
+ export declare class WebinarProtocolError extends Error {
144
+ constructor(message: string);
145
+ }
146
+ export declare class WebinarPermissionError extends Error {
147
+ constructor(message: string);
148
+ }
@@ -0,0 +1,12 @@
1
+ export class WebinarProtocolError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = "WebinarProtocolError";
5
+ }
6
+ }
7
+ export class WebinarPermissionError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "WebinarPermissionError";
11
+ }
12
+ }
@@ -0,0 +1,151 @@
1
+ # Student portal: webinars and portfolio
2
+
3
+ All new methods belong to `StudentPortalClient` from `chuvsu-js` or
4
+ `chuvsu-js/node`. Pure HTML parsers are also available from `chuvsu-js/parsers`.
5
+ Types and lesson matching helpers are available from `chuvsu-js/browser`.
6
+
7
+ ```ts
8
+ import { StudentPortalClient, TimetableClient, attachWebinars, parseLocalDate } from "chuvsu-js";
9
+
10
+ const portal = new StudentPortalClient({
11
+ cache: { portfolio: 60_000, webinars: 15_000 },
12
+ });
13
+ await portal.login({ email, password });
14
+
15
+ // GET the portal's current day; no machine-local date is sent.
16
+ const page = await portal.getWebinarPage();
17
+ const webinars = page.webinars;
18
+ // Equivalent listing-only helper: await portal.getWebinars();
19
+
20
+ const timetable = new TimetableClient();
21
+ await timetable.loginAsGuest();
22
+ const groupId = await portal.getTimetableGroupId();
23
+ if (groupId !== null && page.date) {
24
+ const schedule = await timetable.getGroupSchedule(groupId);
25
+ const lessons = schedule.on(parseLocalDate(page.date));
26
+ const linked = attachWebinars(lessons, webinars);
27
+ }
28
+
29
+ const portfolio = await portal.getPortfolio();
30
+ console.log(portfolio.student.fields, portfolio.grades);
31
+ ```
32
+
33
+ ## Webinar listings and links
34
+
35
+ For participant sessions, live users/chat, presentations and explicit room
36
+ actions, see [Live webinars](webinar.md).
37
+
38
+ `getWebinarPage()` returns `{ date, availableDates, webinars }`.
39
+ `getWebinars()` returns just the rows. An optional `{ date: "2026-10-12" }`
40
+ filters the listing through LK's `day` form field. Availability depends on LK;
41
+ a response for a different date throws `ParseError`. The current live page
42
+ exposed today and upcoming dates, so callers should inspect `availableDates`
43
+ rather than assume historical access.
44
+
45
+ Each row includes:
46
+
47
+ - `subject`: discipline, without the type/teacher/group suffix.
48
+ - `title`: webinar topic, as rendered by LK.
49
+ - `scheduledDate`, `slotNumber`, `time`, `type` (`LessonType`), `teacher`, `groups`, `subgroup`.
50
+ - `server`, `completedAt`, `joinAvailable` and `raw` discipline-cell text.
51
+ - `id`: LK join ID, or `null` when no join button is exposed.
52
+
53
+ Completed and pending rows remain present even when no URL can be obtained.
54
+ Dates come from the page. If a saved page has no date, its webinars cannot
55
+ be attached to a particular dated lesson.
56
+
57
+ To resolve a join URL, explicitly call:
58
+
59
+ ```ts
60
+ const webinar = webinars.find((row) => row.joinAvailable && row.id !== null);
61
+ if (webinar?.id) {
62
+ const url = await portal.getWebinarJoinUrl({ webinarId: webinar.id });
63
+ // The caller decides whether to open the URL.
64
+ }
65
+ ```
66
+
67
+ This method uses the authenticated LK session and `POST /student/joinweb.php`
68
+ with `idw`; separate TT credentials and `idType` are no longer used. URLs are
69
+ not cached or automatically opened. HTTP(S) URLs are accepted; malformed or
70
+ unsuccessful responses throw `ParseError`. The endpoint contract was inspected
71
+ in LK JavaScript and verified with mocked responses and live URL retrieval.
72
+
73
+ `findWebinar(lesson, webinars)` returns a unique compatible row.
74
+ `findWebinars` returns all candidates. Matching checks actual scheduled date,
75
+ slot when known, exact time range, normalized discipline, type, and known
76
+ group/subgroup/teacher data. Cancelled lessons never match. Name comparison
77
+ normalizes case, whitespace and `ё`; it does not guess equivalence between
78
+ full names and initials. Ambiguous rows require caller selection.
79
+ `attachWebinars` preserves lesson IDs and never changes repository records.
80
+
81
+ ## Portfolio
82
+
83
+ `getPortfolio()` discovers the portfolio link from the authenticated home
84
+ page and fetches it. The site resolves its own portfolio landing URL to the
85
+ current student's page; no student ID needs to be supplied. `getPortfolioUrl()`
86
+ returns the canonical URL from the same parsed/cached result.
87
+
88
+ The returned `StudentPortfolio` contains:
89
+
90
+ - `id`, `url`, `student.fullName`, `student.photoUrl`, and `student.fields`.
91
+ Identity-field keys retain LK's Russian labels without the trailing colon.
92
+ - `grades`: semester, subject code, discipline, assessment (`LessonType`),
93
+ grade (`number | boolean | null`), tooltips, and optional referral metadata.
94
+ - `controlWeeks`: semester, discipline and numeric grades (`number | null`) for each week.
95
+ - `performance`: discipline, attendance cells and planned activity tables.
96
+ - `sections`: every top-level tab in page order, including curriculum,
97
+ programs, achievements, interests, practices, coursework and thesis.
98
+
99
+ Section content is a tree of `text`, `heading`, `group`, `link`, `image`, and
100
+ `table` entries. Tables preserve every row/cell, header flags, spans, tooltips,
101
+ links and nested content. Nested tab labels are group labels. Document URLs
102
+ are resolved against the portfolio page; no linked files are downloaded.
103
+ Unknown tabs are preserved without requiring a parser update.
104
+
105
+ Attendance expands merged month/day headers into individual cells, retaining
106
+ month label, day, slot, lesson type (`LessonType`), subgroup and raw mark (`+`, `Н`, grade or
107
+ empty). The page does not reliably identify the journal year, so absolute dates
108
+ are not invented. Activity `content` preserves separate grade/date fields even
109
+ when their displayed text is concatenated. Numeric grades such as `4 (Хорошо)` become `4`; `Зачтено` becomes `true`,
110
+ `Не зачтено` becomes `false`. Missing/unrecognized grades become `null`;
111
+ control-week `"0"` becomes numeric `0`. No extra source-text fields are added.
112
+ Assessment labels such as `Экзамен`, `Зачет`, `Зачет с оценкой`, and
113
+ `Курсовой проект` use the existing `LessonType` values. Labels without an
114
+ existing enum equivalent use `LessonType.Unknown`. Existing enum IDs remain unchanged; `StateExam = 12` and `ThesisDefense = 13`
115
+ distinguish state exams and thesis defenses. Referral endpoint IDs remain
116
+ separate from domain lesson types.
117
+
118
+ Referral `semester`, `disciplineId`, `lessonTypeId`, `type`, `key`, and `code`
119
+ are parsed from the existing button. **No referral ordering method is provided
120
+ or called.** Scripts, edit/order buttons, and action-dialog fields are excluded
121
+ from section content. Parsing never evaluates scripts or follows links.
122
+
123
+ Offline parsing:
124
+
125
+ ```ts
126
+ import { parsePortfolio, parsePortfolioUrl, parseWebinarPage } from "chuvsu-js/parsers";
127
+
128
+ const portfolio = parsePortfolio(portfolioHtml);
129
+ const landingUrl = parsePortfolioUrl(homeHtml);
130
+ const page = parseWebinarPage(webinarsHtml);
131
+ ```
132
+
133
+ Only same-origin portfolio landing/index routes can be discovered from home.
134
+ Unrelated pages, missing identity and mismatched student IDs are rejected before
135
+ caching. Cache TTLs are milliseconds. Keep webinar TTL short because LK refreshes
136
+ availability frequently. Shared cache adapters should be scoped to one account,
137
+ as with the existing profile cache.
138
+
139
+ ## Typed-value migration
140
+
141
+ Webinar/journal `type` and grade `assessment` are now `LessonType`, replacing
142
+ short codes and full text labels. Grade consumers should distinguish numbers,
143
+ booleans and `null`; avoid truthiness checks because `false` is a failed credit
144
+ and `0` is a reported control-week score. Updated cache keys skip cached results
145
+ using the old string schema. Generic portfolio section tables remain display
146
+ content; normalized fields are available in `grades`, `controlWeeks`, and
147
+ `performance`.
148
+
149
+ `LessonType` and `parseLessonType` are defined in `common/lesson-type`; LK and
150
+ TT share them. Import from `chuvsu-js` or `chuvsu-js/browser`; the old TT utility
151
+ exports are removed.
package/docs/testing.md CHANGED
@@ -21,3 +21,16 @@
21
21
 
22
22
  Live-тест сравнивает парсер с текущими страницами портала, но не заменяет
23
23
  зафиксированные HTML и ручные эталоны.
24
+
25
+ ## Student portal checks
26
+
27
+ Synthetic LK fixtures cover webinar availability, topics, selected dates,
28
+ lesson matching, all portfolio tabs, grades, control weeks, merged attendance
29
+ headers, activity fields, documents and referral metadata. LK parsers and webinar
30
+ matching participate in `pnpm test:coverage` alongside the timetable core.
31
+ Client contracts use mocked HTTP; automated tests never call a real join or
32
+ referral endpoint.
33
+
34
+ Read-only live verification used login, home navigation, webinar listing and
35
+ own portfolio only. Join URL resolution was checked against the site's
36
+ JavaScript and mocked responses. Live pages and credentials are not fixtures.
@@ -121,7 +121,7 @@ const schedule = await client.getTeacherSchedule(teacherId, {
121
121
  ```
122
122
 
123
123
  `LessonType` хранит тип занятия числом в наблюдениях, репозитории и снимке.
124
- `parseLessonType(code)` переводит код портала в этот индекс. Для неизвестного
124
+ `parseLessonType(code)` переводит код портала или полное название формы контроля в этот индекс. Для неизвестного
125
125
  кода возвращается `LessonType.Unknown`; текстовые расшифровки принадлежат клиенту.
126
126
 
127
127
  Для кода, который работает с разными владельцами одинаково, добавлен общий
@@ -407,13 +407,21 @@ for (const day of days) {
407
407
  import { attachWebinars } from "chuvsu-js";
408
408
 
409
409
  const lessons = schedule.on(date);
410
- const webinars = await client.getWebinars({ date });
410
+ const webinars = await portal.getWebinars(); // StudentPortalClient, current LK day
411
411
  const withWebinars = attachWebinars(lessons, webinars);
412
412
  ```
413
413
 
414
414
  `attachWebinars` возвращает новые объекты `LessonWithWebinar` и не изменяет
415
415
  занятия в репозитории.
416
416
 
417
+ Webinars now belong to LK: use `StudentPortalClient.getWebinars`,
418
+ `getWebinarPage` and `getWebinarJoinUrl({ webinarId })` after `portal.login`.
419
+ The old TT methods and TT parser are removed. The root `parseWebinars` export
420
+ now parses LK HTML. `Webinar.idType` is removed; `id` is nullable because
421
+ completed/pending rows have no join button. Optional listing date is a
422
+ `LocalDate` string, not a `Date`. Matching rejects ambiguity and conflicting
423
+ known groups, subgroups or teachers.
424
+
417
425
  ## Сетка звонков
418
426
 
419
427
  | v4 | v5 |
@@ -498,3 +506,18 @@ const schedule = new Schedule(
498
506
  10. Проверить сессию, переносы, замены, подгруппы и ДОТ на реальных данных.
499
507
 
500
508
  Описание внутренней модели: [`v5-architecture.md`](v5-architecture.md).
509
+
510
+ ## Typed LK values
511
+
512
+ `Webinar.type`, `PortfolioAttendance.type`, and `PortfolioGrade.assessment`
513
+ now reuse `LessonType`. `PortfolioGrade.grade` is `number | boolean | null`:
514
+ `4 (Хорошо)` → `4`, `Зачтено` → `true`, `Не зачтено` → `false`, absent → `null`.
515
+ `PortfolioControlWeek.grades` contains `number | null`; zero remains zero.
516
+ No additional raw grade or assessment fields are introduced.
517
+
518
+ `LessonType.StateExam = 12` and `LessonType.ThesisDefense = 13` distinguish
519
+ state exams and thesis defenses. Existing enum values 0–11 are unchanged.
520
+
521
+ Shared lesson/assessment types now live in `common/lesson-type`. Import
522
+ `LessonType` and `parseLessonType` from the package root or browser entrypoint.
523
+ The old TT utility exports are removed without compatibility shims.
@@ -0,0 +1,145 @@
1
+ # Live webinars
2
+
3
+ `StudentPortalClient.openWebinar()` creates a participant session on the actual
4
+ server from LK's signed join URL. This can register room presence. It does not
5
+ connect microphone, camera, audio playback, send chat, or modify an LK profile.
6
+ `getWebinarJoinUrl()` still resolves a link without opening it.
7
+
8
+ ```ts
9
+ const gateway = await portal.openWebinar({ webinarId });
10
+ const room = await gateway.connect(); // Backend state connection, no media.
11
+ try {
12
+ console.log(room.getUsers(), room.getPresenter(), room.getMessages());
13
+ const presentation = room.getCurrentPresentation();
14
+ if (presentation) {
15
+ for (const slide of presentation.slides) {
16
+ const file = await gateway.downloadSlide({ slide });
17
+ // file.body: Buffer; file.contentType; file.filename.
18
+ }
19
+ }
20
+ } finally {
21
+ room.close();
22
+ }
23
+ ```
24
+
25
+ For a custom frontend, send `gateway.getSession()` to **that student's browser**,
26
+ then instantiate `WebinarClient` from `chuvsu-js/browser` there and call
27
+ `connect()`. This connects state directly to BBB rather than through your backend.
28
+ Use either backend or browser state connection; duplicate connections for the
29
+ same participant can interfere with each other. Do not log, persist in shared
30
+ caches, or expose participant session credentials to other users. The session
31
+ contains BBB credentials, never LK email/password or cookies.
32
+
33
+ ## State and events
34
+
35
+ - `getUsers()`, `getPresenter()`, `getModerators()` distinguish participant roles.
36
+ Presenter/moderator does not automatically mean the scheduled lecturer.
37
+ - `getChats()` exposes only chats published to this participant.
38
+ - `getMessages({ chatId? })` reads accumulated history/live messages.
39
+ - `loadMessages({ chatId?, page? })` fetches a historical page, starting at 1.
40
+ `connect()` loads the first public-chat page; subsequent pages are explicit.
41
+ History and live messages deduplicate by ID and sort chronologically. Sender
42
+ names also resolve for departed users. Text is plain text; do not render as HTML.
43
+ - `getPresentations()`, `getCurrentPresentation()` include sorted slides, SVG,
44
+ thumbnail/text URLs, active slide and viewport. Slide URLs may need backend HTTP
45
+ relay because of CORS; use `gateway.downloadSlide()` for bytes.
46
+ - `getMediaStreams()` lists published cameras/screens; meeting audio is separate.
47
+ - `getNotes()` returns revision and existing read/edit pad URLs when published.
48
+ It never creates or edits a notes pad.
49
+ - `getSnapshot()` returns a fresh detached object; modifying it does not change
50
+ the room or local state.
51
+
52
+ ```ts
53
+ const unsubscribe = room.subscribe((event) => {
54
+ if (event.type === "message") appendMessage(event.message);
55
+ if (event.type === "change") refresh(room.getSnapshot());
56
+ });
57
+ // Or:
58
+ for await (const event of room.events({ signal, bufferSize: 512 })) {
59
+ handle(event);
60
+ }
61
+ unsubscribe();
62
+ ```
63
+
64
+ Streams are bounded. Overflow raises an error; refresh the snapshot and resubscribe.
65
+ Connection failures, rejected methods/subscriptions and unsupported versions fail
66
+ explicitly. `close()` releases the connection; create a new session/client to
67
+ reconnect. No automatic reconnect, replay of writes, or settings changes.
68
+
69
+ ## Explicit actions
70
+
71
+ ```ts
72
+ await room.setRaisedHand(true);
73
+ await room.setRaisedHand(false);
74
+ await room.sendMessage({ text: "Hello" }); // Public chat by default.
75
+ const chat = await room.openPrivateChat({ userId });
76
+ await room.sendMessage({ chatId: chat.id, text: "Hello" });
77
+ await room.sendPrivateMessage({ userId, text: "Hello" });
78
+ await room.setMuted(true); // Requires an already connected microphone session.
79
+ ```
80
+
81
+ These methods are never invoked by connection, subscriptions or downloads.
82
+ Meeting locks are checked locally and BBB still enforces participant permissions.
83
+ An accepted method means submitted to BBB; observe live state for confirmation.
84
+
85
+ Original-file download uses `gateway.downloadPresentation({ presentationId })`
86
+ only after a state connection exposes `downloadable: true`. Disabled originals
87
+ are not fetched. SVG slide downloads remain separate from original downloads;
88
+ callers can assemble exported slides into a rendered PDF.
89
+
90
+ ## Direct browser media
91
+
92
+ ```ts
93
+ import { WebinarClient, WebinarMediaClient } from "chuvsu-js/browser";
94
+
95
+ // Session obtained from your authenticated backend, scoped to this student.
96
+ const room = new WebinarClient(session);
97
+ await room.connect();
98
+ const media = new WebinarMediaClient(session, room);
99
+ const audio = await media.listen(); // Explicit listen-only connection.
100
+ audioElement.srcObject = audio.stream;
101
+ await audioElement.play(); // Invoke from a user gesture when autoplay is blocked.
102
+
103
+ const camera = room.getMediaStreams().find((stream) => stream.kind === "camera");
104
+ if (camera) {
105
+ const playback = await media.receiveCamera({ streamId: camera.id });
106
+ videoElement.srcObject = playback.stream;
107
+ }
108
+ // Only when a screen is currently published:
109
+ // const screen = await media.receiveScreen({ signal });
110
+ // screenElement.srcObject = screen.stream;
111
+
112
+ const stats = await audio.getStats();
113
+ audio.onError(handleMediaError);
114
+ audio.onClose(handlePlaybackEnd);
115
+ // Component/page teardown:
116
+ media.close();
117
+ room.close();
118
+ ```
119
+
120
+ Media uses the server's authenticated SFU WebSocket and browser WebRTC directly.
121
+ No backend media receiver or forwarding is required. `listen()` receives the
122
+ mixed room audio, not separate speaker tracks. Every playback exposes `stream`,
123
+ `connection`, `getStats()`, `onError()`, `onClose()`, and idempotent `close()`.
124
+ ICE candidates queue until negotiation is ready. Timeouts, aborts, disconnects
125
+ and remote stream termination release sockets, peers and tracks. Media teardown
126
+ is separate from room state teardown. Browser and network restrictions can still
127
+ require the BBB server's TURN relay.
128
+
129
+ Camera/screen IDs must be currently published to this participant. Camera lists
130
+ respect the moderator-only visibility setting. No microphone or camera is
131
+ captured/published by these receivers. Microphone connection, camera publication,
132
+ programmatic notes editing, and newer server adapters are not implemented in this
133
+ initial API; `setMuted()` only controls an already connected microphone session.
134
+
135
+ ## Server versions
136
+
137
+ Initial adapter supports the inspected **BBB 2.3 Meteor/DDP + Kurento** protocol.
138
+ Version/build and endpoint configuration are read from each server's actual
139
+ HTML5 client, not the REST API's unrelated `version=2.0`. Other versions fail
140
+ explicitly until their participant protocol is implemented and tested. No shared
141
+ BBB integration secret is required or used.
142
+
143
+ Protocol references: [Meteor DDP](https://github.com/meteor/meteor/blob/devel/packages/ddp/DDP.md),
144
+ [BBB 2.3 participant source](https://github.com/bigbluebutton/bigbluebutton/tree/v2.3.0/bigbluebutton-html5/imports/api),
145
+ [external UI configuration](https://docs.bigbluebutton.org/administration/cluster-proxy/).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chuvsu-js",
3
- "version": "5.4.1",
3
+ "version": "5.5.0",
4
4
  "description": "Библиотека для расписания и личного кабинета ЧГУ им. И. Н. Ульянова",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -53,7 +53,7 @@
53
53
  "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
54
54
  "build": "pnpm clean && tsc",
55
55
  "test": "pnpm build && node --test",
56
- "test:coverage": "pnpm build && node --experimental-test-coverage --test-coverage-include='dist/tt/domain/*.js' --test-coverage-include='dist/tt/observations.js' --test-coverage-include='dist/tt/parse/*.js' --test-coverage-include='dist/tt/utils/*.js' --test-coverage-include='dist/tt/webinars.js' --test-coverage-lines=95 --test-coverage-functions=94 --test-coverage-branches=80 --test",
56
+ "test:coverage": "pnpm build && node --experimental-test-coverage --test-coverage-include='dist/tt/domain/*.js' --test-coverage-include='dist/tt/observations.js' --test-coverage-include='dist/tt/parse/*.js' --test-coverage-include='dist/tt/utils/*.js' --test-coverage-include='dist/common/lesson-type.js' --test-coverage-include='dist/lk/webinars.js' --test-coverage-include='dist/lk/parse/*.js' --test-coverage-lines=95 --test-coverage-functions=94 --test-coverage-branches=80 --test",
57
57
  "test:live:schedules": "pnpm build && node --env-file=.env utils/testSchedules.mjs",
58
58
  "fixtures:test": "pnpm build && node --test test/schedule-fixtures.test.mjs",
59
59
  "fixtures:collect": "pnpm build && node --env-file=.env utils/collectScheduleFixtures.mjs"
@@ -1,2 +0,0 @@
1
- import type { Webinar } from "../types.js";
2
- export declare function parseWebinars(html: string): Webinar[];
@@ -1,97 +0,0 @@
1
- import { parseHtml, parseTeacher, parseTime, text, } from "../../common/parse.js";
2
- import { parseGroupsString } from "./groups.js";
3
- import { FLEXIBLE_LESSON_TYPE_RE_I, SUBGROUP_RE } from "./patterns.js";
4
- const GROUP_CODE_RE = /[A-ZА-ЯЁ]{1,}(?:-[A-ZА-ЯЁa-zа-яё0-9]+)+(?:\s*ин)?/u;
5
- function parseDateValue(value) {
6
- const match = value?.match(/^(\d{4})-(\d{2})-(\d{2})$/);
7
- if (!match)
8
- return undefined;
9
- return `${match[1]}-${match[2]}-${match[3]}`;
10
- }
11
- function parseTimeRange(raw) {
12
- const match = raw.match(/(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/);
13
- if (!match)
14
- return null;
15
- return { start: parseTime(match[1]), end: parseTime(match[2]) };
16
- }
17
- function splitLesson(raw) {
18
- const typeMatches = [...raw.matchAll(new RegExp(FLEXIBLE_LESSON_TYPE_RE_I, "gi"))];
19
- const typeMatch = typeMatches.at(-1);
20
- if (!typeMatch || typeMatch.index == null) {
21
- return {
22
- subject: raw,
23
- type: "",
24
- teacherRaw: "",
25
- groupsRaw: "",
26
- };
27
- }
28
- const subject = raw.slice(0, typeMatch.index).trim();
29
- const type = typeMatch[1].replace(/\.$/, "").toLowerCase();
30
- const rest = raw.slice(typeMatch.index + typeMatch[0].length).trim();
31
- const groupMatch = rest.match(GROUP_CODE_RE);
32
- const teacherRaw = groupMatch?.index == null ? rest : rest.slice(0, groupMatch.index).trim();
33
- const groupsRaw = groupMatch?.index == null ? "" : rest.slice(groupMatch.index).trim();
34
- const subgroupMatch = raw.match(SUBGROUP_RE);
35
- return {
36
- subject,
37
- type,
38
- teacherRaw,
39
- groupsRaw,
40
- subgroup: subgroupMatch ? parseInt(subgroupMatch[1]) : undefined,
41
- };
42
- }
43
- function parseWebinarRows(doc, tableSelector, scheduled, fallbackDate) {
44
- const webinars = [];
45
- for (const slotRow of doc.querySelectorAll(`${tableSelector} > tbody > tr`)) {
46
- const slotCells = [...slotRow.children].filter((child) => child.tagName.toLowerCase() === "td");
47
- const timeCell = slotCells[0];
48
- const dataCell = slotCells[1];
49
- if (!timeCell || !dataCell)
50
- continue;
51
- const timeText = text(timeCell);
52
- const timeRange = parseTimeRange(timeText);
53
- if (!timeRange)
54
- continue;
55
- const id = timeCell.querySelector("div")?.getAttribute("id") ?? "";
56
- const idMatch = id.match(/trd(\d{4}-\d{2}-\d{2})t(\d+)/);
57
- const date = parseDateValue(idMatch?.[1]) ?? fallbackDate;
58
- const slotNumber = idMatch ? parseInt(idMatch[2]) : undefined;
59
- for (const row of dataCell.querySelectorAll("table tr")) {
60
- const cells = [...row.children].filter((child) => child.tagName.toLowerCase() === "td");
61
- const lessonCell = cells[0];
62
- const titleCell = cells[1];
63
- if (!lessonCell || !titleCell)
64
- continue;
65
- const button = row.querySelector("button[onclick*=\"jointo\"]");
66
- const onclick = button?.getAttribute("onclick") ?? "";
67
- const joinMatch = onclick.match(/jointo(?:sub)?\('([^']+)',\s*(\d+)\)/);
68
- const raw = text(lessonCell);
69
- const parsed = splitLesson(raw);
70
- webinars.push({
71
- id: joinMatch?.[1] ?? "",
72
- idType: joinMatch ? parseInt(joinMatch[2]) : 1,
73
- scheduled,
74
- scheduledDate: date,
75
- slotNumber,
76
- time: timeRange,
77
- subject: parsed.subject,
78
- type: parsed.type,
79
- teacher: parseTeacher(parsed.teacherRaw),
80
- groups: parseGroupsString(parsed.groupsRaw),
81
- subgroup: parsed.subgroup,
82
- title: text(titleCell),
83
- raw,
84
- });
85
- }
86
- }
87
- return webinars;
88
- }
89
- export function parseWebinars(html) {
90
- const doc = parseHtml(html);
91
- const selectedDate = doc.querySelector('select[name="seldate"] option[selected]')?.getAttribute("value");
92
- const fallbackDate = parseDateValue(selectedDate);
93
- return [
94
- ...parseWebinarRows(doc, "#webstt", true, fallbackDate),
95
- ...parseWebinarRows(doc, "#websttext", false, fallbackDate),
96
- ];
97
- }