UNPKG

pawnote

Version:

A purrfect API wrapper for PRONOTE.

1 lines 52.1 kB
import{setCookiesArrayToRequest as e,defaultFetcher as s}from"@literate.ink/utilities";import n from"node-forge";import t from"pako";var i=e=>{let s=new URL(e);s=new URL(`${s.protocol}//${s.host}${s.pathname}`);const n=s.pathname.split("/");return n[n.length-1].includes(".html")&&n.pop(),s.pathname=n.join("/"),s.href.endsWith("/")?s.href.slice(0,-1):s.href},a=(e,s)=>e.instance.weekFrequencies.get(s),r=(e,s,n="timetable")=>{const t=e.instance.version.join(".");return`${e.information.url}/ical/${n}.ics?icalsecurise=${s}&version=${t}&param=266f3d32`},o=class extends Error{constructor(){super("Unable to resolve the challenge, make sure the credentials or token are corrects"),this.name="BadCredentialsError"}},c=class extends Error{constructor(e){super(e),this.name="AuthenticateError"}},u=class extends Error{constructor(){super("You do not have access to this area or your authorizations are insufficient"),this.name="AccessDeniedError"}},l=class extends Error{constructor(){super("Your account has been deactivated"),this.name="AccountDisabledError"}},d=class extends Error{constructor(){super("You can't send a message or a draft in this discussion"),this.name="DiscussionActionError"}},p=class extends Error{constructor(){super("You should request messages before sending anything"),this.name="DiscussionMessagesMissingError"}},m=e=>{if("["!==(e=e.trim())[0]||"]"!==e[e.length-1])return[];if(0===(e=e.slice(1,-1)).length)return[];const s=[];for(const n of e.split(","))if(n.includes("..")){const[e,t]=n.split("..").map((e=>parseInt(e)));for(let n=e;n<=t;n++)s.push(n)}else s.push(parseInt(n));return s},h=class extends Error{handle;constructor(e,s,n){super("You're asked to custom your security methods"),this.name="SecurityError",this.handle=((e,s,n)=>{const t=m(e.actionsDoubleAuth.V);return{availableSecurityModes:m(e.modesPossibles.V),defaultSecurityMode:e.modeSecurisationParDefaut,passwordRules:(i=e.reglesSaisieMDP,{maxLength:i.max,minLength:i.min,rules:m(i.regles.V)}),shouldCustomPassword:t.includes(k.AIHMSC_PersonnalisationMotDePasse),shouldCustomDoubleAuth:t.includes(k.AIHMSC_ChoixStrategie),shouldEnterPIN:t.includes(k.AIHMSC_SaisieCodePINetSource),shouldEnterSource:t.includes(k.AIHMSC_SaisieSourcePourNotifSeulement),context:{authentication:e,identity:s,initialUsername:n}};var i})(e,s,n)}},f=class extends Error{constructor(e){super(`The source name is too long, limited to ${e} characters`),this.name="SecuritySourceTooLongError"}},g=class extends Error{constructor(){super("Your IP address has been suspended"),this.name="SuspendedIPError"}},D=class extends Error{constructor(){super("The session has expired"),this.name="SessionExpiredError"}},C=class extends Error{constructor(){super("The requested page does not exist"),this.name="PageUnavailableError"}},b=class extends Error{constructor(){super("The site is temporarily unavailable"),this.name="BusyPageError"}},w=class extends Error{constructor(){super("You've been rate-limited"),this.name="RateLimitedError"}},A=class extends Error{constructor(e="An error occurred, server-side"){super(e),this.name="ServerSideError"}},E=class extends Error{constructor(e){super(`Unreachable code reached in '${e}' function, please open an issue on GitHub (LiterateInk/Pawnote)`),this.name="UnreachableError"}},v=class extends Error{constructor(e){super(`The file you are trying to upload is too large, maximum allowed is ${e} bytes`),this.name="UploadSizeError"}},y=class extends Error{constructor(){super("The file upload failed"),this.name="UploadFailedError"}},S={STUDENT:6,PARENT:7,TEACHER:8},M={None:0,Easy:1,Medium:2,Hard:3},V={None:0,Paper:1,FileUpload:2,Kiosk:3,AudioRecording:4},P={Link:0,File:1},N={lu:"lu",nonLu:"nonLu",archiver:"archiver",desarchiver:"desarchiver",transferer:"transferer",signaler:"signaler",modifierCategories:"modifierCategories",fermerDiscussion:"fermerDiscussion",ouvrirDiscussion:"ouvrirDiscussion",signalerSuppression:"signalerSuppression",Trash:"corbeille",Restore:"restauration",Delete:"suppression",brouillon:"brouillon",plus:"plus",purger:"purger",discussionEnFenetre:"discussionEnFenetre",entrerSortirDiscussion:"entrerSortirDiscussion",modificationObjetDiscussion:"modificationObjetDiscussion",afficherDestinataires:"afficherDestinataires",copierContenuVisu:"copierContenuVisu",repondreMessage:"repondreMessage",afficherDiscussion:"afficherDiscussion"},I={OCEM_Utilisateur:0,OCEM_Pre_Reception:1,OCEM_Pre_Archive:2,OCEM_Pre_Envoye:3,OCEM_Pre_Brouillon:4,OCEM_Pre_Poubelle:5,OCEM_Pre_Signalement:6,OCEM_Expl_Bleu:7,OCEM_Expl_Vert:8,OCEM_Expl_Rouge:9,OCEM_Pre_CarnetLiaison:10,OCEM_Pre_Alerte:11,OCEM_Pre_ContactVS:12,OCEM_Pre_Conversation:13,OCEM_Pre_InvisiblePlageDesactivee:14},L={Send:0,SendEveryone:1,SendEveryoneExceptParentsAndStudents:3,ReplyEveryone:2,ReplyEveryoneExceptParentsAndStudents:4,Close:5},T={Entry:0,Main:1,Side:2,Drink:3,Dessert:4,Fromage:5},_={UNKNOWN:0,TEXT:1,PDF:2,EXCEL:3,ARCHIVE:4,IMAGE:5,SOUND:6,VIDEO:7,DIAPORAMA:8,GEOGEBRA:9},R={URL:0,FILE:1,CLOUD:2,KIOSK_LINK:3,CONFERENCE_LINK:4},k={AIHMSC_PersonnalisationMotDePasse:0,AIHMSC_ChoixStrategie:1,AIHMSC_ChoixCodePINetSource:2,AIHMSC_SaisieCodePINetSource:3,AIHMSC_ReinitCodePINetSource:4,AIHMSC_SaisieSourcePourNotifSeulement:5},x={MGDA_PasEncoreChoisi:0,MGDA_Inactive:1,MGDA_NotificationSeulement:2,MGDA_SaisieCodePIN:3},O={csch_VerifierPIN:0,csch_VerifierMotDePassePersonnalise:1,csch_LibellesSourceConnexionDejaConnus:2,csch_EnregistrerChoixUtilisateur:3,csch_AffecterModeDoubleAuthentification:4,csch_AffecterCodePIN:5,csch_RenommerSourceConnexionConnue:6,csch_SupprimerSourceConnexionConnue:7,csch_AffecterMotDePassePersonnalise:8,csch_ModifierLogin:9,csch_DemandeReinitialisationPIN:10,csch_VerifierCodeReinitialisationPIN:11},F={Aucune:0,Classe:1,Group:2,Teacher:3,Student:4,Responsable:5,Niveau:6,Orientation:7,Specialite:8,OptionSpecialite:9,Etablissement:10,Period:11,Service:12,Absence:13,Delay:14,Exclusion:15,Subject:16,Room:17,CoEnseignant:18,Suivis:19,Cours:20,Infirmerie:21,AbsenceRepas:22,Pilier:23,ElementPilier:24,Competence:25,_DisciplineBrevet:26,Palier:27,SousItem:28,Evaluation:29,Stage:30,SousMatiere:31,MaitreDeStage:32,InspecteurPedagogique:33,Personal:34,EvaluationHistorique:35,DossierProgression:36,ContenuDeCours:37,TravailAFaire:38,Progression:39,Dispense:40,Punishment:41,Sanction:42,Communication:43,AbsenceInternat:44,Observation:45,ObservationProfesseurEleve:46,ConvocationVS:47,DocumentJoint:48,InternetCategorie:49,DocJointEtablissement:50,Option:51,ProgrammationPunition:52,ReportPunition:53,DisciplineLivretScolaire:54,QCM:55,ExecutionQCM:56,QCMEditeur:57,PartieDeClasse:58,DocJointEleve:59,Devoir:60,InternetEnumere:61,AppreciationBulletinCompetence:62,Entreprise:63,DomaineProfessionnel:64,OffreDeStage:65,SujetDeStage:66,DocumentCasier:67,Message:68,PossessionMessage:69,RelationMessageDocJointEtablissement:70,Engagement:71,PrecautionaryMeasure:72,SousCategorieObjetDossier:73,Incident:74,ProtagonisteIncident:75,RelationIncidentFichierExterne:76,RegimeEleve:77,RepasAPreparer:78,SessionDeStage:79,Materiel:80,Bourse:81,RelationTravailAFaireEleve:82,LieuDossier:83,ElementProgramme:84,ChapitreEltPgm:85,EltPgmTravailleCDT:86,Appreciation:87,ExecutionDevoirKiosque:88,PanierRessourceKiosque:89,RessourceNumeriqueKiosque:90,MetaMatiere:91,EvaluationSujet:92,EvaluationCorrige:93,LibelleCours:94,Site:95,QuestionQCM:96,RelationElevePilierDeCompetence:97,QuestionCopieQCM:98,Coordonnees:99,ResponsablePostulant:100,ExecutionQCMEleve:101,DocJointInscription:102,CategorieDossier:103,MEFGEP:104,AutreOrientation:105,Commission:106,ReponseEducative:107,SuiviReponseEducative:108,NatureDocumentEleve:109},U={NONE:0,CREATION:1,MODIFICATION:2,DELETION:3,CHILDREN_MODIFICATION:4},G={Error:-1,Grade:0,Absent:1,Exempted:2,NotGraded:3,Unfit:4,Unreturned:5,AbsentZero:6,UnreturnedZero:7,Congratulations:8},B={Lunch:0,Dinner:1},j={InformationText:0,SurveyText:5,TextInput:1,UniqueChoice:2,MultipleChoice:3},q={Reception:0,Broadcast:1,Draft:2,Template:3},$={LogBookIssue:0,Observation:1,Encouragement:2,Other:3},H={NONE:0,LESSON:1,CORRECTION:2,DST:3,ORAL_INTERROGATION:4,TD:5,TP:6,EVALUATION_COMPETENCES:7,EPI:8,AP:9,VISIO:12},J={ACCOUNT:0,ACCOUNT_CONNECTION:1,DIRECT_CONNECTION:2,TOKEN_ACCOUNT_CONNECTION:3,TOKEN_DIRECT_CONNECTION:4,COOKIE_CONNECTION:5},K={Grades:198,Resources:89,Assignments:88,Timetable:16,Evaluations:201,Account:49,Presence:7,News:8,Notebook:19,Discussions:131,Gradebook:13,Menus:10},Q=async(t,i=s)=>{const a=new URL(t.base+"/"+(e=>{let s;switch(e){case S.STUDENT:s="eleve";break;case S.PARENT:s="parent";break;case S.TEACHER:s="professeur"}return`mobile.${s}.html`})(t.kind));for(const[e,s]of Object.entries(t.params))a.searchParams.set(e,s);const r={url:a,redirect:"manual"};e(r,t.cookies);const{content:o}=await i(r);try{const e=o.replace(/ /gu,"").replace(/\n/gu,""),s="Start(",i=")}catch",a=e.substring(e.indexOf(s)+s.length,e.indexOf(i)).replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/gu,'"$2": ').replace(/'/gu,'"');return((e,s)=>{const t=!e.MR&&!e.ER;return{url:s,id:parseInt(e.h),accountKind:e.a,demo:e.d??!1,accessKind:e.g??J.ACCOUNT,rsaModulus:t?"B99B77A3D72D3A29B4271FC7B7300E2F791EB8948174BE7B8024667E915446D4EEA0C2424B8D1EBF7E2DDFF94691C6E994E839225C627D140A8F1146D1B0B5F18A09BBD3D8F421CA1E3E4796B301EEBCCF80D81A32A1580121B8294433C38377083C5517D5921E8A078CDC019B15775292EFDA2C30251B1CCABE812386C893E5":e.MR,rsaExponent:t?"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001":e.ER,rsaFromConstants:t,aesIV:n.random.getBytesSync(16),aesKey:"",skipEncryption:e.sCrA??!1,skipCompression:e.sCoA??!1,http:e.http??!1,poll:e.poll??!1,order:0}})(JSON.parse(a),t.base)}catch(e){if(o.includes("Votre adresse IP est provisoirement suspendue"))throw new g;if(o.includes("Le site n'est pas disponible"))throw new C;if(o.includes("Le site est momentanément indisponible"))throw new b;throw new C}},z=class{static decrypt(e,s,t){s=n.md.md5.create().update(s.bytes()).digest(),t=t.length()?n.md.md5.create().update(t.bytes()).digest():n.util.createBuffer().fillWithByte(0,16);const i=n.util.createBuffer(n.util.binary.hex.decode(e)),a=n.cipher.createDecipher("AES-CBC",s);return a.start({iv:t}),a.update(i),a.finish(),a.output.bytes()}static encrypt(e,s,t){s=n.md.md5.create().update(s.bytes()).digest(),t=t.length()?n.md.md5.create().update(t.bytes()).digest():n.util.createBuffer().fillWithByte(0,16),e=n.util.createBuffer(e);const i=n.cipher.createCipher("AES-CBC",s);return i.start({iv:t}),i.update(e),i.finish(),i.output.toHex()}},Y=(e,s=!1)=>({iv:n.util.createBuffer(s?"":e.information.aesIV),key:n.util.createBuffer(e.information.aesKey)}),W=class{constructor(e,s){this.session=e,this.data=s,this.session.information.order++;const n=s;try{if(this.data=JSON.parse(this.data).donneesSec,this.session.information.skipEncryption||this.decrypt(),this.session.information.skipCompression||this.decompress(),"string"==typeof this.data&&(this.data=JSON.parse(this.data)),void 0!==this.data?._Signature_?.Erreur)throw new A(this.data._Signature_.MessageErreur)}catch(e){if(n.includes("La page a expir"))throw new D;if(n.includes("Votre adresse IP "))throw new g;if(n.includes("La page dem")||n.includes("Impossible d'a"))throw new C;if(n.includes("Vous avez d"))throw new w;if(n.includes("s refus"))throw new u;throw e}}decrypt(){const{iv:e,key:s}=Y(this.session);this.data=z.decrypt(this.data,s,e),this.session.information.skipCompression||(this.data=n.util.bytesToHex(this.data))}decompress(){const e=n.util.hexToBytes(this.data),s=new Uint8Array(Array.from(e).map((e=>e.charCodeAt(0))));this.data=t.inflateRaw(s,{to:"string"})}},Z=class{constructor(e,s,n){this.session=e,this.name=s,this.data=n}process(){this.session.information.order++;const e=this.generateOrder(),s=new URL(`${this.session.information.url}/appelfonction/${this.session.information.accountKind}/${this.session.information.id}/${e}`);return this.session.information.skipCompression||this.compress(),this.session.information.skipEncryption||this.encrypt(),{order:e,url:s}}keys(){return Y(this.session,1===this.session.information.order)}generateOrder(){const{key:e,iv:s}=this.keys();return z.encrypt(this.session.information.order.toString(),e,s)}stringify(){return n.util.encodeUtf8(JSON.stringify(this.data)||"")}compress(){const e=n.util.createBuffer(this.stringify()).toHex(),s=t.deflateRaw(e,{level:6}),i=Array.from(s).map((e=>String.fromCharCode(e))).join("");this.data=n.util.bytesToHex(i)}encrypt(){const{key:e,iv:s}=this.keys(),t=this.session.information.skipCompression?this.stringify():n.util.hexToBytes(this.data);this.data=z.encrypt(t,e,s)}async send(){return this.session.queue.push((async()=>{const e=this.process(),s=await this.session.fetcher({url:e.url,method:"POST",headers:{"Content-Type":"application/json"},content:JSON.stringify({session:this.session.information.id,numeroOrdre:e.order,nom:this.name,donneesSec:this.data})});return new W(this.session,s.content)}))}},X=/^\d{2}\/\d{2}\/\d{4}$/,ee=/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}$/,se=/^\d{2}\/\d{2}\/\d{2} \d{2}h\d{2}$/,ne=(new Date).getFullYear().toString().slice(0,2),te=e=>{if(X.test(e)){const[s,n,t]=e.split("/").map(Number);return new Date(t,n-1,s)}if(ee.test(e)){const[s,n]=e.split(" "),[t,i,a]=s.split("/").map(Number),[r,o,c]=n.split(":").map(Number),u=new Date(a,i-1,t);return u.setHours(r,o,c),u}if(se.test(e)){const[s,n]=e.split(" "),[t,i,a]=s.split("/").map(Number),[r,o]=n.split("h").map(Number),c=new Date(parseInt(`${ne}${a}`),i-1,t);return c.setHours(r,o),c}throw new E("decodePronoteDate")},ie=e=>({id:e.N,name:e.L,startDate:te(e.dateDebut.V),endDate:te(e.dateFin.V)}),ae=e=>({id:e.N,kind:e.G,name:e.L,startDate:te(e.dateDebut.V),endDate:te(e.dateFin.V)}),re=async(e,s=null)=>{const t=n.pki.rsa.setPublicKey(new n.jsbn.BigInteger(e.information.rsaModulus,16),new n.jsbn.BigInteger(e.information.rsaExponent,16)),i=e.information.aesIV;let a;a=e.information.rsaFromConstants?n.util.encode64(e.information.http?t.encrypt(i):i,64):n.util.encode64(t.encrypt(i));const r=new Z(e,"FonctionParametres",{donnees:{identifiantNav:s,Uuid:a}});return(e=>{const s=new Map;for(const n of[1,2]){const t=m(e.General.DomainesFrequences[n].V);for(const i of t)s.set(i,{label:e.General.LibellesFrequences[n],fortnight:n})}return{version:e.General.versionPN.split(".").map(Number),nextBusinessDay:te(e.General.JourOuvre.V),firstMonday:te(e.General.PremierLundi.V),firstDate:te(e.General.PremiereDate.V),lastDate:te(e.General.DerniereDate.V),navigatorIdentifier:e.identifiantNav,endings:e.General.ListeHeuresFin.V.map((e=>e.L)),periods:e.General.ListePeriodes.map(ae),holidays:e.General.listeJoursFeries.V.map(ie),weekFrequencies:s,blocksPerDay:e.General.PlacesParJour}})((await r.send()).data.donnees)},oe=async(e,s)=>{const n=new Z(e,"Identification",{donnees:{genreConnexion:0,genreEspace:e.information.accountKind,identifiant:s.username,pourENT:s.useCAS,enConnexionAuto:!1,enConnexionAppliMobile:s.reuseMobileAuthentication,demandeConnexionAuto:!1,demandeConnexionAppliMobile:s.requestFirstMobileAuthentication,demandeConnexionAppliMobileJeton:s.requestFromQRCode,uuidAppliMobile:s.deviceUUID,loginTokenSAV:""}});return(await n.send()).data.donnees},ce=async(e,s)=>{const n=new Z(e,"Authentification",{donnees:{connexion:0,challenge:s,espace:e.information.accountKind}}),t=(await n.send()).data.donnees;if("number"==typeof t.Acces&&0!==t.Acces)switch(t.Acces){case 1:throw new o;case 2:case 3:case 4:case 5:case 7:case 8:throw new u;case 6:case 10:throw new l;case 9:if(void 0!==t.AccesMessage){let e=t.AccesMessage.message??"(none)";throw t.AccesMessage.titre&&(e+=`${t.AccesMessage.titre} ${e}`),new c(e)}}return t},ue=(e,s)=>{const n=e.AvecDiscussion??!1,t=n&&!e.discussionInterdit,i=t&&(e.AvecDiscussionPersonnels??!1),a=t&&(e.AvecDiscussionParents??!1),r=t&&(e.AvecDiscussionEleves??!1),o=t&&(e.AvecDiscussionProfesseurs??!1),c=[];if(s.length>0){const e=s=>{"G"in s&&c.push(s.G),"Onglet"in s&&s.Onglet.forEach(e)};s.forEach(e)}return{canReadDiscussions:n,canDiscuss:t,canDiscussWithStaff:i,canDiscussWithParents:a,canDiscussWithStudents:r,canDiscussWithTeachers:o,hasAdvancedDiscussionEditor:e.AvecDiscussionAvancee??!1,maxAssignmentFileUploadSize:e.tailleMaxRenduTafEleve,tabs:c}},le=(e,s,n={})=>{const t=e.L??"",i=e.G,a=e.N;let r;if(i===P.Link)r=e.url??t;else{const{iv:e,key:i}=Y(s),o=JSON.stringify({N:a,Actif:!0,...n}),c=z.encrypt(o,i,e);r=`${s.information.url}/FichiersExternes/${c}/${encodeURIComponent(t)}?Session=${s.information.id}`}return{kind:i,name:t,url:r,id:a}},de=(e,s)=>{const n=e=>s.find((s=>s.id===e)),t=e.periodeParDefaut&&n(e.periodeParDefaut.V.N),i=e.listePeriodes.V.map((e=>n(e.N))).filter(Boolean);return{defaultPeriod:t,location:e.G,periods:i}},pe=(e,s)=>{let n;switch(s.information.accountKind){case S.STUDENT:case S.TEACHER:n=[e.ressource];break;case S.PARENT:n=e.ressource.listeRessources}return{id:e.ressource.N,kind:e.ressource.G,name:e.ressource.L,resources:n.map((e=>((e,s)=>{let n=null;e.avecPhoto&&(n=le({G:1,N:e.N,L:"photo.jpg"},s));const t=new Map;for(const n of e.listeOngletsPourPeriodes?.V??[])t.set(n.G,de(n,s.instance.periods));return{id:e.N,kind:e.G,name:e.L,establishmentName:e.Etablissement.V.L,className:e.classeDEleve?.L,profilePicture:n,tabs:t,isDirector:e.estDirecteur??!1,isDelegate:e.estDelegue??!1,isMemberCA:e.estMembreCA??!1}})(e,s))),authorizations:ue(e.autorisations,e.listeOnglets)}},me=e=>{const s=e.split(".");switch(s.pop(),s.pop()){case"eleve":return S.STUDENT;case"parent":return S.PARENT;case"professeur":return S.TEACHER;default:throw new E("decodeAccountKindFromPath")}},he={fd:1,login:!0},fe=async(e,s)=>{const n=i(s.url);e.information=await Q({base:n,kind:s.kind,cookies:[],params:{...he,bydlg:"A6ABB224-12DD-4E31-AD3E-8A39A1C2C335"}},e.fetcher),e.instance=await re(e,s.navigatorIdentifier);const t=await oe(e,{username:s.username,deviceUUID:s.deviceUUID,requestFirstMobileAuthentication:!0,reuseMobileAuthentication:!1,requestFromQRCode:!1,useCAS:!1});we(s,"password",t);const a=be(t,s.username,s.password),r=Ae(e,t,a),o=await ce(e,r);return Ee(e,o,a),ve(o)?Ce(e,{token:o.jetonConnexionAppliMobile,username:t.login??s.username,deviceUUID:s.deviceUUID}):ye(e,o,t,s.username)},ge=async(e,s)=>{const n=i(s.url);e.information=await Q({base:n,kind:s.kind,cookies:["appliMobile=1"],params:he},e.fetcher),e.instance=await re(e,s.navigatorIdentifier);const t=await oe(e,{username:s.username,deviceUUID:s.deviceUUID,requestFirstMobileAuthentication:!1,reuseMobileAuthentication:!0,requestFromQRCode:!1,useCAS:!1});we(s,"token",t);const a=be(t,s.username,s.token),r=Ae(e,t,a),o=await ce(e,r);if(Ee(e,o,a),ve(o))throw new h(o,t,s.username);return ye(e,o,t,s.username)},De=async(e,s)=>{const t=(e=>{const s=e.url,n=s.lastIndexOf("/")+1,t=s.substring(0,n-1),i=s.substring(n);return{kind:me(i),url:t,token:e.jeton,username:e.login}})(s.qr),i=n.util.createBuffer(s.pin),a=e=>z.decrypt(n.util.encodeUtf8(t[e]),i,n.util.createBuffer()),r={username:a("username"),token:a("token")};e.information=await Q({base:t.url,kind:t.kind,cookies:["appliMobile=1"],params:he},e.fetcher),e.instance=await re(e,s.navigatorIdentifier);const o=await oe(e,{username:r.username,deviceUUID:s.deviceUUID,requestFirstMobileAuthentication:!0,reuseMobileAuthentication:!1,requestFromQRCode:!0,useCAS:!1});we(r,"token",o);const c=be(o,r.username,r.token),u=Ae(e,o,c),l=await ce(e,u);return Ee(e,l,c),ve(l)?Ce(e,{token:l.jetonConnexionAppliMobile,username:o.login??r.username,deviceUUID:s.deviceUUID}):ye(e,l,o,r.username)},Ce=(e,s)=>ge(e,{url:e.information.url,kind:e.information.accountKind,username:s.username,token:s.token,deviceUUID:s.deviceUUID,navigatorIdentifier:e.instance.navigatorIdentifier}),be=(e,s,t)=>{const i=n.md.sha256.create().update(e.alea??"").update(n.util.encodeUtf8(t)).digest().toHex().toUpperCase();return n.util.createBuffer(s+i)},we=(e,s,n)=>{1===n.modeCompLog&&(e.username=e.username.toLowerCase()),1===n.modeCompMdp&&(e[s]=e[s].toLowerCase())},Ae=(e,s,t)=>{const i=n.util.createBuffer(e.information.aesIV);try{const e=n.util.decodeUtf8(z.decrypt(s.challenge,t,i)),a=new Array(e.length);for(let s=0;s<e.length;s+=1)s%2==0&&a.push(e.charAt(s));const r=n.util.encodeUtf8(a.join(""));return z.encrypt(r,t,i)}catch{throw new o}},Ee=(e,s,t)=>{const i=n.util.createBuffer(e.information.aesIV),a=z.decrypt(s.cle,t,i).split(",").map((e=>String.fromCharCode(parseInt(e)))).join("");e.information.aesKey=a},ve=e=>Boolean(e.actionsDoubleAuth),ye=async(e,s,n,t)=>(e.user=await(async e=>{const s=new Z(e,"ParametresUtilisateur",{}),n=await s.send();return pe(n.data.donnees,e)})(e),{token:s.jetonConnexionAppliMobile,username:n.login??t,kind:e.information.accountKind,url:e.information.url,navigatorIdentifier:e.instance.navigatorIdentifier}),Se=(e,s,n)=>{e.kind===j.TextInput||e.kind===j.InformationText?e.textInputAnswer=s:(e.selectedAnswers=s,e.textInputAnswer=n),e.answered=void 0!==s,e.answerDate=e.answered?new Date:void 0},Me=(e,s,{withSuperposedCanceledClasses:n=!1,withCanceledClasses:t=s.withCanceledClasses,withPlannedClasses:i=!0})=>{const a=s.classes;if(!t)for(const e of a)"lesson"===e.is&&e.canceled&&(e._visible=!1);if(!i)for(const e of a)"lesson"===e.is&&!1!==e._visible&&!e.canceled&&[0,3,4].includes(e.kind)&&(e._visible=!1);if(t&&!n){let s=!0;for(;s;)s=Ne(e,a)}s.classes=a.filter((e=>!1!==e._visible));for(const e of a)delete e._visible},Ve=(e,s)=>{const n=e.instance.blocksPerDay,t=Math.floor(s.blockPosition/n);let i=s.blockPosition+s.blockLength-1;return Math.floor(i/n)!==t&&(i=t*n+n-1),i},Pe=(e,s,n,t)=>{const i=[n],a=s.blockPosition,r=Ve(e,s);for(let e=a;e<=r;e++){const s=t[e];void 0!==s&&(s===n||i.includes(s)||i.push(s))}return i},Ne=(e,s)=>{const n={};for(let t=0;t<s.length;t++){const i=s[t];i.weekNumber in n||(n[i.weekNumber]=[]);const a=n[i.weekNumber],r=i.blockPosition,o=Ve(e,i);if(!1!==i._visible)for(let n=r;n<=o;n++){if(void 0!==a[n]){const n=Pe(e,i,t,a);let r=!1,o=!1;for(let e=0;e<n.length;e++){const t=s[n[e]];o||(o=!("lesson"===t.is&&t.canceled)),r||(r="lesson"===t.is&&t.canceled)}if(o&&r)for(let e=0;e<n.length;e++){const t=s[n[e]];if(t&&"lesson"===t.is&&t.canceled)return t._visible=!1,!0}break}a[n]=t}}return!1},Ie=async e=>{const s=new Z(e,"Presence",{_Signature_:{onglet:K.Presence}});await s.send()},Le=(e,s=12e4)=>{Te(e),e.presence=setInterval((()=>Ie(e)),s)},Te=e=>{e.presence&&(clearInterval(e.presence),e.presence=null)},_e=class{queue=[];pendingPromise=!1;push(e){return new Promise(((s,n)=>{this.queue.push({promise:e,resolve:s,reject:n}),this.pendingPromise||this.dequeue()}))}dequeue(){if(this.pendingPromise)return!1;const e=this.queue.shift();return!!e&&(this.pendingPromise=!0,e.promise().then((s=>{e.resolve(s),this.pendingPromise=!1,this.dequeue()})).catch((s=>{e.reject(s),this.pendingPromise=!1,this.dequeue()})),!0)}},Re=(e=s)=>({information:null,instance:null,user:null,queue:new _e,fetcher:e,presence:null}),ke=e=>e.getTime()+60*e.getTimezoneOffset()*1e3,xe=e=>new Date(ke(e)),Oe=(e,s)=>{const n=Math.floor((ke(e)-ke(s))/864e5);return 1+Math.floor(n/7)},Fe=async e=>{const s=new Z(e,"PageInfosPerso",{_Signature_:{onglet:K.Account}});return((e,s)=>{const n=e.Informations;let t;return s.instance.version[0]>=2024&&(t=e.iCal?.liste.V[0]?.paramICal),{address:[n.adresse1,n.adresse2,n.adresse3,n.adresse4],postalCode:n.codePostal,province:n.province,country:n.pays,city:n.ville,email:n.eMail,phone:`+${n.indicatifTel}${n.telephonePortable}`,INE:n.numeroINE,iCalToken:t}})((await s.send()).data.donnees,e)},Ue=async(e,s)=>{const n=new Z(e,"SaisieTAFARendreEleve",{_Signature_:{onglet:K.Assignments},donnees:{listeFichiers:[{E:U.DELETION,TAF:{N:s}}]}});await n.send()},Ge=async(e,s,n)=>{const t=new Z(e,"SaisieTAFFaitEleve",{_Signature_:{onglet:K.Assignments},donnees:{listeTAF:[{E:U.MODIFICATION,TAFFait:n,N:s}]}});await t.send()},Be=-1e3,je=()=>Be-=1,qe=class{constructor(e,s,n,t){this.session=e,this.functionName=s,this.fileName=t,e.information.order++;const{iv:i,key:a}=Y(e);this.order=z.encrypt(e.information.order.toString(),a,i);const r=new FormData;r.append("numeroOrdre",this.order),r.append("numeroSession",e.information.id.toString()),r.append("nomRequete",s),r.append("idFichier",this.id),r.append("md5",""),r.append("files[]",n,t),this.form=r,this.url=e.information.url+`/uploadfilesession/${e.information.accountKind}/${e.information.id}`,this.headers["Content-Disposition"]=`attachment; filename="${encodeURI(t)}"`}order;id=`selecfile_1_${Date.now()}`;url;form;headers={};async send(){const e=await new Response(this.form).text();this.headers["Content-Type"]=`multipart/form-data; boundary=${e.split("\n")[0].slice(2)}`;let s=3;for(;3===s;){const n=await this.session.fetcher({url:new URL(this.url),method:"POST",content:e,headers:this.headers});s=JSON.parse(n.content).etat}if(this.session.information.order++,0===s||2===s)throw new y}},$e=async(e,s,n,t)=>{const i=n.size||n.byteLength,a=e.user.authorizations.maxAssignmentFileUploadSize;if("number"==typeof i&&i>a)throw new v(a);const r=new qe(e,"SaisieTAFARendreEleve",n,t);await r.send();const o=new Z(e,"SaisieTAFARendreEleve",{_Signature_:{onglet:K.Assignments},donnees:{listeFichiers:[{E:U.CREATION,G:R.FILE,L:t,N:je(),idFichier:r.id,TAF:{N:s}}]}});await o.send()},He=e=>({id:e.N,name:e.L,inGroups:e.estServiceGroupe??!1}),Je=e=>({id:e.N,name:e.L,subject:He(e.Matiere.V)}),Ke=(e,s)=>({id:e.N,subject:He(e.Matiere.V),description:e.descriptif.V,backgroundColor:e.CouleurFond,done:e.TAFFait,deadline:te(e.PourLe.V),attachments:e.ListePieceJointe.V.map((e=>le(e,s))),difficulty:e.niveauDifficulte,length:e.duree,themes:e.ListeThemes.V.map((e=>Je(e))),return:{kind:e.genreRendu??V.None,canUpload:e.peuRendre??!1,uploaded:e.documentRendu&&le(e.documentRendu.V,s)},resourceID:e.cahierDeTextes?.V.N}),Qe=async(e,s,n,t)=>{const i=new Z(e,"PageCahierDeTexte",{_Signature_:{onglet:s},donnees:{domaine:{_T:8,V:"number"==typeof t?`[${n}..${t}]`:`[${n}]`}}});return(await i.send()).data.donnees},ze=async(e,s,n,t)=>{n=xe(n),t=xe(t);const i=Oe(n,e.instance.firstMonday),a=Oe(t,e.instance.firstMonday);return Qe(e,s,i,a)},Ye=(e,s)=>s.ListeTravauxAFaire.V.map((s=>Ke(s,e))),We=async(e,s,n)=>{const t=await Qe(e,K.Assignments,s,n);return Ye(e,t)},Ze=async(e,s,n)=>{const t=await ze(e,K.Assignments,s,n);return Ye(e,t).filter((e=>s<=e.deadline&&e.deadline<=n))},Xe=async(e,s,n)=>{let t;switch(s){case N.brouillon:t={commande:s,brouillon:"number"==typeof n.id?{E:U.CREATION,N:n.id}:{E:U.MODIFICATION,N:n.id},contenu:n.content,messagePourReponse:{G:0,N:n.replyMessageID},listeDestinataires:[],listeFichiers:[],objet:""};break;case"":t={commande:s,bouton:{N:0,G:n.button},brouillon:{N:n.id},contenu:n.content,listeDestinataires:[],listeFichiers:[],messagePourReponse:{G:0,N:n.replyMessageID}};break;default:t={commande:s,listePossessionsMessages:n.possessions}}const i=new Z(e,"SaisieMessage",{_Signature_:{onglet:K.Discussions},donnees:t});await i.send()},es=e=>({id:e.N,name:e.L,kind:e.G}),ss=async(e,s={_:[]})=>{const n=new Z(e,"ListeMessagerie",{_Signature_:{onglet:K.Discussions},donnees:{avecLu:!0,avecMessage:!0,possessionMessageDiscussionUnique:null}}),t=(await n.send()).data.donnees,i=t.listeEtiquettes.V.map(es),a=t.listeMessagerie.V.filter((e=>{const s=0===(e.profondeur||0),n=e.messagePourParticipants?.V.N;return e.estUneDiscussion&&n&&s})).map((e=>((e,s,n)=>({cache:n,creator:e.initiateur,dateAsFrenchText:e.libelleDate,recipientName:e.public,participantsMessageID:e.messagePourParticipants.V.N,possessions:e.listePossessionsMessages.V,numberOfDrafts:e.nbBrouillons??0,subject:e.objet??"",numberOfMessages:e.nombreMessages??0,numberOfMessagesUnread:e.nbNonLus??0,closed:e.ferme??!1,folders:e.listeEtiquettes?.V.map((e=>s.find((s=>s.id===e.N)))).filter(Boolean)??[]}))(e,i,s)));s._.length=0,s._.push(...a);for(const e of s._)e.participantsMessageID in s?Object.assign(s[e.participantsMessageID],e):s[e.participantsMessageID]=e;for(const e in s)"_"!==e&&(s._.find((s=>s.participantsMessageID===e))||delete s[e]);return{folders:i,items:s._}},ns=e=>{const s=e.estHTML??!1;return{possessionID:e.possessionMessage.V.N,replyMessageID:e.messageSource.V.N,content:s?e.contenu.V:e.contenu,isHTML:s}},ts=e=>{let s;switch(e){case"Professeur":s=F.Teacher;break;case"Personnel":s=F.Personal;break;default:s=F.Student}return s},is=(e,s)=>{let n,t;return"Moi"!==e.public_gauche&&(n={name:e.public_gauche,kind:ts(e.hint_gauche)}),"Moi"===e.public_droite?t=void 0:"string"==typeof e.public_droite&&(t={name:e.public_droite,kind:ts(e.hint_droite)}),{id:e.N,content:e.estHTML?e.contenu.V:e.contenu,creationDate:te(e.date.V),author:n,receiver:t,partialVisibility:e.estUnAparte,amountOfRecipients:(e.nbPublic??1)+1,files:e.listeDocumentsJoints?.V.map((e=>le(e,s)))??[]}},as=(e,s,n)=>{const t=[],i=e.messageSource.V.N;if(e.listeMessagesPourContexte)for(const n of e.listeMessagesPourContexte.V){const e=is(n,s);t.push(e)}let a=n.find((e=>e.id===i));return{...is(e,s),transferredMessages:t,replyMessageID:i,replyingTo:a}},rs=async(e,s,n=!1)=>{const t=new Z(e,"ListeMessages",{_Signature_:{onglet:K.Discussions},donnees:{listePossessionsMessages:s.possessions,marquerCommeLu:n,nbMessagesVus:0}}),i=((e,s)=>{const n=e.brouillon,t=[],i=[],a=e.messagePourReponse.V.N;for(const n of e.listeMessages.V)n.brouillon?i.push(ns(n)):t.push(as(n,s,t));if(t.sort(((e,s)=>s.creationDate.getTime()-e.creationDate.getTime())),n){const e=n.V.estHTML??!1;i.push({isHTML:e,content:e?n.V.contenu:n.V.contenu.V,possessionID:n.V.N,replyMessageID:a})}const r=e.listeBoutons.V.find((e=>e.L.startsWith("Envoyer")))?.G;return{sents:t,drafts:i,defaultReplyMessageID:a,sendAction:r,canIncludeStudentsAndParents:r===L.ReplyEveryoneExceptParentsAndStudents||r===L.SendEveryoneExceptParentsAndStudents}})((await t.send()).data.donnees,e);return s.messages?Object.assign(s.messages,i):s.messages=i,i},os=async(e,s,n,t=s.messages?.defaultReplyMessageID)=>{await Xe(e,N.brouillon,{id:je(),content:n,replyMessageID:t}),await ss(e,s.cache),await rs(e,s)},cs=async(e,s)=>{await Xe(e,N.Delete,{possessions:s.possessions}),await ss(e,s.cache)},us=async(e,s)=>{await rs(e,s,!0)},ls=e=>({id:e.N,name:e.L,kind:e.G,disallowMessages:e.refusMess??!1}),ds=async(e,s)=>{const n=new Z(e,"SaisiePublicMessage",{_Signature_:{onglet:K.Discussions},donnees:{message:{N:s.participantsMessageID},estPublicParticipant:!0,estDestinatairesReponse:!1}});return(await n.send()).data.donnees.listeDest.V.map(ls)},ps=async(e,s,n)=>{await Xe(e,N.brouillon,{id:n.possessionID,content:n.content,replyMessageID:n.replyMessageID}),await ss(e,s.cache),await rs(e,s)},ms=async(e,s,n)=>{await Xe(e,N.Delete,{possessions:[{N:n.possessionID}]}),await ss(e,s.cache),await rs(e,s)},hs=async(e,s)=>{await Xe(e,N.Restore,{possessions:s.possessions}),await ss(e,s.cache)},fs=(e,s)=>(e===L.SendEveryoneExceptParentsAndStudents&&s&&(e=L.SendEveryone),e===L.ReplyEveryoneExceptParentsAndStudents&&s&&(e=L.ReplyEveryone),e),gs=async(e,s,n,t=!1)=>{if(void 0===s.messages?.sendAction)throw new d;await Xe(e,"",{button:fs(s.messages.sendAction,t),content:n.content,id:n.possessionID,replyMessageID:n.replyMessageID}),await ss(e,s.cache),await rs(e,s)},Ds=async(e,s,n,t=!1,i=s.messages?.defaultReplyMessageID)=>{if(!s.messages)throw new p;if(void 0===s.messages.sendAction)throw new d;const a=fs(s.messages.sendAction,t),r=new Z(e,"SaisieMessage",{donnees:{contenu:e.user.authorizations.hasAdvancedDiscussionEditor?{_T:21,V:n}:n,bouton:{N:0,G:a},brouillon:{N:je(),E:U.CREATION},genreDiscussion:0,messagePourReponse:{G:0,N:i},listeFichiers:[]},_Signature_:{onglet:K.Discussions}});await r.send(),await ss(e,s.cache),await rs(e,s)},Cs=async(e,s)=>{await Xe(e,N.Trash,{possessions:s.possessions}),await ss(e,s.cache)},bs=e=>({id:e.N,level:e.L,abbreviation:e.abbreviation,coefficient:e.coefficient,domainID:e.domaine.V.N,domainName:e.domaine.V.L,itemID:e.item?.V.N,itemName:e.item?.V.L,order:e.ordre,pillarID:e.pilier.V.N,pillarName:e.pilier.V.L,pillarPrefixes:e.pilier.V.strPrefixes.split(",").map((e=>e.trim()))}),ws=e=>{const s=e.listeNiveauxDAcquisitions.V.map(bs);return s.sort(((e,s)=>e.order-s.order)),{skills:s,name:e.L,id:e.N,teacher:e.individu.V.L,coefficient:e.coefficient,description:e.descriptif,subject:He(e.matiere.V),levels:e.listePaliers.V.map((e=>e.L)),date:te(e.date.V)}},As=e=>({N:e.id,G:e.kind,L:e.name}),Es=async(e,s)=>{const n=new Z(e,"DernieresEvaluations",{_Signature_:{onglet:K.Evaluations},donnees:{periode:As(s)}});return(await n.send()).data.donnees.listeEvaluations.V.map(ws)},vs=e=>e*Math.PI/180,ys=e=>(e=>e*e)(Math.sin(e/2)),Ss=(e,s)=>{const n=vs(e[0]),t=vs(s[0]),i=vs(e[1]),a=vs(s[1]),r=ys(t-n)+Math.cos(n)*Math.cos(t)*ys(a-i);return 12756274*Math.asin(Math.sqrt(r))},Ms=async(e,n=s)=>{const t=`data={"nomFonction":"geoLoc","lat":"${e.latitude}","long":"${e.longitude}"}`,i=await n({url:new URL("https://www.index-education.com/swie/geoloc.php"),method:"POST",content:t,headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"}});if("{}"===i.content)return[];const a=JSON.parse(i.content).map((s=>((e,s)=>{const n=parseFloat(e.lat),t=parseFloat(e.long);return{url:e.url.toLowerCase(),name:e.nomEtab.trim().replace("COLLEGE","COLLÈGE").replace("LYCEE","LYCÉE"),latitude:n,longitude:t,postalCode:parseInt(e.cp),distance:Ss(s,[n,t])}})(s,[e.latitude,e.longitude])));return a.sort(((e,s)=>e.distance>s.distance?1:e.distance<s.distance?-1:e.name>s.name?1:e.name<s.name?-1:0)),a},Vs=async(e,s)=>{const n=new Z(e,"GenerationPDF",{donnees:{avecCodeCompetences:!1,genreGenerationPDF:2,options:{adapterHauteurService:!1,desEleves:!1,gererRectoVerso:!1,hauteurServiceMax:15,hauteurServiceMin:10,piedMonobloc:!0,portrait:!0,taillePolice:6.5,taillePoliceMin:5,taillePolicePied:6.5,taillePolicePiedMin:5},periode:As(s)},_Signature_:{onglet:K.Gradebook}}),t=await n.send();return e.information.url+"/"+encodeURI(t.data.donnees.url.V)},Ps=e=>{let s,n=G.Grade;if("string"==typeof e)e.split("|").length>=2&&(n=parseInt(e.split("|")[1])),s=parseFloat(e.replace(",",".")),n!==G.AbsentZero&&n!==G.UnreturnedZero||(s=0);else{if("number"!=typeof e)throw new E("decodeGradeValue");s=e}return{kind:n,points:s}},Ns=e=>({student:e.moyEleve&&Ps(e.moyEleve.V),outOf:e.baremeMoyEleve&&Ps(e.baremeMoyEleve.V),defaultOutOf:e.baremeMoyEleveParDefaut&&Ps(e.baremeMoyEleveParDefaut.V),class_average:Ps(e.moyClasse.V),min:Ps(e.moyMin.V),max:Ps(e.moyMax.V),subject:He(e),backgroundColor:e.couleur}),Is=(e,s)=>({grades:e.listeDevoirs.V.map((e=>((e,s)=>{const n=e.N,t=e.estBonus,i=(t,i)=>e[t]&&le({G:P.File,L:e[t],N:n},s,{G:i});return{id:n,value:Ps(e.note.V),outOf:Ps(e.bareme.V),defaultOutOf:Ps(e.baremeParDefaut.V),date:te(e.date.V),subject:He(e.service.V),average:e.moyenne&&Ps(e.moyenne.V),max:Ps(e.noteMax.V),min:Ps(e.noteMin.V),coefficient:e.coefficient,comment:e.commentaire,commentaireSurNote:e.commentaireSurNote,isBonus:t,isOptional:e.estFacultatif&&!t,isOutOf20:e.estRamenerSur20,subjectFile:i("libelleSujet","DevoirSujet"),correctionFile:i("libelleCorrige","DevoirCorrige")}})(e,s))),subjectsAverages:e.listeServices.V.map(Ns),classAverage:e.moyGeneraleClasse&&Ps(e.moyGeneraleClasse.V),overallAverage:e.moyGenerale&&Ps(e.moyGenerale.V)}),Ls=async(e,s)=>{const n=new Z(e,"DernieresNotes",{_Signature_:{onglet:K.Grades},donnees:{Periode:As(s)}}),t=await n.send();return Is(t.data.donnees,e)},Ts=e=>`${e.getDate()}/${e.getMonth()+1}/${e.getFullYear()} ${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}`,_s=e=>({description:e.commentaire,name:e.L,url:e.url}),Rs=e=>({name:e.libellePorteMonnaie,description:e.hintPorteMonnaie,warning:e.avecWarning,balance:parseInt(e.valeurSolde.replace(",",".")),balanceDescription:e.hintSolde}),ks=e=>({sso:e.SSO}),xs=e=>{const s=[];let n,t;var i;"partenaireARD"in e&&(i=e.partenaireARD,t={...ks(i),canRefreshData:i.avecActualisation,wallets:i.porteMonnaie.V.map(Rs)});for(const t of e.lienUtile.listeLiens.V)"SSO"in t?"TURBOSELF"===t.SSO.codePartenaire&&(n=ks(t)):s.push(_s(t));return{partnerARD:t,partnerTurboself:n,links:s}},Os=async(e,s=e.instance.nextBusinessDay)=>{const n=Oe(s,e.instance.firstMonday),t=Ts(s),i=new Z(e,"PageAccueil",{_Signature_:{onglet:K.Presence},donnees:{avecConseilDeClasse:!0,dateGrille:{_T:7,V:t},numeroSemaine:n,coursNonAssures:{numeroSemaine:n},personnelsAbsents:{numeroSemaine:n},incidents:{numeroSemaine:n},exclusions:{numeroSemaine:n},donneesVS:{numeroSemaine:n},registreAppel:{date:{_T:7,V:t}},previsionnelAbsServiceAnnexe:{date:{_T:7,V:t}},donneesProfs:{numeroSemaine:n},EDT:{numeroSemaine:n},TAFARendre:{date:{_T:7,V:t}},TAFEtActivites:{date:{_T:7,V:t}},partenaireCDI:{CDI:{}},tableauDeBord:{date:{_T:7,V:t}},modificationsEDT:{date:{_T:7,V:t}}}}),a=await i.send();return xs(a.data.donnees)},Fs=async(e,n=s)=>{e=i(e),e+="/infoMobileApp.json?id=0D264427-EEFC-4810-A9E9-346942A862A4";const t={url:new URL(e)},a=await n(t);return(e=>{let s,n;return e.CAS.actif&&(s=e.CAS.casURL,n=e.CAS.jetonCAS),{name:e.nomEtab,version:e.version,date:new Date(e.date),accounts:e.espaces.map((e=>({name:e.nom,path:e.URL}))),casURL:s,casToken:n}})(JSON.parse(a.content))},Us=e=>({name:e.L,color:e.couleur}),Gs=e=>({name:e.L,color:e.couleur}),Bs=e=>({name:e.L,allergens:e.listeAllergenesAlimentaire.V.map(Us),labels:e.listeLabelsAlimentaires.V.map(Gs)}),js=e=>{let s=e.ListeRepas.V.reduce(((e,s)=>{let n;switch(s.G){case B.Lunch:n="lunch";break;case B.Dinner:n="dinner";break;default:throw new E("decodeMenu")}return e[n]=(e=>{const s=e.ListePlats.V.reduce(((e,s)=>{let n;switch(s.G){case T.Entry:n="entry";break;case T.Main:n="main";break;case T.Side:n="side";break;case T.Drink:n="drink";break;case T.Fromage:n="fromage";break;case T.Dessert:n="dessert";break;default:throw new E("decodeMeal")}return e[n]=s.ListeAliments.V.map(Bs),e}),{});return{name:e.L,...s}})(s),e}),{});return{date:te(e.Date.V),...s}},qs=async(e,s=new Date)=>{const n=new Z(e,"PageMenus",{_Signature_:{onglet:K.Menus},donnees:{date:{_T:7,V:Ts(s)}}}),t=await n.send();return{containsLunch:(i=t.data.donnees).AvecRepasMidi,containsDinner:i.AvecRepasSoir,days:i.ListeJours.V.map(js),weeks:m(i.DomaineDePresence.V),allergens:i.ListeAllergenes.V.map(Us),labels:i.Listelabels.V.map(Gs)};var i},$s=e=>({id:e.N,name:e.L,from:e.libelleMatiere}),Hs=(e,s)=>({id:e.N,name:e.L,sub:s}),Js=e=>{const s=[];if(e.listeRessources){const n=e.listeRessources.V.filter((e=>e.estUneSousMatiere)).map($s);for(const t of e.listeRessources.V)t.estUneSousMatiere||s.push(Hs(t,n.filter((e=>e.from===t.L))))}return{id:e.N,name:e.L,kind:e.G,subjects:s,function:e.fonction&&(n=e.fonction.V,{id:n.N,name:n.L}),isPrincipal:e.estPrincipal??!1};var n},Ks=async(e,s,n)=>{const t=new Z(e,"ListeRessourcesPourCommunication",{_Signature_:{onglet:K.Discussions},donnees:{filtreElement:{G:s.kind,L:s.name,N:s.id},onglet:{N:0,G:n}}});return(await t.send()).data.donnees.listeRessourcesPourCommunication.V.filter((e=>e.avecDiscussion)).map(Js)},Qs=async(e,s,n,t)=>{const i=new Z(e,"SaisieMessage",{_Signature_:{onglet:K.Discussions},donnees:{contenu:e.user.authorizations.hasAdvancedDiscussionEditor?{_T:21,V:n}:n,objet:s,estCreationCarnetLiaison:!1,listeFichiers:[],listeDestinataires:t.map((e=>({E:U.MODIFICATION,G:e.kind,N:e.id})))}});await i.send()},zs=e=>{if(0===e.length)return"[]";const s=[...e].sort(((e,s)=>e-s)),n=[];let t=s[0],i=t;for(let e=1;e<s.length;e++)s[e]-t!=1&&(i===t?n.push(i.toString()):n.push(`${i}..${t}`),i=s[e]),t=s[e];return i===t?n.push(i.toString()):n.push(`${i}..${t}`),`[${n.join(",")}]`},Ys=async(e,s,n={delete:!1,markAsRead:!0,onlyMarkAsRead:!1})=>{const t=n.onlyMarkAsRead||n.delete?[]:"information"===s.is?[s.question]:s.questions,i=new Z(e,"SaisieActualites",{_Signature_:{onglet:K.News},donnees:{listeActualites:[{N:s.id,L:s.title??"",genrePublic:s.public.G,public:s.public,validationDirecte:!0,listeQuestions:t.map((e=>({N:e.id,L:e.fullTitle,genreReponse:e.kind,reponse:{N:parseInt(e.answerID),Actif:!0,valeurReponse:e.kind===j.InformationText||e.kind===j.TextInput?e.textInputAnswer??"":{_T:8,V:zs(e.selectedAnswers??[])},valeurReponseLibre:e.choices.filter((e=>e.isTextInput)).length>0?e.textInputAnswer:void 0,avecReponse:e.answered,estReponseAttendue:e.shouldAnswer,_validationSaisie:!0}}))),marqueLueSeulement:!n.delete&&n.onlyMarkAsRead,lue:!n.delete&&n.markAsRead,supprimee:!n.onlyMarkAsRead&&n.delete,saisieActualite:!1}],saisieActualite:!1}});await i.send()},Ws=async(e,s)=>{await Ys(e,s,{onlyMarkAsRead:!1,markAsRead:!1,delete:!0})},Zs=async(e,s,n)=>{s.read!==n&&(await Ys(e,s,{onlyMarkAsRead:!0,markAsRead:n,delete:!1}),s.read=n)},Xs=async(e,s,n=!0)=>{if(!s.needToAcknowledge||s.acknowledged)return Zs(e,s,n);Se(s.question,""),await Ys(e,s,{markAsRead:n,onlyMarkAsRead:!1,delete:!1}),n&&(s.read=!0)},en=async(e,s,n=!0)=>{await Ys(e,s,{markAsRead:n,onlyMarkAsRead:!1,delete:!1}),n&&(s.read=!0)},sn=(e,s)=>({id:e.N,title:e.L,category:s.find((s=>s.id===e.categorie.V.N)),creationDate:te(e.dateCreation.V),startDate:te(e.dateDebut.V),endDate:te(e.dateFin.V),author:e.auteur,public:e.public.V,read:e.lue}),nn=e=>({value:e.L,position:e.rang,isTextInput:!!e.estReponseLibre}),tn=(e,s)=>{const n=e.genreReponse,t=e.reponse.V.avecReponse;let i,a;return t&&e.reponse.V.valeurReponse&&("string"==typeof e.reponse.V.valeurReponse?a=e.reponse.V.valeurReponse:(i=m(e.reponse.V.valeurReponse.V),a=e.reponse.V.valeurReponseLibre)),{id:e.N,fullTitle:e.L,title:e.titre,position:e.rang,kind:n,maximumLength:e.tailleReponse,shouldRespectMaximumChoices:e.avecMaximum,maximumChoices:e.nombreReponsesMax,content:e.texte.V,attachments:e.listePiecesJointes.V.map((e=>le(e,s))),answerID:e.reponse.V.N,answered:t,shouldAnswer:e.reponse.V.estReponseAttendue,answerDate:e.reponse.V.reponduLe?.V&&te(e.reponse.V.reponduLe.V),choices:n===j.TextInput?[]:e.listeChoix.V.map(nn),selectedAnswers:i,textInputAnswer:a}},an=(e,s,n)=>({is:"information",...sn(e,n),question:tn(e.listeQuestions.V[0],s),get attachments(){return this.question.attachments},get acknowledged(){return this.question.answered},get acknowledgedDate(){return this.question.answerDate},get needToAcknowledge(){return this.question.shouldAnswer},get content(){return this.question.content}}),rn=e=>({id:e.N,name:e.L,default:e.estDefaut??!1}),on=(e,s,n)=>({is:"survey",...sn(e,n),questions:e.listeQuestions.V.map((e=>tn(e,s))),isAnonymous:e.reponseAnonyme}),cn=async e=>{const s=new Z(e,"PageActualites",{_Signature_:{onglet:K.News},donnees:{modesAffActus:{_T:26,V:zs([0])}}});return((e,s)=>{const n=e.listeCategories.V.map(rn);return{categories:n,items:e.listeModesAff[0].listeActualites.V.map((e=>{let t;if(e.estInformation)t=an;else{if(!e.estSondage)throw new E("decodeNews");t=on}return t(e,s,n)}))}})((await s.send()).data.donnees,e)},un=e=>{const[s,n]=e.NbrHeures.split("h").map(Number),t=e.estMotifNonEncoreConnu;return{id:e.name,startDate:te(e.dateDebut.V),endDate:te(e.dateFin.V),justified:e.justifie,opened:e.ouverte,hoursMissed:s,minutesMissed:n,daysMissed:e.NbrJours,shouldParentsJustify:e.aJustifierParParents,administrativelyFixed:e.reglee,isReasonUnknown:t,reason:!t&&e.listeMotifs.V[0].L}},ln=e=>{const s=e.estMotifNonEncoreConnu,n=e.justifie;return{id:e.N,date:te(e.date.V),minutes:e.duree,justified:n,justification:n&&e.justification,shouldParentsJustify:e.aJustifierParParents,administrativelyFixed:e.reglee,isReasonUnknown:s,reason:!s&&e.listeMotifs.V[0].L}},dn=(e,s)=>({id:e.N,title:e.nature.V.L,reasons:e.listeMotifs.V.map((e=>e.L)),exclusion:e.estUneExclusion,isDuringLesson:!e.horsCours,workToDo:e.travailAFaire,workToDoDocuments:e.documentsTAF.V.map((e=>le(e,s))),circumstances:e.circonstances,circumstancesDocuments:e.documentsCirconstances.V.map((e=>le(e,s))),giver:e.demandeur.V.L,dateGiven:te(e.dateDemande.V),durationMinutes:e.duree}),pn=e=>{let s;return"L"in e.matiere.V&&"0"!==e.matiere.V.N&&(s=He(e.matiere.V)),{id:e.N,date:te(e.date.V),opened:e.estLue,shouldParentsJustify:e.avecARObservation,name:e.L,kind:e.genreObservation,sectionID:e.rubrique.V.N,subject:s,reason:e.commentaire}},mn=(e,s)=>({id:e.N,title:e.nature.V.L,comments:e.commentaire,reasons:e.listeMotifs.V.map((e=>e.L)),exclusion:e.estUneExclusion,circumstances:e.circonstances,circumstancesDocuments:e.documentsCirconstances.V.map((e=>le(e,s))),decisionMaker:e.decideur.V.L,giver:e.demandeur.V.L,dateGiven:te(e.dateDemande.V),startDate:te(e.dateDebut.V),endDate:te(e.dateFin.V),disallowedAccesses:m(e.interditAcces.V)}),hn=async(e,s)=>{const n=new Z(e,"PagePresence",{_Signature_:{onglet:K.Notebook},donnees:{periode:As(s),DateDebut:{_T:7,V:Ts(s.startDate)},DateFin:{_T:7,V:Ts(s.endDate)}}});return((e,s)=>{const n=[],t=[],i=[],a=[],r=[];for(const o of e.listeAbsences.V)switch(o.G){case 13:n.push(un(o));break;case 14:t.push(ln(o));break;case 41:i.push(dn(o,s));break;case 46:a.push(pn(o));break;case 72:r.push(mn(o,s))}return{absences:n,delays:t,punishments:i,observations:a,precautionaryMeasures:r}})((await n.send()).data.donnees,e)},fn=async(e,s)=>{const n=new Z(e,"SaisieURLPartenaire",{_Signature_:{onglet:K.Presence},donnees:{SSO:s.sso}});return(await n.send()).data.RapportSaisie.urlSSO.V},gn=async(e,s)=>{const n=new Z(e,"donneesContenusCDT",{_Signature_:{onglet:K.Resources},donnees:{pourTAF:!0,cahierDeTextes:{N:s}}});return(await n.send()).data.donnees.ListeCahierDeTextes.V[0].ListeTravailAFaire.V.map((s=>Ke(s,e)))},Dn=(e,s)=>({id:e.N,startDate:te(e.Date.V),endDate:te(e.DateFin.V),subject:He(e.Matiere.V),haveAssignment:void 0!==e.dateTAF,assignmentDeadline:e.dateTAF?.V&&te(e.dateTAF.V),teachers:e.listeProfesseurs.V.map((e=>e.L)),groups:e.listeGroupes.V.map((e=>e.L)),backgroundColor:e.CouleurFond,contents:e.listeContenus.V.map((e=>((e,s)=>({id:e.N,title:e.L,description:e.descriptif.V,category:e.categorie.V.G,files:e.ListePieceJointe.V.map((e=>le(e,s))),themes:e.ListeThemes.V.map((e=>Je(e))),educativeValue:e.parcoursEducatif}))(e,s)))}),Cn=async(e,s)=>{const n=new Z(e,"donneesContenusCDT",{_Signature_:{onglet:K.Resources},donnees:{cahierDeTextes:{N:s}}}),t=(await n.send()).data.donnees.ListeCahierDeTextes.V[0];return Dn(t,e)},bn=(e,s)=>s.ListeCahierDeTextes.V.map((s=>Dn(s,e))),wn=async(e,s,n)=>{const t=await Qe(e,K.Resources,s,n);return bn(e,t)},An=async(e,s,n)=>{const t=await ze(e,K.Resources,s,n);return bn(e,t).filter((e=>s<=e.endDate&&e.endDate<=n))},En=async(e,s)=>{const n=Y(e),t=new Z(e,"SecurisationCompteDoubleAuth",{donnees:{action:O.csch_VerifierMotDePassePersonnalise,nouveauMDP:z.encrypt(s,n.key,n.iv)}});return(await t.send()).data.donnees.result},vn=async(e,s)=>{const n=Y(e),t=new Z(e,"SecurisationCompteDoubleAuth",{donnees:{action:O.csch_VerifierPIN,codePin:z.encrypt(s,n.key,n.iv)}});return(await t.send()).data.donnees.result},yn=async(e,s,n)=>{const t={action:O.csch_EnregistrerChoixUtilisateur},i=Y(e);"number"==typeof n.mode&&(t.mode=n.mode),n.password&&(t.nouveauMDP=z.encrypt(n.password,i.key,i.iv)),n.pin&&(t.codePin=z.encrypt(n.pin,i.key,i.iv)),n.deviceName&&(t.avecIdentification=!0,t.strIdentification=n.deviceName);const a=new Z(e,"SecurisationCompteDoubleAuth",{donnees:t}),r=(await a.send()).data.donnees.jetonConnexionAppliMobile;r&&(s.context.authentication.jetonConnexionAppliMobile=r)},Sn=async(e,s)=>{if(s.length>30)throw new f(30);const n=new Z(e,"SecurisationCompteDoubleAuth",{donnees:{action:O.csch_LibellesSourceConnexionDejaConnus,libelle:s}});return(await n.send()).data.donnees.dejaConnu},Mn=(e,s)=>({[e]:s,[e[0].toUpperCase()+e.substring(1)]:s}),Vn=(e,s)=>{const n=te(e.DateDuCours.V),t=e.place,i=e.duree;let a;if("string"==typeof e.DateDuCoursFin?.V)a=te(e.DateDuCoursFin.V);else{const e=(({instance:{endings:e}},s)=>{s>e.length&&(s%=e.length-1);const n=e[s],[t,i]=n.split("h").map(Number);return{hours:t,minutes:i}})(s,t%s.instance.blocksPerDay+i-1);a=new Date(n),a.setHours(e.hours,e.minutes)}return{id:e.N,backgroundColor:e.CouleurFond,notes:e.memo,startDate:n,endDate:a,blockLength:i,blockPosition:t,weekNumber:Oe(n,s.instance.firstMonday)}},Pn=(e,s)=>({absences:e.absences,withCanceledClasses:e.avecCoursAnnule??!0,classes:(e.ListeCours??[]).map((e=>(e=>"estSortiePedagogique"in e&&e.estSortiePedagogique)(e)?((e,s)=>({is:"activity",...Vn(e,s),title:e.motif,attendants:e.accompagnateurs,resourceTypeName:e.strGenreRess,resourceValue:e.strRess}))(e,s):(e=>"estRetenue"in e&&void 0!==e.estRetenue)(e)?((e,s)=>{let n;const t=[],i=[],a=[];if("ListeContenus"in e)for(const s of e.ListeContenus.V){const e=s.L;if(s.estHoraire)n=e;else if("G"in s)switch(s.G){case 3:i.push(e);break;case 34:t.push(e);break;case 17:a.push(e)}}return{is:"detention",...Vn(e,s),title:n,personalNames:t,teacherNames:i,classrooms:a}})(e,s):((e,s)=>{const n=[],t=[],i=[],a=[],r=[];let o,c;if(e.listeVisios)for(const s of e.listeVisios.V)n.push(s.url);if(e.ListeContenus)for(const s of e.ListeContenus.V)switch(s.G){case 16:o=He(s);break;case 3:t.push(s.L);break;case 34:i.push(s.L);break;case 17:a.push(s.L);break;case 2:r.push(s.L)}return e.AvecCdT&&e.cahierDeTextes&&(c=e.cahierDeTextes.V.N),{is:"lesson",...Vn(e,s),kind:e.G,status:e.Statut,canceled:e.estAnnule??!1,exempted:e.dispenseEleve??!1,test:e.cahierDeTextes?.V.estDevoir??!1,virtualClassrooms:n,personalNames:i,teacherNames:t,classrooms:a,groupNames:r,subject:o,lessonResourceID:c}})(e,s))).sort(((e,s)=>e.startDate.getTime()-s.startDate.getTime()))}),Nn=async(e,s,n={})=>{const t=new Z(e,"PageEmploiDuTemps",{_Signature_:{onglet:K.Timetable},donnees:{estEDTAnnuel:!1,estEDTPermanence:!1,avecAbsencesEleve:!1,avecRessourcesLibrePiedHoraire:!1,avecAbsencesRessource:!0,avecInfosPrefsGrille:!0,avecConseilDeClasse:!0,avecCoursSortiePeda:!0,avecDisponibilites:!0,avecRetenuesEleve:!0,edt:{G:16,L:"Emploi du temps"},...Mn("ressource",(i=e.user.resources[s],{G:i.kind,L:i.name,N:i.id})),...n}});var i;const a=await t.send();return Pn(a.data.donnees,e)},In=async(e,s,n=0)=>Nn(e,n,Mn("numeroSemaine",s)),Ln=async(e,s,n,t=0)=>Nn(e,t,{...Mn("dateDebut",{_T:7,V:Ts(s)}),...n&&Mn("dateFin",{_T:7,V:Ts(n)})});export{u as AccessDeniedError,l as AccountDisabledError,S as AccountKind,M as AssignmentDifficulty,V as AssignmentReturnKind,P as AttachmentKind,c as AuthenticateError,o a