### Install chuvsu-js Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Install the chuvsu-js library using npm. ```bash npm install chuvsu-js ``` -------------------------------- ### Initialize and use LkClient for personal data Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Quick start for using LkClient to log in and retrieve personal student data. Supports caching. ```typescript import { LkClient } from "chuvsu-js"; const lk = new LkClient({ cache: 60_000 }); await lk.login({ email: "student@mail.ru", password: "password" }); const data = await lk.getPersonalData(); console.log(`${data.lastName} ${data.firstName}, группа ${data.group}`); // Получить ID группы для использования с TtClient const groupId = await lk.getGroupId(); ``` -------------------------------- ### Get Current Lesson Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Retrieves information about the current lesson. An optional subgroup number can be provided. ```typescript const lesson = schedule.currentLesson({ subgroup?: number }); ``` -------------------------------- ### Initialize and use TtClient for schedules Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Quick start for using TtClient to fetch and display student schedules. Requires guest login or authenticated login. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient(); // Войти гостем (без учётной записи) await tt.loginAsGuest(); // Найти группу по названию const groups = await tt.searchGroup({ name: "КТ-41-24" }); console.log(groups); // [{ id: 8919, name: "КТ-41-24", specialty: "...", profile: "..." }] // Получить расписание группы const schedule = await tt.getSchedule({ groupId: groups[0].id }); // Расписание на сегодня const today = schedule.today(); for (const lesson of today) { console.log( `${lesson.start.hours}:${lesson.start.minutes} — ${lesson.subject} (${lesson.type})`, ); } // С фильтром по подгруппе schedule.today({ subgroup: 1 }); // На завтра schedule.tomorrow(); // На текущую неделю schedule.thisWeek(); // Текущая пара schedule.currentLesson(); ``` -------------------------------- ### Get schedule for a week Source: https://context7.com/artegoser/chuvsu-js/llms.txt Returns all lessons for a specified or the current week of the semester. Can be filtered by subgroup. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); // Текущая неделя const thisWeek = schedule.thisWeek(); // Конкретная неделя семестра (3-я неделя) const week3 = schedule.forWeek(3); console.log(`Занятий на 3-й неделе: ${week3.length}`); // С фильтром подгруппы const week3sub1 = schedule.forWeek(3, { subgroup: 1 }); ``` -------------------------------- ### Implement Redis Cache and S3 Blob Storage Adapters Source: https://context7.com/artegoser/chuvsu-js/llms.txt Provides example implementations for `CacheAdapter` using Redis and `BlobAdapter` using S3. These adapters enable persistent caching and blob storage for the `TtClient`. ```typescript import { TtClient } from "chuvsu-js"; import type { CacheAdapter, BlobAdapter } from "chuvsu-js"; // Пример Redis-адаптера const redisAdapter: CacheAdapter = { async get(category, key) { const val = await redis.get(`chuvsu:${category}:${key}`); return val ? JSON.parse(val) : null; }, async set(category, key, data, ttl) { const opts = ttl && ttl !== Infinity ? { PX: ttl } : {}; await redis.set(`chuvsu:${category}:${key}`, JSON.stringify(data), opts); }, async clear(category) { const pattern = category ? `chuvsu:${category}:*` : "chuvsu:*"; const keys = await redis.keys(pattern); if (keys.length > 0) await redis.del(...keys); }, }; // Пример S3 blob-адаптера const s3Adapter: BlobAdapter = { async get(key) { try { const obj = await s3.getObject({ Bucket: "chuvsu", Key: key }).promise(); return obj.Body as Buffer; } catch { return null; } }, async put(key, data, opts) { await s3.putObject({ Bucket: "chuvsu", Key: key, Body: data, ContentType: opts?.contentType ?? "application/octet-stream", }).promise(); }, }; const tt = new TtClient({ cache: { schedule: 10 * 60_000, teacherPhotos: 7 * 24 * 60 * 60_000, audienceImages: 7 * 24 * 60 * 60_000, }, cacheAdapter: redisAdapter, blobAdapter: s3Adapter, }); ``` -------------------------------- ### Get Audience Images and Floorplan Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetches audience photos, block images, and floor plans as Buffers. Returns null if an image is not available. Requires `node:fs` for writing files. ```typescript import { writeFileSync } from "node:fs"; import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 24 * 60 * 60_000 }); await tt.loginAsGuest(); const audienceId = 42; const [photo, block, floor] = await Promise.all([ tt.getAudienceImage(audienceId), tt.getAudienceBlockImage(audienceId), tt.getAudienceFloorplan(audienceId), ]); if (photo) writeFileSync("aud_photo.jpg", photo); if (block) writeFileSync("aud_block.jpg", block); if (floor) writeFileSync("aud_floor.jpg", floor); console.log("Изображения сохранены"); ``` -------------------------------- ### Get a list of all teachers Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetches a complete list of all teachers, returning objects with their IDs and names. Initializes TtClient with infinite cache. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: Infinity }); await tt.loginAsGuest(); const teachers = await tt.getTeachers(); console.log(`Всего преподавателей: ${teachers.length}`); // [{ id: 653, name: "Иванов Иван Иванович" }, ...] ``` -------------------------------- ### Get Webinar Join URL Source: https://context7.com/artegoser/chuvsu-js/llms.txt Obtains a URL to join a webinar. Requires webinar details and user credentials. Catches `AuthError` for login issues. ```typescript import { TtClient, AuthError } from "chuvsu-js"; const tt = new TtClient(); await tt.loginAsGuest(); const webinars = await tt.getWebinars(); if (webinars.length > 0) { try { const url = await tt.getWebinarJoinUrl({ webinarId: webinars[0].id, idType: webinars[0].idType, email: "student@mail.ru", password: "secret", }); console.log(`Ссылка: ${url}`); // https://bbb.chuvsu.ru/... } catch (e) { if (e instanceof AuthError) { console.error("Ошибка входа в вебинар:", e.message); } } } ``` -------------------------------- ### Semester Utilities Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Provides utility functions for semester-related information, including week numbers and semester start dates. ```APIDOC ## Semester Utilities ### Description Provides utility functions for semester-related information. ### Functions #### getWeekNumber ##### Description Gets the current week number of the semester. ##### Method Signature `schedule.getWeekNumber(date?: Date)` ##### Parameters - **date** (Date) - Optional. The date to get the week number for. Defaults to the current date. #### getSemesterWeeks ##### Description Gets all weeks within the semester. ##### Method Signature `schedule.getSemesterWeeks(weekCount?: number)` ##### Parameters - **weekCount** (number) - Optional. The total number of weeks in the semester. #### getSemesterStart ##### Description Gets the start date of the semester. ##### Method Signature `schedule.getSemesterStart()` ``` ```APIDOC ## Standalone Semester Utilities ### Description Semester utilities are also available as standalone functions. ### Functions #### getSemesterStart ##### Description Gets the start date of the semester. ##### Method Signature `getSemesterStart({ period: Period, year: number })` ##### Parameters - **period** (Period) - Required. The period of the semester (e.g., FallSemester). - **year** (number) - Required. The year of the semester. #### getSemesterWeeks ##### Description Gets all weeks within the semester. ##### Method Signature `getSemesterWeeks({ period: Period })` ##### Parameters - **period** (Period) - Required. The period of the semester (e.g., SpringSemester). #### getWeekNumber ##### Description Gets the current week number of the semester. ##### Method Signature `getWeekNumber({ period: Period })` ##### Parameters - **period** (Period) - Required. The period of the semester (e.g., SpringSemester). ``` -------------------------------- ### Get Faculties with TtClient Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetch a list of all available faculties for the current education type. Requires guest or user login. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: Infinity }); await tt.loginAsGuest(); const faculties = await tt.getFaculties(); // [ // { id: 1, name: "Факультет информатики и вычислительной техники" }, // { id: 2, name: "Юридический факультет" }, // ... // ] for (const f of faculties) { console.log(`[${f.id}] ${f.name}`); } ``` -------------------------------- ### Get All Audiences and Search Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves a full list of all available audiences or searches for audiences by a substring (minimum 3 characters). ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: Infinity }); await tt.loginAsGuest(); // Все аудитории const all = await tt.getAudiences(); console.log(`Аудиторий: ${all.length}`); // Поиск по названию const found = await tt.searchAudience({ name: "301" }); // [{ id: 42, name: "301" }, { id: 43, name: "301а" }] // Найти точно по имени const exact = await tt.findAudienceByName({ name: "301" }); if (exact) console.log(`ID аудитории 301: ${exact.id}`); ``` -------------------------------- ### Get Webinars List Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves a list of webinars for a specified date and faculty. If no options are provided, it fetches webinars for the current day across all faculties. Iterates through webinars to display subject, teacher, time, groups, and title. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 5 * 60_000 }); await tt.loginAsGuest(); // Вебинары на сегодня (все факультеты) const webinars = await tt.getWebinars(); // На конкретную дату и факультет const webinarsFac = await tt.getWebinars({ date: new Date("2025-03-10"), facultyId: 1, }); for (const w of webinars) { console.log(`${w.subject} (${w.teacher.name}) — ${w.timeStart.hours}:${String(w.timeStart.minutes).padStart(2,"0")}`); console.log(` Группы: ${w.groups.join(", ")}`); console.log(` Тема: ${w.title}`); } ``` -------------------------------- ### Get schedule for a specific date Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves lessons for a specified date, considering holidays, rescheduling, and week parity. Supports filtering by subgroup. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); const monday = new Date("2025-02-10"); const lessons = schedule.forDate(monday, { subgroup: 2 }); for (const lesson of lessons) { const start = `${lesson.start.hours}:${String(lesson.start.minutes).padStart(2,"0")}`; const end = `${lesson.end.hours}:${String(lesson.end.minutes).padStart(2,"0")}`; console.log(`${start}–${end} ${lesson.subject} [${lesson.type}]`); if (lesson.isDistance) console.log(" (дистанционно)"); if (lesson.weekParity) console.log(` Чётность: ${lesson.weekParity}`); if (lesson.originalRoom) console.log(` Замена аудитории: ${lesson.originalRoom} → ${lesson.room}`); } // Пример вывода: // 08:00–09:35 Математический анализ [лекция] // 09:45–11:20 Программирование [практика] // Чётность: odd ``` -------------------------------- ### Semester Utilities: getCurrentPeriod, getSemesterStart, getSemesterWeeks, getWeekNumber, getTimeSlots Source: https://context7.com/artegoser/chuvsu-js/llms.txt Provides functions for working with the academic calendar without needing a client instance. Includes determining the current period, semester start date, total weeks in a semester, current week number, and time slots for classes. ```typescript import { getCurrentPeriod, getSemesterStart, getSemesterWeeks, getWeekNumber, getTimeSlots, Period, } from "chuvsu-js"; // Текущий учебный период const period = getCurrentPeriod(); // Period.FallSemester | Period.WinterSession | Period.SpringSemester | Period.SummerSession // Начало семестра const start = getSemesterStart({ period: Period.SpringSemester, year: 2025 }); console.log(start.toLocaleDateString("ru-RU")); // "10.02.2025" // Все недели семестра const weeks = getSemesterWeeks({ period: Period.FallSemester }); // [{ week: 1, start: Date, end: Date }, { week: 2, ... }, ...] console.log(`Семестр: ${weeks.length} недель`); // Номер текущей недели const weekNum = getWeekNumber({ period: Period.SpringSemester }); console.log(`Текущая неделя: ${weekNum}`); // Слоты пар (время начала/конца по номеру пары) const slots = getTimeSlots(); // [{ number: 1, start: {hours:8, minutes:0}, end: {hours:9, minutes:35} }, ...] for (const s of slots) { console.log(`Пара ${s.number}: ${s.start.hours}:${String(s.start.minutes).padStart(2,"0")}-${s.end.hours}:${String(s.end.minutes).padStart(2,"0")}`); } ``` -------------------------------- ### Get Audience Information Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetches detailed information about a specific audience, including building, floor, usage, and image URLs. Requires audience ID. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 24 * 60 * 60_000 }); await tt.loginAsGuest(); const info = await tt.getAudienceInfo(42); if (info) { console.log(info.name); console.log(info.building); console.log(info.floor); console.log(info.usage); console.log(info.audImageUrl); console.log(info.blockImageUrl); console.log(info.floorplanUrl); console.log(info.floorplanRect); } ``` -------------------------------- ### Get Teacher Schedule Source: https://context7.com/artegoser/chuvsu-js/llms.txt Loads the entire schedule for a given teacher. The schedule object provides methods to access daily lessons. Requires teacher ID. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const teachers = await tt.searchTeacher({ name: "Иванов" }); const schedule = await tt.getTeacherSchedule(teachers[0].id); const today = schedule.today(); for (const lesson of today) { console.log(`${lesson.subject} — ${lesson.groups.join(", ")}, ауд. ${lesson.room}`); } ``` -------------------------------- ### Get a group's schedule for all periods Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetches the entire academic schedule for a given group ID, covering all four periods (fall semester, winter session, spring semester, summer session) concurrently. Requires group ID obtained from searchGroup. Provides methods to access schedule for today, tomorrow, current week, specific dates, and current lesson. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const groups = await tt.searchGroup({ name: "КТ-41-24" }); const schedule = await tt.getSchedule(groups[0].id); // Расписание на сегодня const today = schedule.today(); for (const lesson of today) { console.log( `Пара ${lesson.number}: ${lesson.start.hours}:${String(lesson.start.minutes).padStart(2,"0")} — ` + `${lesson.subject} (${lesson.type}), ауд. ${lesson.room}, ${lesson.teacher.name}` ); } // С фильтром по подгруппе const sub1 = schedule.today({ subgroup: 1 }); // На завтра const tomorrow = schedule.tomorrow(); // На текущую неделю const week = schedule.thisWeek(); console.log(`Пар на неделе: ${week.length}`); // На конкретную дату const date = new Date("2025-03-10"); const forDate = schedule.forDate(date); // Текущая пара (null если сейчас перерыв) const current = schedule.currentLesson(); if (current) { console.log(`Сейчас идёт: ${current.subject}`); } ``` -------------------------------- ### Get schedule for a specific weekday Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves lessons for a specified day of the week (Sunday=0, Monday=1, ..., Saturday=6). Supports specifying a particular week number within the semester. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); // Расписание на понедельник текущей недели const monday = schedule.forDay(1); // Расписание на пятницу 5-й недели const friday5 = schedule.forDay(5, { week: 5 }); ``` -------------------------------- ### Get Audience Schedule Source: https://context7.com/artegoser/chuvsu-js/llms.txt Loads the schedule of lessons for a specific audience across all periods. The schedule object provides methods to access daily lessons. Requires audience ID. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const audience = await tt.findAudienceByName({ name: "301" }); if (!audience) throw new Error("Аудитория не найдена"); const schedule = await tt.getAudienceSchedule(audience.id); const today = schedule.today(); for (const lesson of today) { console.log(`${lesson.subject} — ${lesson.groups.join(", ")}, ${lesson.teacher.name}`); } ``` -------------------------------- ### Get Teacher Photo Source: https://context7.com/artegoser/chuvsu-js/llms.txt Downloads a teacher's photo. `getTeacherPhoto` fetches via the schedule page (also caches TeacherInfo), while `getTeacherPhotoLazy` uses a direct URL for faster retrieval if TeacherInfo is not needed. Requires teacher ID. ```typescript import { writeFileSync } from "node:fs"; import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 24 * 60 * 60_000 }); await tt.loginAsGuest(); // Через страницу расписания (также кеширует TeacherInfo) const photo = await tt.getTeacherPhoto(653); // Прямой URL (быстрее, если TeacherInfo не нужна) const photoLazy = await tt.getTeacherPhotoLazy(653); if (photo) { writeFileSync("teacher_653.jpg", photo); console.log(`Сохранено ${photo.length} байт`); } else { console.log("Фото отсутствует"); } ``` -------------------------------- ### Get a group's schedule for a specific period Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves the academic schedule for a specific period (e.g., Spring Semester) for a given group ID. Allows fetching semester details like total weeks, start date, and current week number. ```typescript import { TtClient, Period } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getScheduleForPeriod({ groupId: 8919, period: Period.SpringSemester, // 1=FallSemester, 2=WinterSession, 3=SpringSemester, 4=SummerSession }); const weeks = schedule.getSemesterWeeks(); console.log(`Семестр: ${weeks.length} недель`); console.log(`Начало: ${schedule.getSemesterStart().toLocaleDateString("ru-RU")}`); console.log(`Текущая неделя: ${schedule.getWeekNumber()}`); ``` -------------------------------- ### Initialize and Use LkClient Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Initializes the LkClient for the personal cabinet and performs login. Supports caching with configurable TTL or cache adapters. ```typescript const lk = new LkClient({ cache?: number | LkCacheConfig }); await lk.login({ email, password }); const data = await lk.getPersonalData(); const groupId = await lk.getGroupId(); ``` -------------------------------- ### LkClient - Constructor and Login Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Initializes the LkClient and handles user authentication for the student portal. ```APIDOC ## LkClient - Constructor and Login ### Description Initializes the LkClient and handles user authentication for the student portal. ### Constructor ```ts new LkClient({ cache: 60_000 }) ``` - **cache** (`number`): Cache time-to-live in milliseconds. ### Login Method ```ts await lk.login({ email: "student@mail.ru", password: "password" }); ``` - **email** (`string`): Student's email address. - **password** (`string`): Student's password. ``` -------------------------------- ### TtClient Get Current Period Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Retrieves the current academic period. ```typescript // Текущий учебный период const period = tt.getCurrentPeriod(); ``` -------------------------------- ### LkClient - Get Personal Data Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Retrieves the authenticated student's personal data. ```APIDOC ## LkClient - Get Personal Data ### Description Retrieves the authenticated student's personal data. ### Method ```ts const data = await lk.getPersonalData(); ``` ### Response Example ```json { "lastName": "...", "firstName": "...", "group": "..." } ``` ``` -------------------------------- ### Create LkClient Instance Source: https://context7.com/artegoser/chuvsu-js/llms.txt Initializes a client for interacting with the `lk.chuvsu.ru` personal cabinet. Supports various caching configurations, from no cache to fine-grained TTLs. ```typescript import { LkClient } from "chuvsu-js"; // Без кеша const lk = new LkClient(); // С единым TTL const lkCached = new LkClient({ cache: 60_000 }); // С раздельными TTL const lkFine = new LkClient({ cache: { personalData: 5 * 60_000, photo: 24 * 60 * 60_000, groupId: Infinity, }, }); ``` -------------------------------- ### LkClient - Get Group ID Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Retrieves the student's group ID, which can be used with the TtClient. ```APIDOC ## LkClient - Get Group ID ### Description Retrieves the student's group ID, which can be used with the TtClient. ### Method ```ts const groupId = await lk.getGroupId(); ``` ### Response Example ```json "8919" ``` ``` -------------------------------- ### Create TtClient Instance Source: https://context7.com/artegoser/chuvsu-js/llms.txt Instantiate the TtClient for schedule system access. Options include cache configuration (global TTL or per-category TTL) and external adapters for caching and blob storage. ```typescript import { TtClient, EducationType } from "chuvsu-js"; // Без кеша const tt = new TtClient(); // С единым TTL кеша (мс) для всех категорий const ttCached = new TtClient({ cache: 5 * 60_000 }); // 5 минут // С раздельными TTL по категориям const ttFine = new TtClient({ educationType: EducationType.HigherEducation, // по умолчанию cache: { schedule: 10 * 60_000, // расписание — 10 мин faculties: Infinity, // факультеты — бессрочно groups: Infinity, teachers: 60 * 60_000, teacherInfo: 24 * 60 * 60_000, teacherPhotos: 24 * 60 * 60_000, audiences: Infinity, audienceInfo: 24 * 60 * 60_000, audienceImages: 24 * 60 * 60_000, audienceNames: Infinity, webinars: 5 * 60_000, }, }); // С внешним L2-кешем (например Redis) const ttRedis = new TtClient({ cache: 10 * 60_000, cacheAdapter: { async get(category, key) { return redisClient.get(`${category}:${key}`); }, async set(category, key, data, ttl) { await redisClient.set(`${category}:${key}`, JSON.stringify(data), { PX: ttl }); }, async clear(category) { /* ... */ }, }, }); // С blob-хранилищем для фото (S3/R2/MinIO) const ttBlob = new TtClient({ cache: 60_000, blobAdapter: { async get(key) { return s3.getObject(key); }, async put(key, data, opts) { await s3.putObject(key, data); }, }, }); ``` -------------------------------- ### schedule.forDate(date, opts?) Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves lessons for a specific date, considering holidays, transfers, and week parity. ```APIDOC ## schedule.forDate(date, opts?) ### Description Returns lessons (`Lesson[]`) for a specified date, taking into account holidays, rescheduled classes, and whether the week is odd or even. ### Method `schedule.forDate(date: Date, opts?: { subgroup?: number })` ### Parameters #### Path Parameters - **date** (Date) - Required - The specific date for which to retrieve lessons. #### Query Parameters - **subgroup** (number) - Optional - Filters lessons for a specific subgroup (e.g., 1 or 2). ### Request Example ```ts import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); const monday = new Date("2025-02-10"); const lessons = schedule.forDate(monday, { subgroup: 2 }); for (const lesson of lessons) { const start = `${lesson.start.hours}:${String(lesson.start.minutes).padStart(2,"0")}`; const end = `${lesson.end.hours}:${String(lesson.end.minutes).padStart(2,"0")}`; console.log(`${start}–${end} ${lesson.subject} [${lesson.type}]`); if (lesson.isDistance) console.log(" (дистанционно)"); if (lesson.weekParity) console.log(` Чётность: ${lesson.weekParity}`); if (lesson.originalRoom) console.log(` Замена аудитории: ${lesson.originalRoom} → ${lesson.room}`); } ``` ### Response #### Success Response (Lesson[]) - An array of `Lesson` objects for the specified date. - Each `Lesson` object contains details like start time, end time, subject, type, room, teacher, and parity information. #### Response Example ```json [ { "id": 12345, "number": 1, "start": {"hours": 8, "minutes": 0}, "end": {"hours": 9, "minutes": 35}, "subject": "Математический анализ", "type": "лекция", "room": "305", "teacher": {"id": 653, "name": "Иванов Иван Иванович"}, "isDistance": false, "weekParity": "odd", "originalRoom": null } ] ``` ``` -------------------------------- ### TtClient - Get Schedule Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Retrieves the schedule for a specified group, returning a Schedule object for local access. ```APIDOC ## TtClient - Get Schedule ### Description Retrieves the schedule for a specified group, returning a Schedule object for local access. ### Signature ```ts const schedule = await tt.getSchedule({ groupId, period? }); ``` ### Parameters - **groupId** (string) - Required - The ID of the group for which to retrieve the schedule. - **period** (string) - Optional - The academic period for which to fetch the schedule. ``` -------------------------------- ### TtClient - Search and Get Data Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Provides methods to search for faculties, groups, and teachers, and retrieve related data. ```APIDOC ## TtClient - Search and Get Data ### Description Provides methods to search for faculties, groups, and teachers, and retrieve related data. ### Methods - **getFaculties** - **Description**: Retrieves a list of all faculties. - **Signature**: `const faculties = await tt.getFaculties();` - **getGroupsForFaculty** - **Description**: Retrieves groups belonging to a specific faculty. - **Signature**: `const groups = await tt.getGroupsForFaculty({ facultyId });` - **Parameters**: `facultyId` (string) - The ID of the faculty. - **searchGroup** - **Description**: Searches for groups by name. - **Signature**: `const groups = await tt.searchGroup({ name: "ZI" });` - **Parameters**: `name` (string) - The name of the group to search for. - **searchTeacher** - **Description**: Searches for teachers by name. - **Signature**: `const teachers = await tt.searchTeacher({ name: "Ivanov" });` - **Parameters**: `name` (string) - The name of the teacher to search for. ``` -------------------------------- ### TtClient - Constructor Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Initializes a new TtClient instance for interacting with the schedule portal. Options can configure education type, caching, and blob storage. ```APIDOC ## TtClient Constructor ### Description Initializes a new TtClient instance for interacting with the schedule portal. Options can configure education type, caching, and blob storage. ### Signature ```ts new TtClient(options?: TtClientOptions) ``` ### Options - **educationType** (`EducationType`) - Optional - Specifies the type of education (HigherEducation or SPO). - **cache** (`number | CacheConfig`) - Optional - Configures the cache TTL in milliseconds. Can be a single value or an object for category-specific TTLs. - **cacheAdapter** (`CacheAdapter`) - Optional - An external L2 cache adapter for JSON data. - **blobAdapter** (`BlobAdapter`) - Optional - An adapter for storing binary data like images externally. ``` -------------------------------- ### TtClient Get Schedule Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Fetches the schedule for a given group and period, returning a Schedule object for local access. ```typescript const schedule = await tt.getSchedule({ groupId, period? }); ``` -------------------------------- ### schedule.forWeek(week?, opts?) Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves all lessons for a specified or the current semester week. ```APIDOC ## schedule.forWeek(week?, opts?) ### Description Returns all lessons for a specified week of the semester, or the current week if no week number is provided. This method is useful for viewing a week's timetable at a glance. ### Method `schedule.forWeek(week?: number, opts?: { subgroup?: number })` ### Parameters #### Path Parameters - **week** (number) - Optional - The week number of the semester (e.g., 3 for the third week). If omitted, the current week is used. #### Query Parameters - **subgroup** (number) - Optional - Filters lessons for a specific subgroup (e.g., 1 or 2). ### Request Example ```ts import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); // Get lessons for the current week const thisWeek = schedule.thisWeek(); console.log(`Lessons this week: ${thisWeek.length}`); // Get lessons for the 3rd week of the semester const week3 = schedule.forWeek(3); console.log(`Lessons on week 3: ${week3.length}`); // Get lessons for the 3rd week with subgroup filter const week3sub1 = schedule.forWeek(3, { subgroup: 1 }); ``` ### Response #### Success Response (Lesson[]) - An array of `Lesson` objects for the specified week. #### Response Example ```json // Example of a Lesson object (see schedule.forDate for full details) [ { ... lesson object ... }, { ... lesson object ... } ] ``` ``` -------------------------------- ### schedule.forDay(weekday, opts?) Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieves lessons for a specific day of the week within the current or a specified semester week. ```APIDOC ## schedule.forDay(weekday, opts?) ### Description Returns lessons for a specified day of the week (0=Sunday, 1=Monday, ..., 6=Saturday). This can be for the current week or a specific week of the semester. ### Method `schedule.forDay(weekday: number, opts?: { week?: number, subgroup?: number })` ### Parameters #### Path Parameters - **weekday** (number) - Required - The day of the week (0 for Sunday, 1 for Monday, ..., 6 for Saturday). #### Query Parameters - **week** (number) - Optional - The week number of the semester. If omitted, the current week is used. - **subgroup** (number) - Optional - Filters lessons for a specific subgroup (e.g., 1 or 2). ### Request Example ```ts import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(8919); // Get schedule for Monday of the current week const monday = schedule.forDay(1); // Get schedule for Friday of the 5th week const friday5 = schedule.forDay(5, { week: 5 }); ``` ### Response #### Success Response (Lesson[]) - An array of `Lesson` objects for the specified day of the week. #### Response Example ```json // Example of a Lesson object (see schedule.forDate for full details) [ { ... lesson object ... }, { ... lesson object ... } ] ``` ``` -------------------------------- ### Get Groups for Faculty with TtClient Source: https://context7.com/artegoser/chuvsu-js/llms.txt Retrieve a list of student groups belonging to a specific faculty. Requires prior login. ```typescript import { TtClient } from "chuvsu-js"; const tt = new TtClient({ cache: Infinity }); await tt.loginAsGuest(); const groups = await tt.getGroupsForFaculty({ facultyId: 1 }); // [ // { id: 8919, name: "КТ-41-24", specialty: "Прикладная информатика", profile: "..." }, // { id: 8920, name: "КТ-42-24", specialty: "...", profile: "..." }, // ] for (const g of groups) { console.log(`[${g.id}] ${g.name} — ${g.specialty}`); } ``` -------------------------------- ### Handle Authentication Errors Source: https://github.com/artegoser/chuvsu-js/blob/main/README.md Demonstrates how to catch and handle authentication errors using a try-catch block and checking the error instance. ```typescript import { AuthError, ParseError } from "chuvsu-js"; try { await tt.login({ email: "...", password: "wrong" }); } catch (e) { if (e instanceof AuthError) { console.error("Неверные данные для входа"); } } ``` -------------------------------- ### Attach Webinars to Lessons Source: https://context7.com/artegoser/chuvsu-js/llms.txt Associates webinars with schedule lessons by populating the `lesson.webinar` field. Requires a `TtClient` instance, login, and fetching schedule and webinar data. ```typescript import { TtClient, attachWebinarsToLessons } from "chuvsu-js"; const tt = new TtClient({ cache: 5 * 60_000 }); await tt.loginAsGuest(); const groups = await tt.searchGroup({ name: "КТ-41-24" }); const schedule = await tt.getSchedule(groups[0].id); const webinars = await tt.getWebinars(); const lessons = schedule.today(); const lessonsWithWebinars = attachWebinarsToLessons(lessons, webinars); for (const lesson of lessonsWithWebinars) { if (lesson.webinar) { console.log(`${lesson.subject} — есть вебинар: ${lesson.webinar.title}`); } } ``` -------------------------------- ### Download Student Photo Source: https://context7.com/artegoser/chuvsu-js/llms.txt Fetches the student's photo from the personal cabinet as a `Buffer`. Requires login and Node.js `fs` module for saving the file. ```typescript import { writeFileSync } from "node:fs"; import { LkClient } from "chuvsu-js"; const lk = new LkClient({ cache: 24 * 60 * 60_000 }); await lk.login({ email: "student@mail.ru", password: "secret" }); const photo = await lk.getPhoto(); writeFileSync("student_photo.jpg", photo); console.log(`Фото сохранено (${photo.length} байт)`); ``` -------------------------------- ### LkClient Source: https://context7.com/artegoser/chuvsu-js/llms.txt Client for interacting with the personal cabinet (lk.chuvsu.ru), supporting login, data retrieval, and photo download. ```APIDOC ## `LkClient` Client for interacting with `lk.chuvsu.ru`. ### `new LkClient(opts?: LkClientOptions)` Creates a new instance of the LkClient. Options can configure caching behavior. #### Options (`LkClientOptions`) - `cache` (number | CacheConfig): Cache TTL in milliseconds or a configuration object for specific cache types. - `personalData` (number): TTL for personal data cache. - `photo` (number): TTL for photo cache. - `groupId` (number): TTL for group ID cache. ### Example Usage: ```ts import { LkClient } from "chuvsu-js"; // Without cache const lk = new LkClient(); // With a uniform TTL const lkCached = new LkClient({ cache: 60_000 }); // With separate TTLs const lkFine = new LkClient({ cache: { personalData: 5 * 60_000, photo: 24 * 60 * 60_000, groupId: Infinity, }, }); ``` ``` ```APIDOC ### `lk.login(opts: LoginOptions): Promise` Authenticates the user using email and password. #### Parameters - `opts` (LoginOptions): - `email` (string): The student's email address. - `password` (string): The student's password. #### Throws - `AuthError`: If authentication fails. ### Example Usage: ```ts import { LkClient, AuthError } from "chuvsu-js"; const lk = new LkClient({ cache: 60_000 }); try { await lk.login({ email: "student@mail.ru", password: "secret" }); console.log("Logged in to LK successfully"); } catch (e) { if (e instanceof AuthError) { console.error("Invalid credentials:", e.message); // AuthError: LK login failed } } ``` ``` ```APIDOC ### `lk.getPersonalData(): Promise` Retrieves the student's personal data, including name, date of birth, faculty, group, and contact information. #### Returns - `PersonalData`: An object containing the student's personal details. - `lastName` (string) - `firstName` (string) - `patronymic` (string) - `sex` (string) - `birthday` (string) - `recordBookNumber` (string) - `faculty` (string) - `specialty` (string) - `profile` (string) - `group` (string) - `course` (string) - `email` (string) - `phone` (string) ### Example Usage: ```ts import { LkClient } from "chuvsu-js"; const lk = new LkClient({ cache: 5 * 60_000 }); await lk.login({ email: "student@mail.ru", password: "secret" }); const data = await lk.getPersonalData(); console.log(`${data.lastName} ${data.firstName}, group ${data.group}, course ${data.course}`); ``` ``` ```APIDOC ### `lk.getPhoto(): Promise` Downloads the student's photo from the personal cabinet. #### Returns - `Buffer`: The student's photo as a Buffer. ### Example Usage: ```ts import { writeFileSync } from "node:fs"; import { LkClient } from "chuvsu-js"; const lk = new LkClient({ cache: 24 * 60 * 60_000 }); await lk.login({ email: "student@mail.ru", password: "secret" }); const photo = await lk.getPhoto(); writeFileSync("student_photo.jpg", photo); console.log(`Photo saved (${photo.length} bytes)`); ``` ``` ```APIDOC ### `lk.getGroupId(): Promise` Retrieves the student's group ID, compatible with `TtClient.getSchedule()`. #### Returns - `number | null`: The student's group ID, or null if not found. ### Example Usage: ```ts import { LkClient, TtClient } from "chuvsu-js"; const lk = new LkClient({ cache: Infinity }); await lk.login({ email: "student@mail.ru", password: "secret" }); const groupId = await lk.getGroupId(); // 8919 | null if (groupId) { const tt = new TtClient({ cache: 10 * 60_000 }); await tt.loginAsGuest(); const schedule = await tt.getSchedule(groupId); const today = schedule.today(); console.log(`Today's classes: ${today.length}`); } ``` ```