UNPKG

skolengojs

Version:

A wrapper around Skolengo internal API.

1 lines 30.9 kB
import{sha256 as e}from"@noble/hashes/sha2.js";import{base64url as t}from"@scure/base";var 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}`;let n,r={"User-Agent":"@raphckrman/skolengo.js",...a};i instanceof URLSearchParams?(n=i.toString(),r["Content-Type"]="application/x-www-form-urlencoded"):i&&(n=JSON.stringify(i),r["Content-Type"]="application/json");const l=await fetch(o,{method:t,body:n,headers:r});if(!l.ok){const e=await l.json();throw new Error(`${l.status}: ${JSON.stringify(e)}`)}return await l.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,n){this.accessToken=e,this.id=t,this.url=s,this.fileName=i,this.type=a,this.typeLabel=o,this.size=n}fetchAttachmentBuffer(){return a(this.url,this.accessToken)}};function n(e){return e&&!Array.isArray(e.data)?e.data:void 0}var r=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 r=e=>e.toISOString().slice(0,10),c=await l.get("homework-assignments",{"filter[student.id]":e,"filter[dueDate][GE]":r(a),"filter[dueDate][LE]":r(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=n(a.relationships.teacher)?.id,r=o?d.get(`teacher:${o}`):null,l=n(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:r?.attributes?.title??"",firstName:r?.attributes?.firstName??"",lastName:r?.attributes?.lastName??"",photoUrl:r?.attributes?.photoUrl??""})}))},d=async(e,t,i,a,n)=>{const r=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":n,"x-skolengo-school-id":i}),c=new Map;for(const e of r.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,r)=>{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":r,"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=n(h.relationships.subject)?.id,m=n(h.relationships.teacher)?.id,b=p?d.get("subject:"+p):null,f=m?d.get("teacher:"+m):null;return new u(o,t,a,r,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,n,r,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=n,this.html=r,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,n,r,l,c){this.id=e,this.startDateTime=t,this.endDateTime=s,this.room=i,this.canceled=a,this.hasContent=o,this.hasHomeworkToDoForTheLesson=n,this.hasHomeworkToDoAfterTheLesson=r,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=r(a.relationships.lessons),c=[],d=r(a.relationships.homeworkAssignments);for(const a of d){const o=h.get("homework:"+a.id),r=n(o.relationships?.subject)?.id,l=r?h.get("subject:"+r):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:r??"",label:l?.attributes?.label??"",color:l?.attributes?.color??""}))}for(const e of l){const t=e.id?h.get("lesson:"+e.id):null,s=n(t?.relationships?.subject)?.id,i=s?h.get("subject:"+s):null,a=[],l=r(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,n){this.id=e,this.creationDate=t,this.startDate=s,this.endDate=i,this.type=a,this.state=o,this.reason=n}},w="SkoApp.Prod.0d349217-9a4e-41ec-9af9-df9e69e09494",y="7cb4d9a8-2580-4041-9ae8-d5803869183f",S="skoapp-prod://sign-in-callback",k=(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))(k||{}),T=(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))(T||{}),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||{}),$=new i("https://api.skolengo.com/api/v1/bff-sko-app"),C=async(e,t,s,i)=>{const a=await $.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=n(e.relationships.currentState)?.id,s=t?o.get("absenceFileState:"+t):null,i=n(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??"")}))},I=class{constructor(e,t,s,i,a,o,n,r,l,c){this.id=e,this.isGraded=t,this.value=s,this.outOf=i,this.date=a,this.coefficient=o,this.title=n,this.topic=r,this.subject=l,this.notGradedReason=c}},U=class{constructor(e,t,s,i){this.id=e,this.label=t,this.startDate=s,this.endDate=i}},L=class{constructor(e,t,s,i){this.label=e,this.shortLabel=t,this.level=s,this.color=i}},O=class{constructor(e,t,s,i,a,o,n,r){this.id=e,this.name=t,this.coefficient=s,this.value=i,this.outOf=a,this.average=o,this.grades=n,this.teachers=r}},_=new i("https://api.skolengo.com/api/v1/bff-sko-app"),M=async(e,t,s,i)=>{const a=await _.get("evaluations-settings",{"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=r(l.relationships.periods).map((e=>{const t=o.get(`period:${e.id}`);return new U(e.id,t.attributes?.label??"",new Date(t.attributes?.startDate??""),new Date(t.attributes?.endDate??""))})),d=n(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=n(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 L(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}},j=async(e,t,s,i,a=20,o=0)=>{const r=await _.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 r.included??[])l.set(`${e.type}:${e.id}`,e);return(Array.isArray(r.data)?r.data:[]).filter((e=>"evaluationResult"===e.type)).map((e=>{const t=n(e.relationships.evaluation),s="string"==typeof t?.id?t.id:"",i=l.get(`evaluation:${s}`),a=n(i.relationships.evaluationService),o=a&&"string"==typeof a.id?a.id:"",r=l.get(`evaluationService:${o}`),c=n(r?.relationships?.subject),d="string"==typeof c?.id?c.id:"",h=l.get(`subject:${d}`);return console.log(c,d,h),new I(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)}))},P=async(e,t,s,i,a)=>{const o=await _.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=r(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=r(e.relationships.evaluations);for(const e of a){const t=l.get(`evaluation:${e.id}`),s=n(t.relationships?.evaluationResult)?.id,a=s?l.get(`evaluationResult:${s}`):void 0;i.push(new I(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=n(e.relationships.subject),c="string"==typeof o?.id?o.id:"",d=l.get(`subject:${c}`);return new O(e.id,d.attributes?.label??"",e.attributes?.coefficient??1,e.attributes?.studentAverage??10,e.attributes?.scale??20,e.attributes?.average??10,i,t)}))},B=class{constructor(e,t,s,i,a,o,n,r,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=n,this.date=r,this.content=l,this.sender=c,this.replyToAllAllowed=d,this.replyToSenderAllowed=h,this.readTrackingEnabled=u}async getMessages(){return F(this.id,this.emsCode,this.accessToken)}},x=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}},G=new i("https://api.skolengo.com/api/v1/bff-sko-app"),z=async(e,t,s)=>{const i=await G.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=n(o.relationships.signature),c=r(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=r(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 G.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}),r=new Map;for(const e of o.included??[])r.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=n(e.relationships.lastParticipation),o=r.get(`participation:${s?.id??""}`),l=n(o.relationships?.sender),c=r.get(`personParticipant:${l?.id??""}`),d=c.relationships?.technicalUser.data?n(c.relationships?.technicalUser):n(c.relationships?.person),h=d&&"technicalUser"===d.type?r.get(`${d?.type}:${d?.id??""}`):r.get(`${d?.type??""}:${d?.id??""}`);return new B(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)}))},F=async(e,t,s)=>{const i=await G.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=r(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=n(e.relationships?.sender),l=a.get(`personParticipant:${i?.id??""}`),c=l.relationships?.technicalUser.data?n(l.relationships?.technicalUser):n(l.relationships?.person),d=c&&"technicalUser"===c.type?a.get(`${c?.type}:${c?.id??""}`):a.get(`${c?.type??""}:${c?.id??""}`);return new x(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,n)=>{const r=(await G.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":n}})).data.id;return new B(n,o,r,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),n=new i(a),r=new URLSearchParams({client_id:w,client_secret:y,code:t,code_verifier:s,grant_type:"authorization_code",redirect_uri:S});return n.get(o,r)},J=async(e,t)=>{const[s,a]=q(e),o=new i(s),n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:w,client_secret:y,scope:"openid+profile"});return o.post(a,n)},X=class{constructor(e,t,s,i,a,o,n,r){this.id=e,this.publicationDateTime=t,this.title=s,this.shortContent=i,this.content=a,this.author=o,this.linkedWebSiteUrl=n,this.illustration=r}};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,n,r,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=n,this.className=r,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(),C(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 P(this.userId,this.accessToken,this.school.emsCode,this.school.id,e??t[0].id)}async GetGradesSettings(){return await this.refreshAccessToken(),M(this.userId,this.accessToken,this.school.emsCode,this.school.id)}async GetLastGrades(e,t){return await this.refreshAccessToken(),j(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(),z(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=n(h.relationships.school)?.id??""),1===p){const e=r(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=n(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,w=new ae(f?.id??"",g?.name??"",a,s,{city:g?.city??""},void 0,g?.administrativeId,g?.subscribedServices),y=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)),w);return await y.initKids(m),y};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.encode(e.create().update(s).digest()).slice(0,-1):s}get loginURL(){const e=new URLSearchParams({client_id:w,client_secret:y,code_challenge:this.challenge,code_challenge_method:this.challengeMethod,response_type:"code",scope:"openid",schoolId:this.schoolId,state:this.state,redirect_uri:S}),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,n,r){this.id=e,this.name=t,this.emsCode=s,this.OIDCWellKnown=i,this.location=a,this.homepage=o,this.UAI=n,this.subscribedServices=r}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"),ne=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??"")))},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,r=n(s.illustration)?.id,l=n(s.school),c=r?i.get(`schoolInfoFile:${r}`):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??""))}))},le=class{constructor(e,t,s,i,a){this.id=e,this.name=t,this.position=s,this.type=i,this.mails=a}};async function ce(e,t,s,i,a){const o=await J(e,t);return se(o.access_token,o.refresh_token,s,i,a)}export{u as Assignment,o as Attachment,g as AttendanceItem,E as AttendanceItemState,v as AttendanceItemType,ie as AuthFlow,A as ChallengeMethod,ee as DecodePayload,d as GetAssignmentAttachments,c as GetAssignments,C as GetAttendanceItems,P as GetGradesForPeriod,M as GetGradesSettings,j as GetLastGrades,z as GetMailSettings,W as GetMailsFromFolder,F as GetMessagesFromMail,V as GetOIDCAccessTokens,Y as GetOIDCJWKS,H as GetOIDCWellKnown,re as GetSchoolNews,se as GetUserInfo,I as Grade,R as Kind,p as Lesson,ce as LoginWithToken,B as Mail,le as MailFolder,D as MailFolderType,x as Message,X as News,J as OIDCRefresh,w as OIDC_CLIENT_ID,y as OIDC_CLIENT_SECRET,U as Period,k as Permissions,S as REDIRECT_URI,ae as School,ne as SearchSchools,K as SendMail,T as Services,h as SetAssignmentCompletion,L as SkillLevel,N as SkillLevels,Q as Skolengo,O as Subject,m as TimetableDay,a as downloadAttachment,q as extractBaseUrl,r as getMultipleRelations,n as getSingleRelation,f as getTimetableForPeriods};//# sourceMappingURL=index.mjs.map