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

feat: Use biomejs for formatting & linting (#42)

This commit is contained in:
James Cook 2023-11-29 00:03:56 +00:00 committed by GitHub
parent 602529171f
commit ac5569f53e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 1095 additions and 1000 deletions

View file

@ -1,21 +1,21 @@
import type {
ActivityResponse,
AnnouncementsResponse,
AttendanceResponse,
BadgesResponse,
BehaviourResponse,
ClassChartsResponse,
DetentionsResponse,
GetActivityOptions,
GetAttendanceOptions,
GetBehaviourOptions,
GetFullActivityOptions,
GetHomeworkOptions,
GetLessonsOptions,
GetStudentInfoResponse,
HomeworksResponse,
LessonsResponse,
PupilFieldsResponse,
ActivityResponse,
AnnouncementsResponse,
AttendanceResponse,
BadgesResponse,
BehaviourResponse,
ClassChartsResponse,
DetentionsResponse,
GetActivityOptions,
GetAttendanceOptions,
GetBehaviourOptions,
GetFullActivityOptions,
GetHomeworkOptions,
GetLessonsOptions,
GetStudentInfoResponse,
HomeworksResponse,
LessonsResponse,
PupilFieldsResponse,
} from "../types.ts";
import { PING_INTERVAL } from "../utils/consts.ts";
@ -23,290 +23,283 @@ import { PING_INTERVAL } from "../utils/consts.ts";
* Shared client for both parent and student. This is not exported and should not be used directly
*/
export class BaseClient {
/**
* @property studentId Currently selected student ID
*/
public studentId = 0;
/**
* @property authCookies Cookies used for authentication (set during login and can be empty)
*/
public authCookies: Array<string>;
/**
* @property sessionId Session ID used for authentication
*/
public sessionId = "";
/**
* @property lastPing Last time the sessionId was updated
*/
public lastPing = 0;
/**
* @property API_BASE Base API URL, this is different depending on if its called as a parent or student
*/
protected API_BASE = "";
/**
* @param API_BASE Base API URL, this is different depending on if its called as a parent or student
*/
constructor(API_BASE: string) {
this.authCookies = [];
this.API_BASE = API_BASE;
}
/**
* Revalidates the session ID.
*
* This is called automatically when the session ID is older than 3 minutes or when initially using the .login() method
*/
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,
},
{ revalidateToken: false },
);
this.sessionId = pingData.meta.session_id;
this.lastPing = Date.now();
}
/**
* Makes a request to the ClassCharts API with the required authentication headers
*
* @param path Path to the API endpoint
* @param fetchOptions Request Options
* @param options
* @param options.revalidateToken Whether to revalidate the session ID if it is older than 3 minutes
*
* @returns Response
*/
public async makeAuthedRequest(
path: string,
fetchOptions: RequestInit,
options?: { revalidateToken?: boolean },
) {
if (!this.sessionId) throw new Error("No session ID");
if (!options) {
options = {};
}
if (typeof options?.revalidateToken == "undefined") {
options.revalidateToken = true;
}
const requestOptions = {
...fetchOptions,
headers: {
Cookie: this?.authCookies?.join(";") ?? [],
Authorization: "Basic " + this.sessionId,
"User-Agent":
"classcharts-api https://github.com/classchartsapi/classcharts-api-js",
...fetchOptions.headers,
},
} satisfies RequestInit;
if (options?.revalidateToken === true && this.lastPing) {
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
await this.getNewSessionId();
}
}
const request = await fetch(path, requestOptions);
// deno-lint-ignore no-explicit-any
let responseJSON: ClassChartsResponse<any, any>;
try {
responseJSON = await request.json();
} catch {
throw new Error(
"Error parsing JSON. Returned response: " + (await request.text()),
);
}
if (responseJSON.success == 0) {
throw new Error(responseJSON.error);
}
return responseJSON;
}
/**
* Gets general information about the current student
* @returns Student object
*/
async getStudentInfo(): Promise<GetStudentInfoResponse> {
const body = new URLSearchParams();
body.append("include_data", "true");
return await this.makeAuthedRequest(this.API_BASE + "/ping", {
method: "POST",
body: body,
});
}
/**
* Gets the current student's activity
*
* This function is only used for pagination, you likely want client.getFullActivity
* @param options GetActivityOptions
* @returns Activity data
* @see getFullActivity
*/
async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to);
options?.last_id && params.append("last_id", options?.last_id);
return await this.makeAuthedRequest(
this.API_BASE + "/activity/" + this.studentId + "?" + params.toString(),
{
method: "GET",
},
);
}
/**
* 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
* @see getActivity
*/
async getFullActivity(
options: GetFullActivityOptions,
): 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);
}
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;
}
/**
* Gets the current student's behaviour
* @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);
options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest(
this.API_BASE + "/behaviour/" + this.studentId + "?" + params.toString(),
{
method: "GET",
},
);
}
/**
* Gets the current student's homework
* @param options GetHomeworkOptions
* @returns Array of homeworks
*/
async getHomeworks(options?: GetHomeworkOptions): Promise<HomeworksResponse> {
const params = new URLSearchParams();
if (options?.displayDate) {
params.append("display_date", String(options?.displayDate));
}
/**
* @property studentId Currently selected student ID
*/
public studentId = 0;
/**
* @property authCookies Cookies used for authentication (set during login and can be empty)
*/
public authCookies: Array<string>;
/**
* @property sessionId Session ID used for authentication
*/
public sessionId = "";
/**
* @property lastPing Last time the sessionId was updated
*/
public lastPing = 0;
/**
* @property API_BASE Base API URL, this is different depending on if its called as a parent or student
*/
protected API_BASE = "";
/**
* @param API_BASE Base API URL, this is different depending on if its called as a parent or student
*/
constructor(API_BASE: string) {
this.authCookies = [];
this.API_BASE = API_BASE;
}
/**
* Revalidates the session ID.
*
* This is called automatically when the session ID is older than 3 minutes or when initially using the .login() method
*/
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,
},
{ revalidateToken: false },
);
this.sessionId = pingData.meta.session_id;
this.lastPing = Date.now();
}
/**
* Makes a request to the ClassCharts API with the required authentication headers
*
* @param path Path to the API endpoint
* @param fetchOptions Request Options
* @param options
* @param options.revalidateToken Whether to revalidate the session ID if it is older than 3 minutes
*
* @returns Response
*/
public async makeAuthedRequest(
path: string,
fetchOptions: RequestInit,
options: { revalidateToken?: boolean } = { revalidateToken: true },
) {
if (!this.sessionId) throw new Error("No session ID");
if (typeof options?.revalidateToken === "undefined") {
options.revalidateToken = true;
}
const requestOptions = {
...fetchOptions,
headers: {
Cookie: this?.authCookies?.join(";") ?? [],
Authorization: `Basic ${this.sessionId}`,
"User-Agent":
"classcharts-api https://github.com/classchartsapi/classcharts-api-js",
...fetchOptions.headers,
},
} satisfies RequestInit;
if (options?.revalidateToken === true && this.lastPing) {
if (Date.now() - this.lastPing + 5000 > PING_INTERVAL) {
await this.getNewSessionId();
}
}
const request = await fetch(path, requestOptions);
// biome-ignore lint/suspicious/noExplicitAny:
let responseJSON: ClassChartsResponse<any, any>;
try {
responseJSON = await request.json();
} catch {
throw new Error(
`Error parsing JSON. Returned response: ${await request.text()}`,
);
}
if (responseJSON.success === 0) {
throw new Error(responseJSON.error);
}
return responseJSON;
}
/**
* Gets general information about the current student
* @returns Student object
*/
async getStudentInfo(): Promise<GetStudentInfoResponse> {
const body = new URLSearchParams();
body.append("include_data", "true");
return await this.makeAuthedRequest(`${this.API_BASE}/ping`, {
method: "POST",
body: body,
});
}
/**
* Gets the current student's activity
*
* This function is only used for pagination, you likely want client.getFullActivity
* @param options GetActivityOptions
* @returns Activity data
* @see getFullActivity
*/
async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to);
options?.last_id && params.append("last_id", options?.last_id);
return await this.makeAuthedRequest(
`${this.API_BASE}/activity/${this.studentId}?${params.toString()}`,
{
method: "GET",
},
);
}
/**
* 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
* @see getActivity
*/
async getFullActivity(
options: GetFullActivityOptions,
): 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);
}
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;
}
/**
* Gets the current student's behaviour
* @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);
options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest(
`${this.API_BASE}/behaviour/${this.studentId}?${params.toString()}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's homework
* @param options GetHomeworkOptions
* @returns Array of homeworks
*/
async getHomeworks(options?: GetHomeworkOptions): Promise<HomeworksResponse> {
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));
return await this.makeAuthedRequest(
this.API_BASE + "/homeworks/" + this.studentId + "?" + params.toString(),
{
method: "GET",
},
);
}
/**
* Gets the current student's lessons for a given date
* @param options GetLessonsOptions
* @returns Array of lessons
*/
async getLessons(options: GetLessonsOptions): Promise<LessonsResponse> {
if (!options?.date) throw new Error("No date specified");
const params = new URLSearchParams();
params.append("date", String(options?.date));
return await this.makeAuthedRequest(
this.API_BASE + "/timetable/" + this.studentId + "?" + params.toString(),
{
method: "GET",
},
);
}
/**
* Gets the current student's earned badges
* @returns Array of badges
*/
async getBadges(): Promise<BadgesResponse> {
return await this.makeAuthedRequest(
this.API_BASE + "/eventbadges/" + this.studentId,
{
method: "GET",
},
);
}
/**
* Gets the current student's announcements
* @returns Array of announcements
*/
async getAnnouncements(): Promise<AnnouncementsResponse> {
return await this.makeAuthedRequest(
this.API_BASE + "/announcements/" + this.studentId,
{
method: "GET",
},
);
}
/**
* Gets the current student's detentions
* @returns Array of detentions
*/
async getDetentions(): Promise<DetentionsResponse> {
return await this.makeAuthedRequest(
this.API_BASE + "/detentions/" + this.studentId,
{
method: "GET",
},
);
}
/**
* Gets the current student's attendance
* @param options GetAttendanceOptions
* @returns Array of dates of attendance
*/
async getAttendance(
options?: GetAttendanceOptions,
): Promise<AttendanceResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest(
this.API_BASE +
"/attendance/" +
this.studentId +
"?" +
params.toString(),
{
method: "GET",
},
);
}
/**
* Gets the current student's pupil fields
* @returns Array of stats
*/
async getPupilFields(): Promise<PupilFieldsResponse> {
return await this.makeAuthedRequest(
this.API_BASE + "/customfields/" + this.studentId,
{
method: "GET",
},
);
}
options?.from && params.append("from", String(options?.from));
options?.to && params.append("to", String(options?.to));
return await this.makeAuthedRequest(
`${this.API_BASE}/homeworks/${this.studentId}?${params.toString()}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's lessons for a given date
* @param options GetLessonsOptions
* @returns Array of lessons
*/
async getLessons(options: GetLessonsOptions): Promise<LessonsResponse> {
if (!options?.date) throw new Error("No date specified");
const params = new URLSearchParams();
params.append("date", String(options?.date));
return await this.makeAuthedRequest(
`${this.API_BASE}/timetable/${this.studentId}?${params.toString()}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's earned badges
* @returns Array of badges
*/
async getBadges(): Promise<BadgesResponse> {
return await this.makeAuthedRequest(
`${this.API_BASE}/eventbadges/${this.studentId}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's announcements
* @returns Array of announcements
*/
async getAnnouncements(): Promise<AnnouncementsResponse> {
return await this.makeAuthedRequest(
`${this.API_BASE}/announcements/${this.studentId}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's detentions
* @returns Array of detentions
*/
async getDetentions(): Promise<DetentionsResponse> {
return await this.makeAuthedRequest(
`${this.API_BASE}/detentions/${this.studentId}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's attendance
* @param options GetAttendanceOptions
* @returns Array of dates of attendance
*/
async getAttendance(
options?: GetAttendanceOptions,
): Promise<AttendanceResponse> {
const params = new URLSearchParams();
options?.from && params.append("from", options?.from);
options?.to && params.append("to", options?.to);
return await this.makeAuthedRequest(
`${this.API_BASE}/attendance/${this.studentId}?${params.toString()}`,
{
method: "GET",
},
);
}
/**
* Gets the current student's pupil fields
* @returns Array of stats
*/
async getPupilFields(): Promise<PupilFieldsResponse> {
return await this.makeAuthedRequest(
`${this.API_BASE}/customfields/${this.studentId}`,
{
method: "GET",
},
);
}
}

View file

@ -7,112 +7,107 @@ import { parseCookies } from "../utils/utils.ts";
* Parent Client
*/
export class ParentClient extends BaseClient {
private password = "";
private email = "";
// @ts-expect-error Init in .login
public pupils: GetPupilsResponse;
/**
* @param email Parent's email address
* @param password Parent's password
*/
constructor(email: string, password: string) {
super(API_BASE_PARENT);
this.email = String(email);
this.password = String(password);
}
private password = "";
private email = "";
// @ts-expect-error Init in .login
public pupils: GetPupilsResponse;
/**
* @param email Parent's email address
* @param password Parent's password
*/
constructor(email: string, password: string) {
super(API_BASE_PARENT);
this.email = String(email);
this.password = String(password);
}
/**
* Authenticates with ClassCharts
*/
async login(): Promise<void> {
if (!this.email) throw new Error("Email not provided");
if (!this.password) throw new Error("Password not provided");
const formData = new URLSearchParams();
formData.append("_method", "POST");
formData.append("email", this.email);
formData.append("logintype", "existing");
formData.append("password", this.password);
formData.append("recaptcha-token", "no-token-available");
const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded",
});
const response = await fetch(BASE_URL + "/parent/login", {
method: "POST",
body: formData,
headers: headers,
redirect: "manual",
});
if (response.status != 302 || !response.headers.has("set-cookie")) {
await response.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
}
/**
* Authenticates with ClassCharts
*/
async login(): Promise<void> {
if (!this.email) throw new Error("Email not provided");
if (!this.password) throw new Error("Password not provided");
const formData = new URLSearchParams();
formData.append("_method", "POST");
formData.append("email", this.email);
formData.append("logintype", "existing");
formData.append("password", this.password);
formData.append("recaptcha-token", "no-token-available");
const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded",
});
const response = await fetch(`${BASE_URL}/parent/login`, {
method: "POST",
body: formData,
headers: headers,
redirect: "manual",
});
if (response.status !== 302 || !response.headers.has("set-cookie")) {
await response.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
}
const cookies = String(response.headers.get("set-cookie"));
// this.authCookies = cookies.split(";");
const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse(
String(sessionCookies["parent_session_credentials"]),
);
this.sessionId = sessionID.session_id;
this.pupils = await this.getPupils();
if (!this.pupils) throw new Error("Account has no pupils attached");
this.studentId = this.pupils[0].id;
}
/**
* Get a list of pupils connected to this parent's account
* @returns an array of Pupils connected to this parent's account
*/
async getPupils(): Promise<GetPupilsResponse> {
const response = await this.makeAuthedRequest(this.API_BASE + "/pupils", {
method: "GET",
});
return response.data;
}
/**
* Selects a pupil to be used with API requests
* @param pupilId Pupil ID obtained from this.pupils or getPupils()
*
* @see getPupils
*/
selectPupil(pupilId: number) {
if (!pupilId) throw new Error("No pupil ID specified");
const pupils = this.pupils;
for (let i = 0; i < pupils.length; i++) {
const pupil = pupils[i];
if (pupil.id == pupilId) {
this.studentId = pupil.id;
return;
}
}
throw new Error("No pupil with specified ID returned");
}
/**
* Changes the login password for the current parent account
* @param currentPassword Current password
* @param newPassword New password
* @returns Whether the request was successful
*/
async changePassword(
currentPassword: string,
newPassword: string,
): Promise<ChangePasswordResponse> {
const formData = new URLSearchParams();
formData.append("current", currentPassword);
formData.append("new", newPassword);
formData.append("repeat", newPassword);
return (
await this.makeAuthedRequest(
this.API_BASE + "/password",
{
method: "POST",
body: formData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
)
);
}
const cookies = String(response.headers.get("set-cookie"));
// this.authCookies = cookies.split(";");
const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse(
String(sessionCookies.parent_session_credentials),
);
this.sessionId = sessionID.session_id;
this.pupils = await this.getPupils();
if (!this.pupils) throw new Error("Account has no pupils attached");
this.studentId = this.pupils[0].id;
}
/**
* Get a list of pupils connected to this parent's account
* @returns an array of Pupils connected to this parent's account
*/
async getPupils(): Promise<GetPupilsResponse> {
const response = await this.makeAuthedRequest(`${this.API_BASE}/pupils`, {
method: "GET",
});
return response.data;
}
/**
* Selects a pupil to be used with API requests
* @param pupilId Pupil ID obtained from this.pupils or getPupils()
*
* @see getPupils
*/
selectPupil(pupilId: number) {
if (!pupilId) throw new Error("No pupil ID specified");
const pupils = this.pupils;
for (let i = 0; i < pupils.length; i++) {
const pupil = pupils[i];
if (pupil.id === pupilId) {
this.studentId = pupil.id;
return;
}
}
throw new Error("No pupil with specified ID returned");
}
/**
* Changes the login password for the current parent account
* @param currentPassword Current password
* @param newPassword New password
* @returns Whether the request was successful
*/
async changePassword(
currentPassword: string,
newPassword: string,
): Promise<ChangePasswordResponse> {
const formData = new URLSearchParams();
formData.append("current", currentPassword);
formData.append("new", newPassword);
formData.append("repeat", newPassword);
return await this.makeAuthedRequest(`${this.API_BASE}/password`, {
method: "POST",
body: formData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
}
}

View file

@ -2,34 +2,34 @@ import { assertRejects } from "../../deps_dev.ts";
import { ParentClient } from "../core/parentClient.ts";
Deno.test("Throws when no email is provided", async () => {
const client = new ParentClient("", "password");
await assertRejects(
async () => {
await client.login();
},
Error,
"Email not provided",
);
const client = new ParentClient("", "password");
await assertRejects(
async () => {
await client.login();
},
Error,
"Email not provided",
);
});
Deno.test("Throws when no password is provided", async () => {
const client = new ParentClient("email", "");
await assertRejects(
async () => {
await client.login();
},
Error,
"Password not provided",
);
const client = new ParentClient("email", "");
await assertRejects(
async () => {
await client.login();
},
Error,
"Password not provided",
);
});
Deno.test("Throws with invalid username and password", async () => {
const client = new ParentClient("invalid", "invalid");
await assertRejects(
async () => {
await client.login();
},
Error,
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
const client = new ParentClient("invalid", "invalid");
await assertRejects(
async () => {
await client.login();
},
Error,
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
});

View file

@ -2,116 +2,109 @@ import { API_BASE_STUDENT, BASE_URL } from "../utils/consts.ts";
import { BaseClient } from "../core/baseClient.ts";
import { parseCookies } from "../utils/utils.ts";
import {
GetStudentCodeOptions,
GetStudentCodeResponse,
RewardPurchaseResponse,
RewardsResponse,
GetStudentCodeOptions,
GetStudentCodeResponse,
RewardPurchaseResponse,
RewardsResponse,
} from "../types.ts";
/**
* Student Client
*/
export class StudentClient extends BaseClient {
/**
* @property studentCode ClassCharts student code
*/
private studentCode = "";
/**
* @property dateOfBirth Student's date of birth
*/
private dateOfBirth = "";
/**
* @property studentCode ClassCharts student code
*/
private studentCode = "";
/**
* @property dateOfBirth Student's date of birth
*/
private dateOfBirth = "";
/**
* @param studentCode ClassCharts student code
* @param dateOfBirth Student's date of birth
*/
constructor(studentCode: string, dateOfBirth?: string) {
super(API_BASE_STUDENT);
this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth);
}
/**
* @param studentCode ClassCharts student code
* @param dateOfBirth Student's date of birth
*/
constructor(studentCode: string, dateOfBirth?: string) {
super(API_BASE_STUDENT);
this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth);
}
/**
* Authenticates with ClassCharts
*/
async login(): Promise<void> {
if (!this.studentCode) throw new Error("Student Code not provided");
const formData = new URLSearchParams();
formData.append("_method", "POST");
formData.append("code", this.studentCode.toUpperCase());
formData.append("dob", this.dateOfBirth);
formData.append("remember_me", "1");
formData.append("recaptcha-token", "no-token-available");
const request = await fetch(BASE_URL + "/student/login", {
method: "POST",
body: formData,
redirect: "manual",
});
if (request.status != 302 || !request.headers.has("set-cookie")) {
await request.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
}
const cookies = String(request.headers.get("set-cookie"));
this.authCookies = cookies.split(",");
const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse(
String(sessionCookies["student_session_credentials"]),
);
this.sessionId = sessionID.session_id;
await this.getNewSessionId();
const user = await this.getStudentInfo();
this.studentId = user.data.user.id;
}
/**
* Authenticates with ClassCharts
*/
async login(): Promise<void> {
if (!this.studentCode) throw new Error("Student Code not provided");
const formData = new URLSearchParams();
formData.append("_method", "POST");
formData.append("code", this.studentCode.toUpperCase());
formData.append("dob", this.dateOfBirth);
formData.append("remember_me", "1");
formData.append("recaptcha-token", "no-token-available");
const request = await fetch(`${BASE_URL}/student/login`, {
method: "POST",
body: formData,
redirect: "manual",
});
if (request.status !== 302 || !request.headers.has("set-cookie")) {
await request.body?.cancel(); // Make deno tests happy by closing the body, unsure whether this is needed for the actual library
throw new Error(
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
}
const cookies = String(request.headers.get("set-cookie"));
this.authCookies = cookies.split(",");
const sessionCookies = parseCookies(cookies);
const sessionID = JSON.parse(
String(sessionCookies.student_session_credentials),
);
this.sessionId = sessionID.session_id;
await this.getNewSessionId();
const user = await this.getStudentInfo();
this.studentId = user.data.user.id;
}
/**
* Gets the available items in the current student's rewards shop
* @returns Array of purchasable items
*/
async getRewards(): Promise<RewardsResponse> {
return (
await this.makeAuthedRequest(
this.API_BASE + "/rewards/" + this.studentId,
{
method: "GET",
},
)
);
}
/**
* Gets the available items in the current student's rewards shop
* @returns Array of purchasable items
*/
async getRewards(): Promise<RewardsResponse> {
return await this.makeAuthedRequest(
`${this.API_BASE}/rewards/${this.studentId}`,
{
method: "GET",
},
);
}
/**
* Purchase a reward item from the current student's rewards shop
* @param itemId number
* @returns An object containing the current student's balance and item ID purchased
*/
async purchaseReward(itemId: number): Promise<RewardPurchaseResponse> {
return (
await this.makeAuthedRequest(
this.API_BASE + "/purchase/" + itemId,
{
method: "POST",
body: `pupil_id=${this.studentId}`,
},
)
);
}
/**
* Purchase a reward item from the current student's rewards shop
* @param itemId number
* @returns An object containing the current student's balance and item ID purchased
*/
async purchaseReward(itemId: number): Promise<RewardPurchaseResponse> {
return await this.makeAuthedRequest(`${this.API_BASE}/purchase/${itemId}`, {
method: "POST",
body: `pupil_id=${this.studentId}`,
});
}
/**
* Gets the current student's student code
* @param options GetStudentCodeOptions
* @param options.dateOfBirth Date of birth in the format YYYY-MM-DD
* @returns
*/
async getStudentCode(
options: GetStudentCodeOptions,
): Promise<GetStudentCodeResponse> {
const data = await this.makeAuthedRequest(this.API_BASE + "/getcode", {
method: "POST",
body: JSON.stringify({
date: options.dateOfBirth,
}),
});
return data;
}
/**
* Gets the current student's student code
* @param options GetStudentCodeOptions
* @param options.dateOfBirth Date of birth in the format YYYY-MM-DD
* @returns
*/
async getStudentCode(
options: GetStudentCodeOptions,
): Promise<GetStudentCodeResponse> {
const data = await this.makeAuthedRequest(`${this.API_BASE}/getcode`, {
method: "POST",
body: JSON.stringify({
date: options.dateOfBirth,
}),
});
return data;
}
}

View file

@ -2,23 +2,23 @@ import { assertRejects } from "../../deps_dev.ts";
import { StudentClient } from "../core/studentClient.ts";
Deno.test("Throws when no student code is provided", async () => {
const client = new StudentClient("");
await assertRejects(
async () => {
await client.login();
},
Error,
"Student Code not provided",
);
const client = new StudentClient("");
await assertRejects(
async () => {
await client.login();
},
Error,
"Student Code not provided",
);
});
Deno.test("Throws with invalid student code", async () => {
const client = new StudentClient("invalid");
await assertRejects(
async () => {
await client.login();
},
Error,
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
const client = new StudentClient("invalid");
await assertRejects(
async () => {
await client.login();
},
Error,
"Unauthenticated: ClassCharts didn't return authentication cookies",
);
});