- Notifications
You must be signed in to change notification settings - Fork2
Simple node.js package to manage your EduPage account.
License
loumadev/EdupageAPI
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This is an unofficial Node.js implementation of the Edupage API. This module is not maintained, authorized, or sponsored by Edupage. Edupage's internal API could change at any time, and break functionality of this module. If you find bugs, have any questions or suggestions for features, please let me know and submit an issue.
EdupageAPI is a module to easily access and interact with your Edupage account. All the basic types likestudents,teachers,subjects,timetables,messages are stored into the groups with user-friendly API to get data and do basic actions (obtaining lessons,replying to messages...). You can also a send message marked asImportant, which is not possible using the official Edupage application (unless you have an account with teacher privileges).
- Node.js v14.0.0+
- Edupage account
npm i edupage-api
The only thing you need to set up the API is to log in, like so:
const{Edupage}=require("edupage-api");// Create blank Edupage instanceconstedupage=newEdupage();// This will automatically create new User instance and// fill in all arrays and properties inside `edupage`edupage.login("username/email","password").then(user=>{// Currently logged user (`user`) can be also accessed by `edupage.user`// Here you can write your code...}).catch(err=>{// Catch errors});
Most of the objects have_data
property, which holds raw data fetched directly from Edupage servers so in case there are no parsed properties you are looking for, you can get raw data by accessing those_data
properties and process it yourself.
Note: In production, you should be handling Promise rejections bypromise.catch()
ortry ... catch
.
This example shows how to obtain timetable (with lessons) for current date. Initially there are available 2 to 4 timetables only, but this method tries to automatically fetch and update given timetables.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get today's date for exampleconstdate=newDate();//Get timetable for `date`consttimetable=awaitedupage.getTimetableForDate(date);//Get array with lessons for this timetableconstlessons=timetable.lessons;console.log(lessons);edupage.exit();//To exit the process})();
This simple snippet returns each homework and test happening the next day (from today) as an array of the assignments.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get tomorrow's dateconsttomorrow=newDate();tomorrow.setDate(tomorrow.getDate()+1);//Get lessonsconsttimetable=awaitedupage.getTimetableForDate(tomorrow);constlessons=timetable.lessons;//Collect assignmentsconsthomeworks=lessons.reduce((arr,lesson)=>(arr.push(...lesson.assignments),arr),[]);console.log(homeworks);edupage.exit();//To exit the process})();
If you need to access multiple timetables at once, you can use this method.
Note: You shouldn't be calling this method in loop for same date range, usegetTimetableForDate
method instead which reads from cache.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Choose a date rangeconstfrom=newDate("2021-05-10");constto=newDate("2021-05-15");//Fetch array of the timetables//Note: This will also update `edupage.timetables` arrayconsttimetables=awaitedupage.fetchTimetablesForDates(from,to);console.log(timetables);edupage.exit();//To exit the process})();
Using this simple snippet you can tell your teacher that you are present on the lesson.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get today's date for exampleconstdate=newDate();//Get timetable for todayconsttimetable=awaitedupage.getTimetableForDate(date);//Get your lesson//Note: This will return second lesson in array, not second period.// In case you want to access second period you may need:// `timetable.lessons.find(e => e.period.id == "3")`constlesson=timetable.lessons[1];//You should check if the lesson is an online lessonif(lesson.isOnlineLesson){//Sign it (this method may not be successful, in such case it will return `false`)constsuccess=awaitlesson.signIntoLesson();console.log(success);}edupage.exit();//To exit the process})();
This example shows how to send a simple message to another user.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get the userconstclassmate=edupage.students.find(e=>e.firstname=="John"&&e.lastname=="Smith");//Configure the messageconstoptions={text:"Hello there!",//Message contentimportant:true//Make this message marked as important};//Send the messageawaitclassmate.sendMessage(options);edupage.exit();//To exit the process})();
This example shows how to send a message with an attachment(s) to another user.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get a userconstteacher=edupage.teachers.find(e=>e.firstname=="John"&&e.lastname=="Smith");//Upload the attachmentconstattachment=awaitedupage.uploadAttachment("C:/Users/username/Documents/Homework.docx");//Configure the messageconstoptions={text:"Sending my homework!",//Message contentattachments:[attachment]//Array of attachments};//Send the messageawaitteacher.sendMessage(options);edupage.exit();//To exit the process})();
Using this snippet you can access material data and/or results of an assignment. This method is not implemented yet, so you have to process it yourself.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get an assignment (you can search by title, id...)constassignment=edupage.assignments.find(e=>e.title.startsWith("Surface integral of vector field"));//Get the data//Note: This returns RawDataObject (it might get implemented in the future)const{materialData, resultsData}=awaitassignment.getData();console.log(materialData,resultsData);edupage.exit();//To exit the process})();
🚨 This example is experimental, you should avoid using it in production until stable version!
Are you annoyed sending each week a new infectivity application? You can make that programmatically now! The following snipped shows how to post Covid-19 infectivity application with current date.
const{Edupage}=require("edupage-api");constedupage=newEdupage();(async()=>{awaitedupage.login("username","password");//Get an application you want to postconstapplication=edupage.applications.find(e=>e.id=="teacher_infectivity_2_20210517");//Get today's dateconsttoday=newDate();//Post the applicationconstsuccess=awaitapplication.post({date:Edupage.dateToString(today)//Processing for the values is not supported, so you have to make it yourself});//Console.log the result (🚨 This might not be precise!)console.log(success);edupage.exit();//To exit the process})();
Here you can find representations of all classes, interfaces and enums. In code, you shouldn't be creating any instances of the following classes except forEdupage
class. All required classes are created internally. Most of the classes containEdupage
instance.
Note: following snippets are not actual valid code.
This class holds the basic information about a school and logged user.
classASCextendsRawData{edupage:Edupage;loggedUser:string;// UserString of the currently logger userloggedUserRights:any[];lang:string;// Language codetimezone:string;// Example: "Europe/Bratislava"firstDayOfWeek:number;// 0 = sundayweekendDays:number[];// 0 = sundayschoolName:string;// Long name of the schoolschoolCountry:string;// Country codeschoolyearTurnover:string;// Example: "08-01"server:string;gsecHash:string;gpids:string[];gpid?:string;}
🚨 This is an experimental class, you should not be using this class in production
This class holds the information about an application (e.g. Covid-19 infectivity)
classApplicationextendsRawData{edupage:Edupage;id:string;name:string;dateFrom:Date;dateTo:Date;parameters:string[];// List of parameters to be passed to `Application.post(...)`availableFor:EntityType;// Usually `ENTITY_TYPE.STUDENT` or `ENTITY_TYPE.TEACHER`isEnabled:boolean;// Determines whether the application is enabled in your EdupageisTextOptional:boolean;// Unknown propertyisAdvancedWorkflow:boolean;// Unknown propertyisSimpleWorkflow:boolean;// Unknown property// Creates draft for the applicationasynccreateDraft():Promise<string>;// Posts the application// 🚨 This method might not return accurate resultstaticpost(parameters:RawDataObject={},// Parameters from `Application.parameters`draftId?:string=null// Draft ID (created internally if not provided)):Promise<boolean>;}
This class holds the information about an assignment such as homework, test, presentation...
classAssignmentextendsRawData{edupage:Edupage;id:string;superId:string;testId:string;hwkid:string;type:AssignmentType;owner:User|Teacher;// Creator of the assignmentsubject:Subject;period:Period;grades:Grade[];creationDate:Date;// Time when was the assignment createdfromDate:Date;// Time from when is the assignment available for studentstoDate:Date;// Time until the assignment is available for studentsduration:number;// Number of seconds for students to submit the assignmenttitle:string;details:string;comment:string;result:string;state:string;stateUpdatedDate:Date;stateUpdatedBy:User|Teacher;cardsCount:number;answerCardsCount:number;isSeen:boolean;isFinished:boolean;asyncgetData():Promise<RawDataObject>;staticfrom(data:RawDataObject,edupage:Edupage):Assignment|Homework|Test;}
This class holds the information about an attachment.
classAttachmentextendsRawData{edupage:Edupage;name:string;// Name containing file extensionsrc:string;// Source url, absolute path}
This class holds basic the information about a school class.
classClassextendsRawData{edupage:Edupage;id:string;grade:number;// e.g. first grade, second grade etc.name:string;short:string;classroom:Classroom;teacher?:Teacher;teacher2?:Teacher;}
This class holds basic the information about a classroom.
classClassroomextendsRawData{edupage:Edupage;id:string;name:string;short:string;cb_hidden:boolean;}
This is the main EdupageAPI class, containing all resources fetched and parsed from the Edupage servers.You can access all properties and methods to obtain required data.The property_data
contains original raw data. (As well as some data which are not supported yet)
classEdupageextendsRawData{user:User|Teacher|Student;// Gets assigned automatically after successful login() callstudents:Student[];teachers:Teacher[];parents:Parent[];plans:Plan[];classes:Class[];classrooms:Classroom[];seasons:Season[];periods:Period[];subjects:Subject[];timetables:Timetable[];timelineItems:Message[];// Contains all timeline items (including confirmations)timeline:Message[];// Contains only visible items (messages, assignments, grades...)assignments:Assignment[];// Contains all assignments (homework assignments, tests and other)homeworks:Homework[];// Contains assignments type of homeworktests:Test[];// Contains assignments type of testASC:ASC;year:number;baseUrl:string;// Example: "https://example.edupage.org"getUserById(id:string):User|Teacher|Student|Parent|undefined;getUserByUserString(userString:string):User|Teacher|Student|Parent|undefined;getYearStart(time?:boolean=false):string;// Example: "2020-08-01" or "2020-08-01 00:00:00"asyncgetTimetableForDate(date:Date):Promise<Timetable|undefined>;// Note: Calls `fetchTimetablesForDates` method internally if the given timetable is missingasyncfetchTimetablesForDates(// Fetches the timetables from Edupage (+caching and updating existing)fromDate:Date,toDate:Date):Promise<Timetable[]>asynclogin(username:string,password:string):Promise<User|Teacher|Student>;asyncrefresh():void;// Refreshes all values in current instanceasyncrefreshEdupage(_update?:boolean=true):void;// Refreshes global Edupage data (such as teachers, classes, classrooms, subjects...)asyncrefreshTimeline(_update?:boolean=true):void;// Refreshes timeline data (messages, notifications...)asyncrefreshCreatedItems(_update?:boolean=true):void;// Refreshes timeline items data created by currently logged userasyncrefreshGrades(_update?:boolean=true):void;// Refreshes grades of currently logged user_updateInternalValues():void;// Updates all fields of the current instance (called internally after// any of the "refresh" methods, if `_update` is set to `true`)asyncuploadAttachment(filepath:string):Promise<Attachment>;asyncapi(options:APIOptions,_count:number=0):Promise<RawDataObject|string,Error|{retry:true,count:number}>;scheduleSessionPing():void;asyncpingSession():Promise<boolean>;exit():void;// Stops internal timers to prevent process from hanging infinitely.staticcompareDay(date1:Date|number|string,date2:Date|number|string):boolean;staticdateToString(// Converts Date into string (Example: "2020-05-17")date:Date):string;}
This class holds the information about a student's grade.
Note: propertiespoints
,maxPoints
andpercentage
are only available iftype == "3"
.
classGradeextendsRawData{edupage:Edupage;id:string;eventId:string;superId:string;type:string;state:string;provider:string;// Usually "edupage"student:Student;teacher:Teacher;creationDate:Date;signedDate:Date;signedByParentDate:Date;plan:Plan;class:Class;classes:Class[];season:Season;subject:Subject;assignment:Assignment;title:string;short:string;date:string;value:string;// Actual gradeweight:number;// Weight of the grade as decimal number (Example: 0.25)points?:number;// Points gainedmaxPoints?:number;// Max possible pointspercentage?:number;// Ratio between gained points and maxPoints in percentsaverage:string;// Average gained points / grade in classisSigned:boolean;isClassified:boolean;}
This is a wrapper class for the Assignment class
classHomeworkextendsAssignment{}
This class holds the information about a lesson.
classLessonextendsRawData{edupage:Edupage;id:string;lid:string;students:Student[];teachers:Teacher[];classes:Class[];classrooms:Classroom[];date:Date;// Starting time of the lessonperiod:Period;subject:Subject;assignments:Assignment[];onlineLessonURL:string;homeworkNote:string;absentNote:string;curriculum:string;isOnlineLesson:boolean;asyncsignIntoLesson():Promise<boolean>;}
This class holds the information about a message.You can also do some basic actions likereplying,liking the message,starring the message...
classMessageextendsRawData{edupage:Edupage;id:string;otherId:string;type:TimelineItemType;owner:User|Teacher|Student|Parent;// Sender or Authorrecipient:User|Teacher|Student|Parent|Plan|Class;recipientUserString:string;// In some cases, the recipient cannot be parsed, so this property holds it's raw UserStringparticipants:(User|Teacher|Student|Parent)[];participantsCount:number;creationDate:Date;// Time when the message was createdtimelineDate:Date;// Time on the timeline (when someone reacts to the message, it will get pushed at the top of the timeline)lastReplyDate:Date;// Time of the last replyseenDate:Date;// Time when the message has been seen (this will be always same as `creationDate` if the message is not important)likedDate:Date;doneDate:Date;likedBy:({user:User|Teacher|Student|Parent,date:Date})[];seenBy:({user:User|Teacher|Student|Parent,date:Date})[];text:string;title:string;likes:number;replyOf:Message;replies:Message[];repliesCount:number;attachments:Attachment[];assignment:Assignment;isRemoved:boolean;isReply:boolean;isImportant:boolean;isSeen:boolean;// This will be always true if the message is not importantisLiked:boolean;isDone:boolean;isStarred:boolean;isWildcardRecipient:boolean;// Determines whether exact recipient is known (you should be using `recipientUserString` if this is true)asyncmarkAsSeen():Promise<void>;asyncmarkAsLiked(state?:boolean=true):Promise<boolean>;asyncmarkAsDone(state?:boolean=true):Promise<boolean>;asyncmarkAsStarred(state?:boolean=true):Promise<boolean>;asyncreply(options:MessageReplyOptions):void;asyncrefresh(data?:RawDataObject=null):void;// To refresh message content (e.g. replies) call this method (ignoring `data` paramenter)}
This class holds the basic information about a parent.
classParentextendsUser{edupage:Edupage;id:string;userString:string;firstname:string;lastname:string;gender:GENDER;}
This class holds the information about a school period.
classPeriodextendsRawData{id:string;// Starts from 1name:string;short:string;startTime:string;endTime:string;getInvalid(data?:{//Creates new invalid Periodid?:string?,name?:string,short?:string,startTime?:string,endTime?:string}=null):Period;}
This class holds the information about a school Plan.It's like a group of specific students for some subject.
classPlanextendsRawData{edupage:Edupage;id:string;otherId:string;customClassId:string;teacher:Teacher;teachers:Teacher[];students:Student[];changedDate:Date;approvedDate:Date;name:string;customName:string;classOrdering:number;year:number;season:Season;subject:Subject;classes:Class[];state:string;timetableGroup:string;settings:Object<string,any>;topicsCount:number;taughtCount:number;standardsCount:number;isEntireClass:boolean;isApproved:boolean;isPublic:boolean;isValid:boolean;}
This is the base class for storing raw data fetched from Edupage servers.It contains a single property -_data
, this property is non-enumerable
classRawData{_data:RawDataObject;}
This class holds the information about a school season.It could be month, semester...
classSeasonextendsRawData{edupage:Edupage;id:string;index:number;// Starting from 1 (e.g. first month of the school year)types:string[];// ? Unknown propertyfromDate:Date;toDate:Date;name:string;halfYear:number;// First or second semestersupSeason:Season;// Upper season (e.g. if `this` is the first month, this property will be first a half year)classificationSeason?:Season;isClassification:boolean;}
This class holds the information about a student.
classStudentextendsUser{edupage:Edupage;class:Class;number:number;// ? Unknown propertynumberInClass:number;// This is actual number in classparent1Id:string;parent2Id:string;parent3Id:string;parent1?:Parent;parent2?:Parent;parent3?:Parent;userString:string;getUserString(parents?:boolean=false):string;}
This class holds the information about a subject.
classSubjectextendsRawData{id:string;name:string;short:string;}
This class holds the information about a teacher.
classTeacherextendsUser{edupage:Edupage;classroom:Classroom;short:string;userString:string;cb_hidden:number;// ? Unknown property}
This is a wrapper class for the Assignment class.
classTestextendsAssignment{}
This class holds the information about a timetable.Timetable for only single day, not entire week.
classTimetableextendsRawData{edupage:Edupage;date:Date;week:number;// ? Unknown property (Maybe odd/even week?)lessons:Lesson[];}
This class holds the information about a user.UsesendMessage
method to send message to the user.
classUserextendsRawData{edupage:Edupage;id:string;origin:string;userString:string;dateFrom:Date;dateTo:Date;firstname:string;lastname:string;gender:Gender;email?:string;cookies?:CookieJar;credentials?:{username:string,password:string};isLoggedIn:boolean;isOut:boolean;getUserString():string;asyncsendMessage(options:MessageOptions):Message;asynclogin(username:string,password:string):Promise<User>;staticfrom(userString:string,data?:RawDataObject={},edupage?:Edupage=null):User|Teacher|Student|Parent;}
Using this interface you can specify the API options.
interfaceAPIOptions{url:string|APIEndpoint;// APIEndpoint is automatically resolveddata?:(Object<string,any>|stream.Readable|Buffer|string)={};headers?:Object<string,any>={}; method?:string="POST"; encodeBody?:boolean=true;// Encode body as `form-urlencoded` using Edupage "special" encryptiontype?:"json"|"text"="json";// Response type autoLogin?:boolean=true;// Log in the user automatically if they're logged out (e.g. expired session)}
Using this interface you can specify the message options.
interfaceMessageOptions{text:string;// Content of the messageimportant?:boolean=false;// Mark message as importantparents?:boolean=false;// Include parentsattachments?:Attachment[]=[];}
Using this interface you can specify the message options for reply.
interfaceMessageReplyOptions{text:string;// Content of the replyrecipient?:(User|Teacher|Student|Parent)=null;// Send only to the exact userparents?:boolean=false;// Include parentsattachments?:Attachment[]=[]}
This interface is used to represent raw data fetched from the Edupage servers.
interfaceRawDataObject{[property:string]:any;}
This enum contains records about the API endpoints.
enumAPIEndpoint{DASHBOARD_GET_USER,DASHBOARD_SIGN_ONLINE_LESSON,TIMELINE_GET_DATA,TIMELINE_GET_REPLIES,TIMELINE_GET_CREATED_ITEMS,TIMELINE_CREATE_ITEM,TIMELINE_CREATE_CONFIRMATION,TIMELINE_CREATE_REPLY,TIMELINE_FLAG_HOMEWORK,TIMELINE_UPLOAD_ATTACHMENT,ELEARNING_TEST_DATA,ELEARNING_TEST_RESULTS,ELEARNING_CARDS_DATA,GRADES_DATA}
This enum contains records about the API response statuses.
enumAPIStatus{OK="ok",FAIL="fail"}
This enum contains records about the assignment types.
enumAssignmentType{HOMEWORK="hw",ETEST_HOMEWORK="etesthw",BIG_EXAM="bexam",EXAM="exam",SMALL_EXAM="sexam",ORAL_EXAM="oexam",REPORT_EXAM="rexam",TESTING="testing",TEST="test",PROJECT_EXAM="pexam",ETEST="etest",ETEST_PRINT="etestprint",ETEST_LESSON="etestlesson",LESSON="lekcia",PROJECT="projekt",RESULT="result",CURRICULUM="ucivo",TIMELINE="timeline"}
This enum contains records about the assignments groups.
enumAssignmentGroup{HOMEWORK=["hw","etesthw"],EXAM=["bexam","sexam","oexam","rexam","testing"],TEST=["test","etest","etestprint"],PROJECT=["pexam","projekt"],PRESENTATION=["etestlesson","lekcia"],OTHER=["result","ucivo","timeline"]}
This enum contains records about the entity types.
enumEntityType{STUD_PLAN="StudPlan",STUDENT="Student",CUST_PLAN="CustPlan",STUDENT_ONLY="StudentOnly",STUD_CLASS="StudTrieda",TEACHER="Ucitel",ALL="*",CLASS="Trieda",STUDENT_ALL="Student*",STUDENTONLY_ALL="StudentOnly*",TEACHER_ALL="Ucitel*",ADMIN="Admin",PARENT="Parent"}
This enum contains records about the genders.
enumGender{MALE="M",FEMALE="F"}
This enum contains records about the timeline item types.
enumTimelineItemType{MESSAGE="sprava",MESSAGE_TO_SUBTITUTER="spravasuplujucemu",NOTICEBOARD="nastenka",GRADE_ANNOUNCEMENT="nastenka",GRADE="znamka",NOTE="vcelicka",HOMEWORK="homework",HOMEWORK_STUDENT_STATE="homework",ABSENCE_NOTE="ospravedlnenka",ABSENCE_NOTE_REMINDER="ospravedlnenka_reminder",PROCESS="process",PROCESS_ADMIN="processadmin",STUDENT_ABSENT="student_absent",ACCIDENT="accident",EVENT="event",TIMETABLE="timetable",SUBSTITUTION="substitution",CANTEEN_MENU="stravamenu",CANTEEN_CREDIT="strava_kredit",CANTEEN_SUSPEND_REINSTATE_ORDERS="strava_prerusObnovObj",CANTEEN_OPENING="strava_vydaj",SURVEY="anketa",PLAN="plan",SETTINGS="settings",ALBUM="album",NEWS="news",TEST_ASSIGNMENT="testpridelenie",TEST_RESULT="testvysledok",CHAT="chat",CHECK_IN="pipnutie",CONSULTATION_MESSAGE="konzultaciemsg",CONSULTATION="konzultacie",PAYMENTS="payments",SIGN_IN="signin",CURRICULUM="ucivo",CURRICULUM_REMINDER="ucivo_reminder",BLACKBOARD="bb",STUDENT_PICKUP="odchadzka",TIMETABLE_CLOUD_GENERATE="ttcloudgen",CONFIRMATION="confirmation",CONTEST="contest"}
About
Simple node.js package to manage your EduPage account.