1
0
Fork 0
mirror of https://github.com/classchartsapi/classcharts-api-js.git synced 2026-05-14 03:56:59 +00:00

style: prettier

This commit is contained in:
James Cook 2022-01-31 22:32:29 +00:00
parent 0be975389b
commit 0801d3aae0
10 changed files with 529 additions and 492 deletions

View file

@ -1,188 +1,184 @@
import Undici from 'undici'
import { RequestOptions } from 'undici/types/dispatcher'
import Undici from "undici";
import { RequestOptions } from "undici/types/dispatcher";
import {
ActivityResponse,
BehaviourResponse,
GetActivityOptions,
GetBehaviourOptions,
GetHomeworkOptions,
GetLessonsOptions,
Homework,
HomeworksResponse,
LessonsResponse,
Student,
} from './types'
import { API_BASE, BASE_URL } from './consts'
ActivityResponse,
BehaviourResponse,
GetActivityOptions,
GetBehaviourOptions,
GetHomeworkOptions,
GetLessonsOptions,
Homework,
HomeworksResponse,
LessonsResponse,
Student,
} from "./types";
import { API_BASE, BASE_URL } from "./consts";
/**
* The base client
*/
export class ClasschartsClient {
public studentCode = ''
public dateOfBirth = ''
public studentId = 0
public studentName = ''
private authCookies: Array<string> | undefined
private sessionId = ''
/**
*
* @param studentCode Classcharts student code
* @param dateOfBirth Student's date of birth
*/
constructor(studentCode: string, dateOfBirth?: string) {
this.studentCode = String(studentCode)
this.dateOfBirth = String(dateOfBirth)
}
public async makeAuthedRequest(
path: string,
options: Omit<RequestOptions, 'origin' | 'path'>
) {
if (!this.authCookies) throw new Error('Not authenticated')
const requestOptions: Omit<RequestOptions, 'origin' | 'path'> = {
...options,
headers: {
Cookie: this.authCookies.join(';'),
authorization: 'Basic ' + this.sessionId,
},
}
const request = await Undici.request(path, requestOptions)
let responseJSON
try {
responseJSON = await request.body.json()
} catch (err) {
throw new Error('Invalid JSON response, check your dates')
}
if (responseJSON.success == 0) {
throw new Error(responseJSON.error)
}
return responseJSON.data
}
/**
* Initialises the client and authenticates with classcharts
*/
async init(): Promise<void> {
if (!this.studentCode) throw new Error('Student Code not inputted')
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-avaliable')
const request = await Undici.request(BASE_URL + '/student/login', {
method: 'POST',
body: formData.toString(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
if (request.statusCode != 302 || !request.headers['set-cookie'])
throw new Error('Unauthenticated: Classcharts returned an error')
let cookies = request.headers['set-cookie']
for (let i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].substring(0, cookies[i].indexOf(';'))
}
this.authCookies = cookies
let sessionID: any = decodeURI(cookies[2])
.replace(/%3A/g, ':')
.replace(/%2C/g, ',')
sessionID = JSON.parse(
sessionID.substring(sessionID.indexOf('{'), sessionID.length)
)
this.sessionId = sessionID.session_id
const user = await this.getStudentInfo()
this.studentId = user.id
this.studentName = user.name
}
/**
* Gets general information about the logged in student
* @returns Student object
*/
async getStudentInfo(): Promise<Student> {
const data = await this.makeAuthedRequest(API_BASE + '/ping', {
method: 'POST',
body: 'include_date=true',
})
return data?.user
}
/**
* Get's the logged in student's general activity
* @param options GetActivityOptions
* @returns Activity data
*/
async getActivity(
options?: GetActivityOptions
): Promise<ActivityResponse> {
const params = new URLSearchParams()
options?.from && params.append('form', options?.from)
options?.to && params.append('to', options?.to)
return this.makeAuthedRequest(
API_BASE + '/activity/' + this.sessionId + '?' + params.toString(),
{
method: 'GET',
}
)
}
/**
* Gets the logged in students behaviour points
* @param options GetBehaviourOptions
* @returns Array of behaviour points
*/
async getBehaviour(
options?: GetBehaviourOptions
): Promise<BehaviourResponse> {
const params = new URLSearchParams()
options?.from && params.append('form', options?.from)
options?.to && params.append('to', options?.to)
options?.last_id && params.append('last_id', options?.last_id)
return await this.makeAuthedRequest(
API_BASE + '/behaviour/' + this.studentId + '?' + params.toString(),
{
method: 'GET',
}
)
}
/**
* Gets a list of the logged in student's homeworks
* @param options GetHomeworkOptions
* @returns Array of homeworks
*/
async listHomeworks(
options?: GetHomeworkOptions
): Promise<HomeworksResponse> {
const params = new URLSearchParams()
if (options?.displayDate) params.append('display_date', String(options?.displayDate))
options?.fromDate && params.append('from', String(options?.fromDate))
options?.toDate && params.append('to', String(options?.toDate))
let data: Array<Homework> = await this.makeAuthedRequest(
API_BASE + '/homeworks/' + this.studentId + '?' + params.toString(),
{
method: 'GET',
}
)
for (let i = 0; i < data.length; i++) {
// homework.lesson.replace(/\\/g, '')
data[i].description = data[i].description.replace(
/(<([^>]+)>)/gi,
''
)
data[i].description = data[i].description.replace(/&nbsp;/g, '')
data[i].description = data[i].description.trim()
}
return data
}
/**
* Gets the logged in student's lessons for a day
* @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(
API_BASE + '/timetable/' + this.studentId + '?' + params.toString(),
{
method: 'GET',
}
)
}
public studentCode = "";
public dateOfBirth = "";
public studentId = 0;
public studentName = "";
private authCookies: Array<string> | undefined;
private sessionId = "";
/**
*
* @param studentCode Classcharts student code
* @param dateOfBirth Student's date of birth
*/
constructor(studentCode: string, dateOfBirth?: string) {
this.studentCode = String(studentCode);
this.dateOfBirth = String(dateOfBirth);
}
public async makeAuthedRequest(
path: string,
options: Omit<RequestOptions, "origin" | "path">
) {
if (!this.authCookies) throw new Error("Not authenticated");
const requestOptions: Omit<RequestOptions, "origin" | "path"> = {
...options,
headers: {
Cookie: this.authCookies.join(";"),
authorization: "Basic " + this.sessionId,
},
};
const request = await Undici.request(path, requestOptions);
let responseJSON;
try {
responseJSON = await request.body.json();
} catch (err) {
throw new Error("Invalid JSON response, check your dates");
}
if (responseJSON.success == 0) {
throw new Error(responseJSON.error);
}
return responseJSON.data;
}
/**
* Initialises the client and authenticates with classcharts
*/
async init(): Promise<void> {
if (!this.studentCode) throw new Error("Student Code not inputted");
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-avaliable");
const request = await Undici.request(BASE_URL + "/student/login", {
method: "POST",
body: formData.toString(),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
if (request.statusCode != 302 || !request.headers["set-cookie"])
throw new Error("Unauthenticated: Classcharts returned an error");
let cookies = request.headers["set-cookie"];
for (let i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].substring(0, cookies[i].indexOf(";"));
}
this.authCookies = cookies;
let sessionID: any = decodeURI(cookies[2])
.replace(/%3A/g, ":")
.replace(/%2C/g, ",");
sessionID = JSON.parse(
sessionID.substring(sessionID.indexOf("{"), sessionID.length)
);
this.sessionId = sessionID.session_id;
const user = await this.getStudentInfo();
this.studentId = user.id;
this.studentName = user.name;
}
/**
* Gets general information about the logged in student
* @returns Student object
*/
async getStudentInfo(): Promise<Student> {
const data = await this.makeAuthedRequest(API_BASE + "/ping", {
method: "POST",
body: "include_date=true",
});
return data?.user;
}
/**
* Get's the logged in student's general activity
* @param options GetActivityOptions
* @returns Activity data
*/
async getActivity(options?: GetActivityOptions): Promise<ActivityResponse> {
const params = new URLSearchParams();
options?.from && params.append("form", options?.from);
options?.to && params.append("to", options?.to);
return this.makeAuthedRequest(
API_BASE + "/activity/" + this.sessionId + "?" + params.toString(),
{
method: "GET",
}
);
}
/**
* Gets the logged in students behaviour points
* @param options GetBehaviourOptions
* @returns Array of behaviour points
*/
async getBehaviour(
options?: GetBehaviourOptions
): Promise<BehaviourResponse> {
const params = new URLSearchParams();
options?.from && params.append("form", options?.from);
options?.to && params.append("to", options?.to);
options?.last_id && params.append("last_id", options?.last_id);
return await this.makeAuthedRequest(
API_BASE + "/behaviour/" + this.studentId + "?" + params.toString(),
{
method: "GET",
}
);
}
/**
* Gets a list of the logged in student's homeworks
* @param options GetHomeworkOptions
* @returns Array of homeworks
*/
async listHomeworks(
options?: GetHomeworkOptions
): Promise<HomeworksResponse> {
const params = new URLSearchParams();
if (options?.displayDate)
params.append("display_date", String(options?.displayDate));
options?.fromDate && params.append("from", String(options?.fromDate));
options?.toDate && params.append("to", String(options?.toDate));
let data: Array<Homework> = await this.makeAuthedRequest(
API_BASE + "/homeworks/" + this.studentId + "?" + params.toString(),
{
method: "GET",
}
);
for (let i = 0; i < data.length; i++) {
// homework.lesson.replace(/\\/g, '')
data[i].description = data[i].description.replace(/(<([^>]+)>)/gi, "");
data[i].description = data[i].description.replace(/&nbsp;/g, "");
data[i].description = data[i].description.trim();
}
return data;
}
/**
* Gets the logged in student's lessons for a day
* @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(
API_BASE + "/timetable/" + this.studentId + "?" + params.toString(),
{
method: "GET",
}
);
}
}

View file

@ -1,2 +1,2 @@
export const BASE_URL = 'https://www.classcharts.com'
export const API_BASE = `${BASE_URL}/apiv2student`
export const BASE_URL = "https://www.classcharts.com";
export const API_BASE = `${BASE_URL}/apiv2student`;

View file

@ -1 +1 @@
export * from './client'
export * from "./client";

View file

@ -1,145 +1,145 @@
export interface Student {
id: number
name: string
first_name: string
last_name: string
avatar_url: string
display_behaviour: boolean
display_parent_behaviour: boolean
display_homework: boolean
display_rewards: boolean
display_detentions: boolean
display_report_cards: boolean
display_classes: boolean
display_announcements: boolean
display_attendance: boolean
display_attendance_type: string
display_attendance_percentage: boolean
display_activity: boolean
display_mental_health: boolean
display_timetable: boolean
is_disabled: boolean
display_two_way_communications: boolean
display_absences: boolean
can_upload_attachments: string | null
display_event_badges: boolean
display_avatars: boolean
display_concern_submission: boolean
display_custom_fields: boolean
pupil_concerns_help_text: string
allow_pupils_add_timetable_notes: boolean
announcements_count: number
messages_count: number
pusher_channel_name: string
has_birthday: boolean
has_new_survey: boolean
survey_id: number | null
detention_alias_plural_uc: string
id: number;
name: string;
first_name: string;
last_name: string;
avatar_url: string;
display_behaviour: boolean;
display_parent_behaviour: boolean;
display_homework: boolean;
display_rewards: boolean;
display_detentions: boolean;
display_report_cards: boolean;
display_classes: boolean;
display_announcements: boolean;
display_attendance: boolean;
display_attendance_type: string;
display_attendance_percentage: boolean;
display_activity: boolean;
display_mental_health: boolean;
display_timetable: boolean;
is_disabled: boolean;
display_two_way_communications: boolean;
display_absences: boolean;
can_upload_attachments: string | null;
display_event_badges: boolean;
display_avatars: boolean;
display_concern_submission: boolean;
display_custom_fields: boolean;
pupil_concerns_help_text: string;
allow_pupils_add_timetable_notes: boolean;
announcements_count: number;
messages_count: number;
pusher_channel_name: string;
has_birthday: boolean;
has_new_survey: boolean;
survey_id: number | null;
detention_alias_plural_uc: string;
}
export interface GetActivityOptions {
from?: string
to?: string
from?: string;
to?: string;
}
export interface ActivityTimelinePoint {
positive: number
negative: number
name: string
start: string
end: string
positive: number;
negative: number;
name: string;
start: string;
end: string;
}
export interface ActivityResponse {
timeline: Array<ActivityTimelinePoint>
positiveReasons: Record<string, string>
negative_reasons: Record<string, string>
other_positive: Array<any>
other_negative: Array<any>
other_positive_count: Array<any>
other_negative_count: Array<any>
timeline: Array<ActivityTimelinePoint>;
positiveReasons: Record<string, string>;
negative_reasons: Record<string, string>;
other_positive: Array<any>;
other_negative: Array<any>;
other_positive_count: Array<any>;
other_negative_count: Array<any>;
}
export interface GetBehaviourOptions {
from?: string
to?: string
last_id?: string
from?: string;
to?: string;
last_id?: string;
}
export interface BehaviourPoint {
id: number
type: string
polarity: string
reason: string
score: number
timestamp: string
timestamp_custom_time: string | null
style: {
border_color: string | null
custom_class: string | null
}
pupil_name: string
lesson_name: string
teacher_name: string
room_name: string | null
note: string
_can_delete: string
detention_date: string | null
detention_time: string | null
detention_location: string | null
detention_type: string | null
id: number;
type: string;
polarity: string;
reason: string;
score: number;
timestamp: string;
timestamp_custom_time: string | null;
style: {
border_color: string | null;
custom_class: string | null;
};
pupil_name: string;
lesson_name: string;
teacher_name: string;
room_name: string | null;
note: string;
_can_delete: string;
detention_date: string | null;
detention_time: string | null;
detention_location: string | null;
detention_type: string | null;
}
export type BehaviourResponse = Array<BehaviourPoint>
export type DisplayDate = 'due_date' | 'issue_date'
export type BehaviourResponse = Array<BehaviourPoint>;
export type DisplayDate = "due_date" | "issue_date";
export interface GetHomeworkOptions {
displayDate?: DisplayDate
fromDate?: string
toDate?: string
displayDate?: DisplayDate;
fromDate?: string;
toDate?: string;
}
export interface Homework {
lesson: string
subject: string
teacher: string
homework_type: string
id: number
title: string
meta_title: string
description: string
issue_date: string
due_date: string
completion_time_unit: string
completion_time_value: string
publish_time: string
status: {
id: number
state: null
mark: null
mark_relative: number
ticked: 'yes' | 'no'
allow_attachments: string
first_seen_date: string
last_seen_date: string
attachments: Array<any>
has_feedback: boolean
}
validated_links: Array<any>
validated_attachments: Array<any>
lesson: string;
subject: string;
teacher: string;
homework_type: string;
id: number;
title: string;
meta_title: string;
description: string;
issue_date: string;
due_date: string;
completion_time_unit: string;
completion_time_value: string;
publish_time: string;
status: {
id: number;
state: null;
mark: null;
mark_relative: number;
ticked: "yes" | "no";
allow_attachments: string;
first_seen_date: string;
last_seen_date: string;
attachments: Array<any>;
has_feedback: boolean;
};
validated_links: Array<any>;
validated_attachments: Array<any>;
}
export type HomeworksResponse = Array<Homework>
export type HomeworksResponse = Array<Homework>;
export interface GetLessonsOptions {
date: string
date: string;
}
export interface Lesson {
teacher_name: string
lesson_name: string
subject_name: string
is_alternative_lesson: boolean
period_name: string
period_number: string
room_name: string
date: string
start_time: string
end_time: string
key: number
note_abstract: string
note: string
pupil_note_abstract: string
pupil_note: string
pupil_note_raw: string
teacher_name: string;
lesson_name: string;
subject_name: string;
is_alternative_lesson: boolean;
period_name: string;
period_number: string;
room_name: string;
date: string;
start_time: string;
end_time: string;
key: number;
note_abstract: string;
note: string;
pupil_note_abstract: string;
pupil_note: string;
pupil_note_raw: string;
}
export type LessonsResponse = Array<Lesson>
export type LessonsResponse = Array<Lesson>;