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

chore: line endings

This commit is contained in:
James Cook 2021-11-23 22:12:17 +00:00
parent 7676b50ccf
commit d0ed8b1cd7
4 changed files with 354 additions and 354 deletions

View file

@ -4,52 +4,52 @@
*/ */
import { ClasschartsClient } from '.' import { ClasschartsClient } from '.'
import { import {
ActivityResponse, ActivityResponse,
BehaviourResponse, BehaviourResponse,
GetActivityOptions, GetActivityOptions,
GetBehaviourOptions, GetBehaviourOptions,
GetHomeworkOptions, GetHomeworkOptions,
GetLessonsOptions, GetLessonsOptions,
HomeworksResponse, HomeworksResponse,
LessonsResponse, LessonsResponse,
Student, Student,
} from './types' } from './types'
export async function getStudentInfo( export async function getStudentInfo(
studentCode: string, studentCode: string,
dateOfBirth: string | null dateOfBirth: string | null
): Promise<Student> { ): Promise<Student> {
const client = new ClasschartsClient(studentCode, dateOfBirth) const client = new ClasschartsClient(studentCode, dateOfBirth)
return await client.getStudentInfo() return await client.getStudentInfo()
} }
export async function getActivity( export async function getActivity(
studentCode: string, studentCode: string,
dateOfBirth: string | null, dateOfBirth: string | null,
options: GetActivityOptions | null options: GetActivityOptions | null
): Promise<ActivityResponse> { ): Promise<ActivityResponse> {
const client = new ClasschartsClient(studentCode, dateOfBirth) const client = new ClasschartsClient(studentCode, dateOfBirth)
return await client.getActivity(options) return await client.getActivity(options)
} }
export async function getBehaviour( export async function getBehaviour(
studentCode: string, studentCode: string,
dateOfBirth: string | null, dateOfBirth: string | null,
options: GetBehaviourOptions | null options: GetBehaviourOptions | null
): Promise<BehaviourResponse> { ): Promise<BehaviourResponse> {
const client = new ClasschartsClient(studentCode, dateOfBirth) const client = new ClasschartsClient(studentCode, dateOfBirth)
return await client.getBehaviour(options) return await client.getBehaviour(options)
} }
export async function listHomeworks( export async function listHomeworks(
studentCode: string, studentCode: string,
dateOfBirth: string | null, dateOfBirth: string | null,
options: GetHomeworkOptions | null options: GetHomeworkOptions | null
): Promise<HomeworksResponse> { ): Promise<HomeworksResponse> {
const client = new ClasschartsClient(studentCode, dateOfBirth) const client = new ClasschartsClient(studentCode, dateOfBirth)
return await client.listHomeworks(options) return await client.listHomeworks(options)
} }
export async function getLessons( export async function getLessons(
studentCode: string, studentCode: string,
dateOfBirth: string | null, dateOfBirth: string | null,
options: GetLessonsOptions options: GetLessonsOptions
): Promise<LessonsResponse> { ): Promise<LessonsResponse> {
const client = new ClasschartsClient(studentCode, dateOfBirth) const client = new ClasschartsClient(studentCode, dateOfBirth)
return await client.getLessons(options) return await client.getLessons(options)
} }

View file

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

View file

@ -5,25 +5,25 @@ import fs from 'fs'
// It will not be included in the npm package. // It will not be included in the npm package.
function main() { function main() {
const source = fs const source = fs
.readFileSync(__dirname + '/../package.json') .readFileSync(__dirname + '/../package.json')
.toString('utf-8') .toString('utf-8')
const sourceObj = JSON.parse(source) const sourceObj = JSON.parse(source)
sourceObj.scripts = {} sourceObj.scripts = {}
sourceObj.devDependencies = {} sourceObj.devDependencies = {}
if (sourceObj.main.startsWith('dist/')) { if (sourceObj.main.startsWith('dist/')) {
sourceObj.main = sourceObj.main.slice(5) sourceObj.main = sourceObj.main.slice(5)
} }
fs.writeFileSync( fs.writeFileSync(
__dirname + '/package.json', __dirname + '/package.json',
Buffer.from(JSON.stringify(sourceObj, null, 2), 'utf-8') Buffer.from(JSON.stringify(sourceObj, null, 2), 'utf-8')
) )
fs.writeFileSync( fs.writeFileSync(
__dirname + '/version.txt', __dirname + '/version.txt',
Buffer.from(sourceObj.version, 'utf-8') Buffer.from(sourceObj.version, 'utf-8')
) )
fs.copyFileSync(__dirname + '/../.npmignore', __dirname + '/.npmignore') fs.copyFileSync(__dirname + '/../.npmignore', __dirname + '/.npmignore')
fs.copyFileSync(__dirname + '/../README.MD', __dirname + '/README.MD') fs.copyFileSync(__dirname + '/../README.MD', __dirname + '/README.MD')
} }
main() main()

242
src/types.d.ts vendored
View file

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