1
0
Fork 0
mirror of https://github.com/classchartsapi/classcharts-api-js.git synced 2026-05-14 11:58:13 +00:00
classcharts-api-js/src/core/baseClient.ts

327 lines
9.3 KiB
TypeScript
Raw Normal View History

import ky, { type Options as KyOptions } from "ky-universal";
2022-03-24 18:56:33 +00:00
import type {
2022-01-31 22:32:29 +00:00
ActivityResponse,
2022-02-06 15:45:28 +00:00
AnnouncementsResponse,
2022-05-25 18:18:31 +01:00
AttendanceResponse,
2022-01-31 23:13:05 +00:00
BadgesResponse,
2022-01-31 22:32:29 +00:00
BehaviourResponse,
ClassChartsResponse,
DetentionsResponse,
2022-01-31 22:32:29 +00:00
GetActivityOptions,
GetAttendanceOptions,
2022-01-31 22:32:29 +00:00
GetBehaviourOptions,
GetFullActivityOptions,
2022-01-31 22:32:29 +00:00
GetHomeworkOptions,
GetLessonsOptions,
2023-04-07 13:47:08 +01:00
GetStudentInfoResponse,
2022-01-31 22:32:29 +00:00
HomeworksResponse,
LessonsResponse,
2023-04-16 21:06:10 +01:00
} from "../types.js";
import { PING_INTERVAL } from "../utils/consts.js";
2023-04-07 12:43:46 +01:00
2021-10-29 15:46:33 +01:00
/**
2023-04-16 20:47:40 +01:00
* Shared client for both parent and student. This is not exported and should not be used directly
* @internal
2021-10-29 15:46:33 +01:00
*/
2023-04-16 20:47:40 +01:00
export class BaseClient {
/**
* @property studentId Currently selected student ID
*/
2023-04-07 12:43:46 +01:00
public studentId = 0;
2023-04-16 20:47:40 +01:00
/**
* @internal
* @property authCookies Cookies used for authentication (set during login and can be empty)
*/
2023-04-07 13:47:08 +01:00
public authCookies: Array<string>;
2023-04-16 20:47:40 +01:00
/**
* @property sessionId Session ID used for authentication
*/
2022-07-21 15:46:08 +01:00
public sessionId = "";
2023-04-16 20:47:40 +01:00
/**
* @property lastPing Last time the sessionId was updated
*/
2023-04-07 12:43:46 +01:00
public lastPing = 0;
2023-04-16 20:47:40 +01:00
/**
* @property API_BASE Base API URL, this is different depending if its called as a parent or student
* @internal
*/
2022-03-12 11:30:03 +00:00
protected API_BASE = "";
2022-01-31 22:32:29 +00:00
/**
*
2022-03-12 11:30:03 +00:00
* @param API_BASE Base API URL, this is different depending if its called as a parent or student
2022-01-31 22:32:29 +00:00
*/
constructor(API_BASE: string) {
2023-04-07 13:47:08 +01:00
this.authCookies = [];
2022-03-12 11:37:28 +00:00
this.API_BASE = API_BASE;
2022-01-31 22:32:29 +00:00
}
2023-04-16 20:47:40 +01:00
/**
* Revalidates the session ID.
*
* This is called automatically when the session ID is older than 3 minutes or when intially using the .login() method
* @internal
*/
2023-04-07 12:43:46 +01:00
public async getNewSessionId() {
const pingFormData = new URLSearchParams();
pingFormData.append("include_data", "true");
const pingData = await this.makeAuthedRequest(
this.API_BASE + "/ping",
{
method: "POST",
body: pingFormData,
2023-04-07 12:43:46 +01:00
},
2023-04-07 13:47:08 +01:00
{ revalidateToken: false }
2023-04-07 12:43:46 +01:00
);
this.sessionId = pingData.meta.session_id;
this.lastPing = Date.now();
}
2023-04-16 20:47:40 +01:00
/**
* Makes a request to the Classcharts API with the required authentication headers
*
* @param path Path to the API endpoint
* @param kyOptions Ky (fetch library) request options
* @param options
* @param options.revalidateToken Whether to revalidate the session ID if it is older than 3 minutes
*
* @returns Response
* @internal
*/
2022-01-31 22:32:29 +00:00
public async makeAuthedRequest(
path: string,
kyOptions: KyOptions,
2023-04-07 13:47:08 +01:00
options?: { revalidateToken?: boolean }
2022-01-31 22:32:29 +00:00
) {
2023-04-07 12:43:46 +01:00
if (!this.sessionId) throw new Error("No session ID");
if (!options) {
options = {};
}
if (typeof options?.revalidateToken == "undefined") {
options.revalidateToken = true;
}
const requestOptions = {
...kyOptions,
2022-01-31 22:32:29 +00:00
headers: {
2023-04-07 12:43:46 +01:00
Cookie: this?.authCookies?.join(";") ?? [],
Authorization: "Basic " + this.sessionId,
...kyOptions.headers,
2022-01-31 22:32:29 +00:00
},
credentials: undefined,
} satisfies KyOptions;
2023-04-07 12:43:46 +01:00
if (options?.revalidateToken === true && this.lastPing) {
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
await this.getNewSessionId();
}
}
const request = await ky(path, requestOptions);
2023-05-09 19:24:03 +01:00
let responseJSON: ClassChartsResponse<unknown, unknown>;
try {
responseJSON = await request.json();
} catch (err) {
throw new Error(
"Error parsing JSON. Returned response: " + (await request.text())
);
}
2022-01-31 22:32:29 +00:00
if (responseJSON.success == 0) {
throw new Error(responseJSON.error);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return responseJSON as any;
2022-01-31 22:32:29 +00:00
}
/**
2023-04-16 20:47:40 +01:00
* Gets general information about the current student
2022-01-31 22:32:29 +00:00
* @returns Student object
*/
2023-04-07 13:47:08 +01:00
async getStudentInfo(): Promise<GetStudentInfoResponse> {
const body = new URLSearchParams();
body.append("include_data", "true");
2022-03-12 11:30:03 +00:00
const data = await this.makeAuthedRequest(this.API_BASE + "/ping", {
2022-01-31 22:32:29 +00:00
method: "POST",
body: body,
2022-01-31 22:32:29 +00:00
});
2023-04-07 13:47:08 +01:00
return data;
2022-01-31 22:32:29 +00:00
}
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's activity
*
* This function is only used for pagination, you likely want client.getFullActivity
2022-01-31 22:32:29 +00:00
* @param options GetActivityOptions
* @returns Activity data
2023-04-16 20:47:40 +01:00
* @see getFullActivity
2022-01-31 22:32:29 +00:00
*/
async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
2022-01-31 22:32:29 +00:00
options?.to && params.append("to", options?.to);
2022-02-06 11:13:23 +00:00
options?.last_id && params.append("last_id", options?.last_id);
2022-01-31 22:32:29 +00:00
return this.makeAuthedRequest(
2022-03-12 11:30:03 +00:00
this.API_BASE + "/activity/" + this.studentId + "?" + params.toString(),
2022-01-31 22:32:29 +00:00
{
method: "GET",
}
);
}
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's activity between two dates
*
* This function will automatically paginate through all the data returned by getActivity
* @param options GetFullActivityOptions
* @returns Activity Data
2023-04-16 20:47:40 +01:00
* @see getActivity
*/
async getFullActivity(
options: GetFullActivityOptions
2023-04-07 13:47:08 +01:00
): Promise<ActivityResponse["data"]> {
let data: ActivityResponse["data"] = [];
let prevLast: number | undefined;
let gotData = true;
while (gotData) {
const params: GetActivityOptions = {
from: options.from,
to: options.to,
};
if (prevLast) {
params.last_id = String(prevLast);
}
2023-04-07 13:47:08 +01:00
const fragment = (await this.getActivity(params)).data;
if (!fragment || !fragment.length) {
gotData = false;
} else {
data = data.concat(fragment);
prevLast = fragment[fragment.length - 1].id;
}
}
return data;
}
2022-01-31 22:32:29 +00:00
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's behaviour
2022-01-31 22:32:29 +00:00
* @param options GetBehaviourOptions
* @returns Array of behaviour points
*/
async getBehaviour(
options?: GetBehaviourOptions
): Promise<BehaviourResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
2022-01-31 22:32:29 +00:00
options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest(
2022-03-12 11:30:03 +00:00
this.API_BASE + "/behaviour/" + this.studentId + "?" + params.toString(),
2022-01-31 22:32:29 +00:00
{
method: "GET",
}
);
}
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's homework
2022-01-31 22:32:29 +00:00
* @param options GetHomeworkOptions
* @returns Array of homeworks
*/
2023-04-07 13:47:08 +01:00
async getHomeworks(options?: GetHomeworkOptions): Promise<HomeworksResponse> {
2022-01-31 22:32:29 +00:00
const params = new URLSearchParams();
if (options?.displayDate)
params.append("display_date", String(options?.displayDate));
options?.from && params.append("from", String(options?.from));
options?.to && params.append("to", String(options?.to));
2023-04-07 13:47:08 +01:00
const data: HomeworksResponse = await this.makeAuthedRequest(
2022-03-12 11:30:03 +00:00
this.API_BASE + "/homeworks/" + this.studentId + "?" + params.toString(),
2022-01-31 22:32:29 +00:00
{
method: "GET",
}
);
2023-04-07 13:47:08 +01:00
for (let i = 0; i < data.data.length; i++) {
data.data[i].description_raw = data.data[i].description;
2022-01-31 22:32:29 +00:00
// homework.lesson.replace(/\\/g, '')
2023-04-07 13:47:08 +01:00
data.data[i].description = data.data[i].description.replace(
/(<([^>]+)>)/gi,
""
);
data.data[i].description = data.data[i].description.replace(
/&nbsp;/g,
""
);
data.data[i].description = data.data[i].description.trim();
2022-01-31 22:32:29 +00:00
}
return data;
}
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's lessons for a given date
2022-01-31 22:32:29 +00:00
* @param options GetLessonsOptions
* @returns Array of lessons
*/
async getLessons(options: GetLessonsOptions): Promise<LessonsResponse> {
2022-01-31 22:32:29 +00:00
if (!options?.date) throw new Error("No date specified");
const params = new URLSearchParams();
params.append("date", String(options?.date));
return await this.makeAuthedRequest(
2022-03-12 11:30:03 +00:00
this.API_BASE + "/timetable/" + this.studentId + "?" + params.toString(),
2022-01-31 22:32:29 +00:00
{
method: "GET",
}
);
}
2022-01-31 23:13:05 +00:00
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's earned badges
2022-01-31 23:13:05 +00:00
* @returns Array of badges
*/
async getBadges(): Promise<BadgesResponse> {
return await this.makeAuthedRequest(
2022-03-12 11:30:03 +00:00
this.API_BASE + "/eventbadges/" + this.studentId,
2022-01-31 23:13:05 +00:00
{
method: "GET",
}
);
}
2022-02-06 15:14:48 +00:00
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's announcements
2022-02-06 15:45:28 +00:00
* @returns Array of announcements
2022-02-06 15:14:48 +00:00
*/
2023-04-07 13:47:08 +01:00
async getAnnouncements(): Promise<AnnouncementsResponse> {
return (
await this.makeAuthedRequest(
this.API_BASE + "/announcements/" + this.studentId,
{
method: "GET",
}
)
).data;
2022-02-06 15:14:48 +00:00
}
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's detentions
* @returns Array of detentions
*/
async getDetentions(): Promise<DetentionsResponse> {
2023-04-07 13:47:08 +01:00
return (
await this.makeAuthedRequest(
this.API_BASE + "/detentions/" + this.studentId,
{
method: "GET",
}
)
).data;
}
2022-05-25 18:18:31 +01:00
/**
2023-04-16 20:47:40 +01:00
* Gets the current student's attendance
* @param options GetAttendanceOptions
2022-05-25 18:18:31 +01:00
* @returns Array of dates of attendance
*/
2023-04-07 13:47:08 +01:00
async getAttendance(
options?: GetAttendanceOptions
): Promise<AttendanceResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to);
2023-04-07 13:47:08 +01:00
return (
await this.makeAuthedRequest(
this.API_BASE +
"/attendance/" +
this.studentId +
"?" +
params.toString(),
{
method: "GET",
}
)
).data;
2022-05-25 18:18:31 +01:00
}
2021-10-28 16:51:07 +01:00
}