UNPKG

skolengojs

Version:

A wrapper around Skolengo internal API.

1 lines 30.9 kB
"use strict";var e=require("@noble/hashes/sha2.js"),t=require("@scure/base"),s=e=>"homework-assignments/"+e,i=class{constructor(e){this.baseURL=e}async sendRequest(e){const{method:t,path:s,body:i,headers:a}=e,o=`${this.baseURL}/${s}`,r=await fetch(o,{method:t,body:i?JSON.stringify(i):void 0,headers:{"Content-Type":"application/json",...a,"User-Agent":"@raphckrman/skolengo.js"}});if(!r.ok){const e=await r.json();throw new Error(`${r.status}: ${JSON.stringify(e)}`)}return await r.json()}async delete(e,t,s){const i=new URLSearchParams(t).toString(),a=i?`${e}?${i}`:e;return this.sendRequest({method:"DELETE",path:a,headers:s?.headers})}async get(e,t,s){const i=new URLSearchParams(t).toString(),a=i?`${e}?${i}`:e;return this.sendRequest({method:"GET",path:a,headers:s})}async post(e,t,s,i){const a=new URLSearchParams(s).toString(),o=a?`${e}?${a}`:e;return this.sendRequest({method:"POST",path:o,body:t,headers:i?.headers})}async put(e,t,s){return this.sendRequest({method:"PUT",path:e,body:t,headers:s?.headers})}async patch(e,t,s,i){const a=new URLSearchParams(s).toString(),o=a?`${e}?${a}`:e;return this.sendRequest({method:"PATCH",path:o,body:t,headers:i?.headers})}},a=async(e,t)=>{const s=await fetch(e,{method:"GET",headers:t?{Authorization:`Bearer ${t}`}:{}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);const i=await s.arrayBuffer();return Buffer.from(i)},o=class{constructor(e,t,s,i,a,o,r){this.accessToken=e,this.id=t,this.url=s,this.fileName=i,this.type=a,this.typeLabel=o,this.size=r}fetchAttachmentBuffer(){return a(this.url,this.accessToken)}};function r(e){return e&&!Array.isArray(e.data)?e.data:void 0}var n=e=>e&&Array.isArray(e.data)?e.data:[],l=new i("https://api.skolengo.com/api/v1/bff-sko-app"),c=async(e,t,s,i,a=new Date,o=new Date((new Date).setMonth((new Date).getMonth()+1)))=>{const n=e=>e.toISOString().slice(0,10),c=await l.get("homework-assignments",{"filter[student.id]":e,"filter[dueDate][GE]":n(a),"filter[dueDate][LE]":n(o),include:"subject,teacher,individualCorrectedWork,individualCorrectedWork.attachments,individualCorrectedWork.audio,commonCorrectedWork.attachments,commonCorrectedWork.audio,commonCorrectedWork.pedagogicContent","fields[homework]":"title,html,deliverWorkOnline,onlineDeliveryUrl,done,dueDateTime","fields[subject]":"label,color"},{Authorization:`Bearer ${t}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":i}),d=new Map;for(const e of c.included??[])d.set(`${e.type}:${e.id}`,e);return(Array.isArray(c.data)?c.data:[]).filter((e=>"homework"===e.type)).map((a=>{const o=r(a.relationships.teacher)?.id,n=o?d.get(`teacher:${o}`):null,l=r(a.relationships.subject)?.id,c=l?d.get(`subject:${l}`):null;return new u(t,e,i,s,a.id,a.attributes?.done??!1,a.attributes?.title??"",a.attributes?.html??"",new Date(a.attributes?.dueDateTime??""),a.attributes?.deliverWorkOnline??!1,a.attributes?.onlineDeliverUrl??"",{id:l??"",label:c?.attributes?.label??"",color:c?.attributes?.color??""},{id:o??"",title:n?.attributes?.title??"",firstName:n?.attributes?.firstName??"",lastName:n?.attributes?.lastName??"",photoUrl:n?.attributes?.photoUrl??""})}))},d=async(e,t,i,a,r)=>{const n=await l.get(s(e),{"filter[student.id]":t,include:"attachments","fields[attachment]":"name,mimeType,mimeTypeLabel,size,url"},{Authorization:`Bearer ${a}`,"x-skolengo-ems-code":r,"x-skolengo-school-id":i}),c=new Map;for(const e of n.included??[])c.set(`${e.type}:${e.id}`,e);return Array.from(c.entries()).filter((([e])=>e.startsWith("attachment:"))).map((([,e])=>{const t=e;return new o(a,t.id,t.attributes?.url??"",t.attributes?.name??"",t.attributes?.mimeType??"",t.attributes?.mimeTypeLabel??"",t.attributes?.size??0)}))},h=async(e,t,i,a,o,n)=>{const c=await l.patch(s(e),{data:{type:"homework",id:e,attributes:{done:i}}},{"filter[student.id]":t,include:"attachments","fields[attachment]":"name,mimeType,mimeTypeLabel,size,url"},{headers:{Authorization:`Bearer ${o}`,"x-skolengo-ems-code":n,"x-skolengo-school-id":a}}),d=new Map;for(const e of c.included??[])d.set(`${e.type}:${e.id}`,e);const h=c.data,p=r(h.relationships.subject)?.id,m=r(h.relationships.teacher)?.id,b=p?d.get("subject:"+p):null,f=m?d.get("teacher:"+m):null;return new u(o,t,a,n,e,i,h.attributes?.title??"",h.attributes?.html??"",new Date(h.attributes?.dueDateTime??""),h.attributes?.deliverWorkOnline??!1,h.attributes?.onlineDeliverUrl??"",{id:b?.id??"",label:b?.attributes?.label??"",color:b?.attributes?.color??""},{id:f?.id??"",title:f?.attributes?.title??"",firstName:f?.attributes?.firstName??"",lastName:f?.attributes?.lastName??"",photoUrl:f?.attributes?.photoUrl??""})},u=class{constructor(e,t,s,i,a,o,r,n,l,c,d,h,u){this.accessToken=e,this.userId=t,this.schoolId=s,this.emsCode=i,this.id=a,this.done=o,this.title=r,this.html=n,this.dueDateTime=l,this.deliverWorkOnline=c,this.onlineDeliverUrl=d,this.subject=h,this.teacher=u}async getAttachments(){return d(this.id,this.userId,this.schoolId,this.accessToken,this.emsCode)}async setCompletion(e){const t=e??!this.done;return h(this.id,this.userId,t,this.schoolId,this.accessToken,this.emsCode)}},p=class{constructor(e,t,s,i,a,o,r,n,l,c){this.id=e,this.startDateTime=t,this.endDateTime=s,this.room=i,this.canceled=a,this.hasContent=o,this.hasHomeworkToDoForTheLesson=r,this.hasHomeworkToDoAfterTheLesson=n,this.subject=l,this.teacher=c}},m=class{constructor(e,t,s){this.date=e,this.lessons=t,this.assignments=s}},b=new i("https://api.skolengo.com/api/v1/bff-sko-app"),f=async(e,t,s,i,a=new Date,o=new Date((new Date).setMonth((new Date).getMonth()+1)),l=50)=>{const c=e=>e.toISOString().slice(0,10),d=await b.get("agendas",{"filter[student.id]":e,"filter[date][GE]":c(a),"filter[date][LE]":c(o),include:"lessons,lessons.subject,lessons.teachers,homeworkAssignments,homeworkAssignments.subject","fields[lesson]":"title,startDateTime,endDateTime,location,canceled,anyContent,anyHomeworkToDoForTheLesson,anyHomeworkToDoAfterTheLesson,subject,teachers","fields[homework]":"title,done,dueDateTime,subject,html,deliverWorkOnline, onlineDeliverUrl","fields[cateringService]":"title,startDateTime,endDateTime","fields[teacher]":"firstName,lastName,title","fields[subject]":"label,color","page[limit]":l},{Authorization:`Bearer ${i}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":t}),h=new Map;for(const e of d.included??[])h.set(`${e.type}:${e.id}`,e);const f=[],g=d.data;for(const a of g){const o=[],l=n(a.relationships.lessons),c=[],d=n(a.relationships.homeworkAssignments);for(const a of d){const o=h.get("homework:"+a.id),n=r(o.relationships?.subject)?.id,l=n?h.get("subject:"+n):null;c.push(new u(i,e,t,s,a.id,o.attributes?.done??!1,o.attributes?.title??"",o.attributes?.html??"",new Date(o.attributes?.dueDateTime??""),o.attributes?.deliverWorkOnline??!1,o.attributes?.onlineDeliverUrl??"",{id:n??"",label:l?.attributes?.label??"",color:l?.attributes?.color??""}))}for(const e of l){const t=e.id?h.get("lesson:"+e.id):null,s=r(t?.relationships?.subject)?.id,i=s?h.get("subject:"+s):null,a=[],l=n(t?.relationships?.teachers);for(const e of l){const t=h.get("teacher:"+e.id);a.push({id:e.id,title:t.attributes?.title??"",firstName:t.attributes?.firstName??"",lastName:t.attributes?.lastName??"",photoUrl:t.attributes?.photoUrl??""})}o.push(new p(e.id,new Date(t?.attributes?.startDateTime??""),new Date(t?.attributes?.endDateTime??""),t?.attributes?.location??"",t?.attributes?.canceled??!1,t?.attributes?.anyContent??!1,t?.attributes?.anyHomeworkToDoForTheLesson??!1,t?.attributes?.anyHomeworkToDoAfterTheLesson??!1,{id:i?.id??"",label:i?.attributes?.label??"",color:i?.attributes?.color??""},a))}f.push(new m(new Date(a.attributes?.date??""),o,c))}return f},g=class{constructor(e,t,s,i,a,o,r){this.id=e,this.creationDate=t,this.startDate=s,this.endDate=i,this.type=a,this.state=o,this.reason=r}},S="SkoApp.Prod.0d349217-9a4e-41ec-9af9-df9e69e09494",w="7cb4d9a8-2580-4041-9ae8-d5803869183f",y="skoapp-prod://sign-in-callback",T=(e=>(e.READ_EVALUATIONS="READ_EVALUATIONS",e.READ_ABSENCE_FILES="READ_ABSENCE_FILES",e.READ_MESSAGES="READ_MESSAGES",e.WRITE_MESSAGES="WRITE_MESSAGES",e.READ_LESSONS="READ_LESSONS",e.READ_ASSIGNMENTS="READ_HOMEWORK_ASSIGNMENTS",e.MARK_ASSIGNMENT_AS_DONE="MARK_HOMEWORK_ASSIGNMENT_AS_DONE",e))(T||{}),k=(e=>(e.MESSAGES="MSG",e.TIMETABLE="CDT",e.APP="SKOAPP",e.ABSENCES="ABS",e.ARTICLES="ART",e.HOMEWORK="TAF",e.EVALUATIONS="EVAL",e.COMMUNICATION="COMC",e))(k||{}),A=(e=>(e.PLAIN="plain",e.S256="S256",e))(A||{}),v=(e=>(e.LATENESS="LATENESS",e.ABSENCE="ABSENCE",e))(v||{}),E=(e=>(e.LOCKED="LOCKED",e.OPEN="OPEN",e))(E||{}),N=(e=>(e.NONE="NONE",e.INSUFFICIENT_MASTERY="INSUFFICIENT_MASTERY",e.LOW_MASTERY="LOW_MASTERY",e.SATISFACTORY_MASTERY="SATISFACTORY_MASTERY",e.VERY_GOOD_MASTERY="VERY_GOOD_MASTERY",e))(N||{}),D=(e=>(e.INBOX="INBOX",e.SENT="SENT",e.PERSONAL="PERSONAL",e.TRASH="TRASH",e))(D||{}),R=(e=>(e[e.STUDENT=0]="STUDENT",e[e.PARENT=1]="PARENT",e))(R||{}),C=new i("https://api.skolengo.com/api/v1/bff-sko-app"),I=async(e,t,s,i)=>{const a=await C.get("absence-files",{"filter[student.id]":e,"filter[currentState.absenceType]":"ABSENCE,CLATENESS","filter[absenceFile]":"currentState",include:"currentState,currentState.absenceReason,currentState.absenceRecurrence","fields[absenceFileState]":"creationDateTime,absenceStartDateTime,absenceEndDateTime,absenceType,absenceFileStatus,absenceReason,absenceRecurrence","fields[absenceReason]":"code,longLabel"},{Authorization:`Bearer ${i}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":t}),o=new Map;for(const e of a.included??[])o.set(`${e.type}:${e.id}`,e);return(Array.isArray(a.data)?a.data:[]).filter((e=>"absenceFile"===e.type)).map((e=>{const t=r(e.relationships.currentState)?.id,s=t?o.get("absenceFileState:"+t):null,i=r(s?.relationships?.absenceReason)?.id,a=i?o.get("absenceReason:"+i):null;return new g(e.id,new Date(s?.attributes?.creationDateTime??""),new Date(s?.attributes?.absenceStartDateTime??""),new Date(s?.attributes?.absenceEndDateTime??""),s?.attributes?.absenceType??"ABSENCE",s?.attributes?.absenceFileStatus??"OPEN",a?.attributes?.longLabel??"")}))},$=class{constructor(e,t,s,i,a,o,r,n,l,c){this.id=e,this.isGraded=t,this.value=s,this.outOf=i,this.date=a,this.coefficient=o,this.title=r,this.topic=n,this.subject=l,this.notGradedReason=c}},x=class{constructor(e,t,s,i){this.id=e,this.label=t,this.startDate=s,this.endDate=i}},U=class{constructor(e,t,s,i){this.label=e,this.shortLabel=t,this.level=s,this.color=i}},L=class{constructor(e,t,s,i,a,o,r,n){this.id=e,this.name=t,this.coefficient=s,this.value=i,this.outOf=a,this.average=o,this.grades=r,this.teachers=n}},M=new i("https://api.skolengo.com/api/v1/bff-sko-app"),O=async(e,t,s,i)=>{const a=await M.get("homework-assignments",{"filter[student.id]":e,include:"periods,skillsSetting,skillsSetting.skillAcquisitionColors","fields[evaluationsSetting]":"periodicReportsEnabled,skillsEnabled,evaluationsDetailsAvailable","fields[period]":"label,startDate,endDate","fields[skillsSetting]":"skillAcquisitionLevels,skillAcquisitionColors","fields[skillAcquisitionColors]":"colorLevelMappings"},{Authorization:`Bearer ${t}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":i}),o=new Map;for(const e of a.included??[])o.set(`${e.type}:${e.id}`,e);const l=Array.isArray(a.data)?a.data[0]:a.data,c=n(l.relationships.periods).map((e=>{const t=o.get(`period:${e.id}`);return new x(e.id,t.attributes?.label??"",new Date(t.attributes?.startDate??""),new Date(t.attributes?.endDate??""))})),d=r(l.relationships.periods),h="string"==typeof d?.id?d.id:"",u=h?o.get(`skillsSetting:${h}`):void 0,p=u?.attributes?.skillAcquisitionLevels?u.attributes.skillAcquisitionLevels.map((e=>{const t=r(u.relationships?.skillAcquisitionColors),s="string"==typeof t?.id?t.id:"",i=s?o.get(`skillAcquisitionColors:${s}`):void 0,a=i?.attributes?.colorLevelMappings.find((t=>t.level===e.level));return new U(e.label,e.shortLabel,e.level,a?.color)})):[];return{periodicReportsEnabled:l?.attributes?.periodicReportsEnabled??!1,skillsEnabled:l?.attributes?.skillsEnabled??!1,evaluationsDetailsAvailable:l?.attributes?.evaluationsDetailsAvailable??!1,periods:c,skillLevels:p}},_=async(e,t,s,i,a=20,o=0)=>{const n=await M.get("evaluations-results",{"page[limit]":a,"page[offset]":o,"filter[student.id]":e,include:"evaluation,evaluation.evaluationService,evaluation.evaluationService,evaluation.subSubject,evaluation.evaluationService.subject,subSkillsEvaluationResults","fields[evaluationResult]":"mark,nonEvaluationReason,evaluation,subSkillEvaluationResult","fields[subSkillEvaluationResult]":"level","fields[evaluation]":"dateTime,topic,title,scale,evaluationService,subSubject","fields[subSubject]":"label","fields[evaluationService]":"subject","fields[subject]":"label,color"},{Authorization:`Bearer ${t}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":i}),l=new Map;for(const e of n.included??[])l.set(`${e.type}:${e.id}`,e);return(Array.isArray(n.data)?n.data:[]).filter((e=>"evaluationResult"===e.type)).map((e=>{const t=r(e.relationships.evaluation),s="string"==typeof t?.id?t.id:"",i=l.get(`evaluation:${s}`),a=r(i.relationships.evaluationService),o=a&&"string"==typeof a.id?a.id:"",n=l.get(`evaluationService:${o}`),c=r(n?.relationships?.subject),d="string"==typeof c?.id?c.id:"",h=l.get(`subject:${d}`);return console.log(c,d,h),new $(e.id,!e.attributes?.nonEvaluationReason,e.attributes?.mark??20,i.attributes?.scale??0,new Date(i.attributes?.dateTime??""),i.attributes?.coefficient??1,i.attributes?.title??"",i.attributes?.topic??"",{id:d,label:h?.attributes?.label??"",color:h?.attributes?.color??""},e.attributes?.nonEvaluationReason??void 0)}))},G=async(e,t,s,i,a)=>{const o=await M.get("evaluation-services",{"filter[student.id]":e,"filter[period.id]":a,include:"subject,evaluations,evaluations.evaluationResult,evaluations.evaluationResult.subSkillsEvaluationResults,evaluations.evaluationResult.subSkillsEvaluationResults.subSkill,evaluations.subSkills,teachers","fields[evaluationService]":"coefficient,average,studentAverage,scale","fields[subject]":"label,color","fields[evaluation]":"dateTime,coefficient,average,scale,evaluationResult,subSkills","fields[evaluationResult]":"mark,nonEvaluationReason,subSkillsEvaluationResults","fields[subSkillEvaluationResult]":"level,subSkill","fields[teacher]":"firstName,lastName,title","fields[subSkill]":"shortLabel"},{Authorization:`Bearer ${t}`,"x-skolengo-ems-code":s,"x-skolengo-school-id":i}),l=new Map;for(const e of o.included??[])l.set(`${e.type}:${e.id}`,e);return(Array.isArray(o.data)?o.data:[]).filter((e=>"evaluationService"===e.type)).map((e=>{const t=[],s=n(e.relationships.teachers);for(const e of s){const s=l.get(`teacher:${e.id}`);t.push({id:e.id,firstName:s.attributes?.firstName??"",lastName:s.attributes?.lastName??"",photoUrl:s.attributes?.photoUrl??"",title:s.attributes?.title??""})}const i=[],a=n(e.relationships.evaluations);for(const e of a){const t=l.get(`evaluation:${e.id}`),s=r(t.relationships?.evaluationResult)?.id,a=s?l.get(`evaluationResult:${s}`):void 0;i.push(new $(e.id,!a?.attributes?.nonEvaluationReason,a?.attributes?.mark??0,t.attributes?.scale??20,new Date(t.attributes?.dateTime??""),t.attributes?.coefficient??1,void 0,void 0,void 0))}const o=r(e.relationships.subject),c="string"==typeof o?.id?o.id:"",d=l.get(`subject:${c}`);return new L(e.id,d.attributes?.label??"",e.attributes?.coefficient??1,e.attributes?.studentAverage??10,e.attributes?.scale??20,e.attributes?.average??10,i,t)}))},P=class{constructor(e,t,s,i,a,o,r,n,l,c,d,h,u){this.emsCode=e,this.accessToken=t,this.id=s,this.subject=i,this.messages=a,this.participants=o,this.read=r,this.date=n,this.content=l,this.sender=c,this.replyToAllAllowed=d,this.replyToSenderAllowed=h,this.readTrackingEnabled=u}async getMessages(){return z(this.id,this.emsCode,this.accessToken)}},j=class{constructor(e,t,s,i,a,o){this.id=e,this.date=t,this.content=s,this.read=i,this.attachments=a,this.author=o}},B=new i("https://api.skolengo.com/api/v1/bff-sko-app"),F=async(e,t,s)=>{const i=await B.get((e=>"users-mail-settings/"+e)(e),{include:"contacts,contacts.person,contacts.personContacts,signature,folders,folders.parent","fields[userMailSetting]":"maxCharsInParticipationContent,maxCharsInCommunicationSubject","fields[signature]":"content","fields[folder]":"name,position,type,parent"},{Authorization:`Bearer ${s}`,"x-skolengo-ems-code":t}),a=new Map;for(const e of i.included??[])a.set(`${e.type}:${e.id}`,e);const o=i.data,l=r(o.relationships.signature),c=n(o.relationships.folders),d=a.get(`signature:${l?.id??""}`),h=c.map((e=>{const t=a.get(`folder:${e.id}`);return{id:e.id,name:t.attributes?.name??"",position:t.attributes?.position??0,type:t.attributes?.type??"PERSONAL"}})),u=n(o.relationships.contacts).map((e=>({id:e.id,type:e.type})));return{maxCharsInCommunicationSubject:o.attributes?.maxCharsInCommunicationSubject??0,maxCharsInParticipationContent:o.attributes?.maxCharsInParticipationContent??0,signature:d.attributes?.content??"",folders:h,recipients:u}},W=async(e,t,s,i,a)=>{const o=await B.get("communications",{"filter[folders.id]":e,include:"lastParticipation,lastParticipation.sender,lastParticipation.sender.person,lastParticipation.sender.technicalUser","fields[communication]":"subject,participationsNumber,recipientsSummary,read,replyToAllAllowed,replyToSenderAllowed,readTrackingEnabled,lastParticipation","fields[participation]":"dateTime,content,sender","fields[personParticipant]":"person,technicalUser","fields[person]":"firstName,lastName,photoUrl","fields[technicalUser]":"label","page[limit]":t,"page[offset]":s},{Authorization:`Bearer ${a}`,"x-skolengo-ems-code":i}),n=new Map;for(const e of o.included??[])n.set(`${e.type}:${e.id}`,e);return(Array.isArray(o.data)?o.data:[]).filter((e=>"communication"===e.type)).map((e=>{const t=e.attributes?.recipientsSummary.match(/<span(?:\s+[^>]*)?>(.*?)<\/span>/g)?.map((e=>e.replaceAll(/<[^>]+>/g,""))),s=r(e.relationships.lastParticipation),o=n.get(`participation:${s?.id??""}`),l=r(o.relationships?.sender),c=n.get(`personParticipant:${l?.id??""}`),d=c.relationships?.technicalUser.data?r(c.relationships?.technicalUser):r(c.relationships?.person),h=d&&"technicalUser"===d.type?n.get(`${d?.type}:${d?.id??""}`):n.get(`${d?.type??""}:${d?.id??""}`);return new P(i,a,e.id,e.attributes?.subject??"",e.attributes?.participationsNumber??1,t??[],e.attributes?.read??!1,new Date(o.attributes?.dateTime??""),o.attributes?.content??"",{id:d?.id??"",name:"technicalUser"===d?.type?h&&"attributes"in h&&h.attributes&&"label"in h.attributes?h.attributes.label:"":h&&"attributes"in h&&h.attributes&&"firstName"in h.attributes&&"lastName"in h.attributes?`${h.attributes.firstName} ${h.attributes.lastName}`:""},e.attributes?.replyToAllAllowed??!1,e.attributes?.replyToSenderAllowed??!1,e.attributes?.readTrackingEnabled??!1)}))},z=async(e,t,s)=>{const i=await B.get((e=>"communications/"+e+"/participations")(e),{include:"sender,sender.person,sender.technicalUser,attachments","fields[participation]":"dateTime,content,read,sender","fields[personParticipant]":"additionalInfo,person,technicalUser","fields[person]":"firstName,lastName,title,photoUrl","fields[technicalUser]":"label","fields[attachment]":"name,mimeType,mimeTypeLabel,size,url"},{Authorization:`Bearer ${s}`,"x-skolengo-ems-code":t}),a=new Map;for(const e of i.included??[])a.set(`${e.type}:${e.id}`,e);return(Array.isArray(i.data)?i.data:[]).filter((e=>"participation"===e.type)).map((e=>{const t=n(e.relationships.attachments).map((e=>{const t=a.get(`attachment:${e.id}`);return new o(s,e.id,t.attributes.url,t.attributes.name,t.attributes.mimeType,t.attributes.mimeTypeLabel,t.attributes.size)})),i=r(e.relationships?.sender),l=a.get(`personParticipant:${i?.id??""}`),c=l.relationships?.technicalUser.data?r(l.relationships?.technicalUser):r(l.relationships?.person),d=c&&"technicalUser"===c.type?a.get(`${c?.type}:${c?.id??""}`):a.get(`${c?.type??""}:${c?.id??""}`);return new j(e.id,new Date(e.attributes?.dateTime??""),e.attributes?.content??"",e.attributes?.read??!1,t,{id:c?.id??"",name:"technicalUser"===c?.type?d&&"attributes"in d&&d.attributes&&"label"in d.attributes?d.attributes.label:"":d&&"attributes"in d&&d.attributes&&"firstName"in d.attributes&&"lastName"in d.attributes?`${d.attributes.firstName} ${d.attributes.lastName}`:""})}))},K=async(e,t,s=[],i=[],a=[],o,r)=>{const n=(await B.post("communications",{data:{type:"communication",attributes:{subject:e,firstParticipationContent:t},relationships:{toRecipients:{data:s},ccRecipients:{data:s},bccRecipients:{data:s}}}},{},{headers:{Authorization:`Bearer ${o}`,"x-skolengo-ems-code":r}})).data.id;return new P(r,o,n,e,1,[...s.map((e=>e.id)),...i.map((e=>e.id)),...a.map((e=>e.id))],!1,new Date,t)},q=e=>{const t=e.split("/");return[t.slice(0,3).join("/"),t.slice(3).join("/")]},H=async e=>{const[t,s]=q(e),a=new i(t),o=await a.get(s);if(o.jwks_uri&&o.authorization_endpoint&&o.token_endpoint)return o;throw new Error("Invalid OIDC Provider Metadata")},Y=async e=>{const[t,s]=q(e),a=new i(t),o=await a.get(s);if(Array.isArray(o.keys))return o;throw new Error("Invalid JWK")},V=async(e,t,s)=>{const[a,o]=q(e),r=new i(a),n=new URLSearchParams({client_id:S,client_secret:w,code:t,code_verifier:s,grant_type:"authorization_code",redirect_uri:y});return r.get(o,n)},J=async(e,t)=>{const[s,a]=q(e),o=new i(s),r=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:S,client_secret:w,scope:"openid+profile"});return o.post(a,r)},X=class{constructor(e,t,s,i,a,o,r,n){this.id=e,this.publicationDateTime=t,this.title=s,this.shortContent=i,this.content=a,this.author=o,this.linkedWebSiteUrl=r,this.illustration=n}};function Z(e=43){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let s="";for(let i=0;i<e;i++){s+=t[Math.floor(66*Math.random())]}return s}var Q=class e{constructor(e,t,s,i,a,o,r,n,l,c,d,h,u,p,m){this.accessToken=e,this.refreshToken=t,this.refreshURL=s,this.accessTokenTTL=i,this.userId=a,this.firstName=o,this.lastName=r,this.className=n,this.mobilePhone=l,this.dateOfBirth=c,this.regime=d,this.kind=h,this.permissions=u,this.school=p,this.kids=m}async GetAllMails(e=20,t=0){await this.refreshAccessToken();const s=(await this.GetMailSettings()).folders;for(const i of s){const s=await W(i.id,e,t,this.school.emsCode,this.accessToken);i.mails||(i.mails=[]),i.mails?.push(...s)}return s}async GetAssignments(e,t){return await this.refreshAccessToken(),c(this.userId,this.accessToken,this.school.emsCode,this.school.id,e,t)}async GetAttendanceItems(){return await this.refreshAccessToken(),I(this.userId,this.school.id,this.school.emsCode,this.accessToken)}async GetGradesForPeriod(e){await this.refreshAccessToken();const t=[];if(!e&&(t.push(...(await this.GetGradesSettings()).periods),!t[0]))throw new Error("We are unable to find any periods.");return G(this.userId,this.accessToken,this.school.emsCode,this.school.id,e??t[0].id)}async GetGradesSettings(){return await this.refreshAccessToken(),O(this.userId,this.accessToken,this.school.emsCode,this.school.id)}async GetLastGrades(e,t){return await this.refreshAccessToken(),_(this.userId,this.accessToken,this.school.emsCode,this.school.id,e,t)}async GetMailFromFolder(e,t,s){return await this.refreshAccessToken(),W(e,t,s,this.school.emsCode,this.accessToken)}async GetMailSettings(){return await this.refreshAccessToken(),F(this.userId,this.school.emsCode,this.accessToken)}async GetNews(){return await this.refreshAccessToken(),re(this.accessToken,this.school.emsCode)}async GetTimetable(e,t){return await this.refreshAccessToken(),f(this.userId,this.school.id,this.school.emsCode,this.accessToken,e,t)}async initKids(t){1===this.kind&&(this.kids=t.map((t=>new e(this.accessToken,this.refreshToken,this.refreshURL,this.accessTokenTTL,t.id,t.firstName,t.lastName,t.className,"",new Date(t.dateOfBirth),t.regime,0,[],this.school))))}async refreshAccessToken(){if(!this.refreshToken)throw new Error("No refresh token available. Please authenticate again.");if(Date.now()>=this.accessTokenTTL){const e=await J(this.refreshURL,this.refreshToken);return this.accessToken=e.access_token,this.refreshToken=e.refresh_token,!0}return!1}async SendMail(e,t,s,i,a){return await this.refreshAccessToken(),K(e,t,s,i,a,this.school.emsCode,this.accessToken)}},ee=e=>{const t=e.split(".")[1],s=Buffer.from(t,"base64").toString("utf8");return JSON.parse(s)},te=new i("https://api.skolengo.com/api/v1/bff-sko-app"),se=async(e,t,s,i,a)=>{const o=ee(e),l={Authorization:`Bearer ${e}`,"x-skolengo-ems-code":a},c=await te.get((d=o.sub,"users-info/"+d),{include:"school,students,students.school,schools,prioritySchool","fields[userInfo]":"lastName,firstName,photoUrl,externalMail,mobilePhone,audienceId,permissions","fields[school]":"name,timeZone,subscribedServices,city,schoolAudience,administrativeId","fields[legalRepresentativeUserInfo]":"addressLines,postalCode,city,country,students","fields[studentUserInfo]":"className,dateOfBirth,regime,school","fields[teacherUserInfo]":"schools,prioritySchool","fields[localAuthorityStaffUserInfo]":"schools,prioritySchool","fields[nonTeachingStaffUserInfo]":"schools,prioritySchool","fields[otherPersonUserInfo]":"schools,prioritySchool","fields[student]":"firstName,lastName,photoUrl,className,dateOfBirth,regime,school"},l);var d;if(Array.isArray(c.data))throw new TypeError("Expected a single user object in response data.");const h=c.data,u=h.attributes,p=function(e){if("legalRepresentativeUserInfo"===e)return 1;return 0}(h.type),m=[];let b="";if(0===p&&(b=r(h.relationships.school)?.id??""),1===p){const e=n(h.relationships.students);if(0===e.length)throw new Error("No kids found for this parent.");const t=c.included.find((t=>t.id===e[0].id&&"student"===t.type));b=r(t.relationships?.school)?.id??"";for(const t of e){const e=c.included.find((e=>e.id===t.id&&"student"===e.type));if(!e)throw new Error(`Kid with ID ${t.id} not found in response.`);m.push({id:e.id,lastName:e.attributes?.lastName??"",firstName:e.attributes?.firstName??"",photoUrl:e.attributes?.photoUrl??"",className:e.attributes?.className??"",dateOfBirth:new Date(e.attributes?.dateOfBirth??""),regime:e.attributes?.regime??""})}}const f=c.included.find((e=>e.id===b)),g=f?.attributes,S=new ae(f?.id??"",g?.name??"",a,s,{city:g?.city??""},void 0,g?.administrativeId,g?.subscribedServices),w=new Q(e,t,i,1e3*(o.exp-300),h.id,u.firstName,u.lastName,u.className,u.mobilePhone,new Date(u.dateOfBirth),u.regime,p,u.permissions.flatMap((e=>e.permittedOperations)),S);return await w.initKids(m),w};var ie=class{constructor(e,t,s,i,a){this.challengeMethod=e,this.endpoints=t,this.schoolId=s,this.jwks=i,this.school=a,this.verifier=Z(),this.state=Z(),this.challenge=this.generateChallenge(this.verifier,this.challengeMethod)}generateChallenge(s,i){return"S256"===i?t.base64url.encode(e.sha256.create().update(s).digest()).slice(0,-1):s}get loginURL(){const e=new URLSearchParams({client_id:S,client_secret:w,code_challenge:this.challenge,code_challenge_method:this.challengeMethod,response_type:"code",scope:"openid",schoolId:this.schoolId,state:this.state,redirect_uri:y}),t=new URL(this.endpoints.authorizationEndpoint);return t.search=e.toString(),t.toString()}async finalizeLogin(e,t){const s=decodeURIComponent(t);if(s!==this.state)throw new Error(`Invalid state: received "${s}", expected "${this.state}"`);const i=await V(this.endpoints.tokenEndpoint,e,this.verifier);return se(i.access_token,i.refresh_token,this.endpoints.wellKnown,this.endpoints.tokenEndpoint,this.school.emsCode)}},ae=class{constructor(e,t,s,i,a,o,r,n){this.id=e,this.name=t,this.emsCode=s,this.OIDCWellKnown=i,this.location=a,this.homepage=o,this.UAI=r,this.subscribedServices=n}async initializeLogin(e="S256"){const t=await H(this.OIDCWellKnown),s=await Y(t.jwks_uri);return new ie(e,{wellKnown:this.OIDCWellKnown,authorizationEndpoint:t.authorization_endpoint,tokenEndpoint:t.token_endpoint,revokeEndpoint:t.revocation_endpoint},this.id,s,this)}},oe=new i("https://api.skolengo.com/api/v1/bff-sko-app"),re=async(e,t)=>{const s=await oe.get("schools-info",{include:"illustration,school,author,author.person,author.technicalUser","fields[schoolInfo]":"illustration,school,author,publicationDateTime,title,shortContent,content,linkedWebSiteUrl","fields[announcement]":"level","fields[schoolInfoFile]":"url,alternativeText","fields[school]":"name","fields[schoolInfoAuthor]":"person,technicalUser,additionalInfo","fields[person]":"firstName,lastName,title,photoUrl","fields[schoolInfoTechnicalUser]":"label,logoUrl","page[limit]":50},{Authorization:`Bearer ${e}`,"x-skolengo-ems-code":t}),i=new Map;for(const e of s.included??[])i.set(`${e.type}:${e.id}`,e);return(Array.isArray(s.data)?s.data:[]).filter((e=>"news"===e.type)).map((t=>{const{relationships:s,attributes:a}=t,n=r(s.illustration)?.id,l=r(s.school),c=n?i.get(`schoolInfoFile:${n}`):null,d=l?i.get(`${l.type}:${l.id}`):null;return new X(t.id,new Date(a?.publicationDateTime??""),a?.title??"",a?.shortContent??"",a?.content??"",{id:l?.id??"",name:d?.attributes?.name??""},a?.linkedWebSiteUrl??"",new o(e,c?.id??"",c?.attributes?.url??""))}))};exports.Assignment=u,exports.Attachment=o,exports.AttendanceItem=g,exports.AttendanceItemState=E,exports.AttendanceItemType=v,exports.AuthFlow=ie,exports.ChallengeMethod=A,exports.DecodePayload=ee,exports.GetAssignmentAttachments=d,exports.GetAssignments=c,exports.GetAttendanceItems=I,exports.GetGradesForPeriod=G,exports.GetGradesSettings=O,exports.GetLastGrades=_,exports.GetMailSettings=F,exports.GetMailsFromFolder=W,exports.GetMessagesFromMail=z,exports.GetOIDCAccessTokens=V,exports.GetOIDCJWKS=Y,exports.GetOIDCWellKnown=H,exports.GetSchoolNews=re,exports.GetUserInfo=se,exports.Grade=$,exports.Kind=R,exports.Lesson=p,exports.Mail=P,exports.MailFolder=class{constructor(e,t,s,i,a){this.id=e,this.name=t,this.position=s,this.type=i,this.mails=a}},exports.MailFolderType=D,exports.Message=j,exports.News=X,exports.OIDCRefresh=J,exports.OIDC_CLIENT_ID=S,exports.OIDC_CLIENT_SECRET=w,exports.Period=x,exports.Permissions=T,exports.REDIRECT_URI=y,exports.School=ae,exports.SearchSchools=async(e,t=10,s=0)=>{const i=await oe.get("schools",{"filter[text]":e,"page[limit]":t,"page[offset]":s});return(Array.isArray(i.data)?i.data:[]).filter((e=>"school"===e.type)).map((e=>new ae(e.id,e.attributes?.name??"",e.attributes?.emsCode??"",e.attributes?.emsOIDCWellKnownUrl??"",{city:e.attributes?.city??"",country:e.attributes?.country??"",addressLine:[e.attributes?.addressLine1??"",e.attributes?.addressLine2??"",e.attributes?.addressLine3??""].filter((e=>null!==e)).join(", "),zipCode:e.attributes?.zipCode??""},e.attributes?.homePageUrl??"")))},exports.SendMail=K,exports.Services=k,exports.SetAssignmentCompletion=h,exports.SkillLevel=U,exports.SkillLevels=N,exports.Skolengo=Q,exports.Subject=L,exports.TimetableDay=m,exports.downloadAttachment=a,exports.extractBaseUrl=q,exports.getMultipleRelations=n,exports.getSingleRelation=r,exports.getTimetableForPeriods=f;//# sourceMappingURL=index.js.map