@studentsphere/ots-provider-wigor 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,656 @@
1
+ import * as crypto from "node:crypto";
2
+ import { BaseTimetableProvider, } from "@studentsphere/ots-core";
3
+ import axios from "axios";
4
+ import { wrapper } from "axios-cookiejar-support";
5
+ import * as cheerio from "cheerio";
6
+ import pLimit from "p-limit";
7
+ import { CookieJar } from "tough-cookie";
8
+ const LOGIN_SERVER = "https://cas-p.wigorservices.net/cas/login";
9
+ const CD_SCHOOLS = [
10
+ "3a",
11
+ "epsi",
12
+ "esail",
13
+ "icl",
14
+ "idrac-business-school",
15
+ "ieft",
16
+ "iet",
17
+ "ifag",
18
+ "igefi",
19
+ "ihedrea",
20
+ "ileri",
21
+ "sup-de-com",
22
+ "viva-mundi",
23
+ "wis",
24
+ ];
25
+ const IGENSIA_SCHOOLS = [
26
+ "american-business-college",
27
+ "business-science-institute",
28
+ "cnva",
29
+ "ecm",
30
+ "emi",
31
+ "esa",
32
+ "esam",
33
+ "icd-business-school",
34
+ "igensia-rh",
35
+ "imis",
36
+ "imsi",
37
+ "ipi",
38
+ "iscpa",
39
+ "ismm",
40
+ ];
41
+ const getScheduleServer = (schoolId) => {
42
+ if (schoolId && CD_SCHOOLS.includes(schoolId)) {
43
+ return "https://ws-edt-cd.wigorservices.net/WebPsDyn.aspx";
44
+ }
45
+ if (schoolId && IGENSIA_SCHOOLS.includes(schoolId)) {
46
+ return "https://ws-edt-igs.wigorservices.net/WebPsDyn.aspx";
47
+ }
48
+ return "https://ws-edt-igs.wigorservices.net/WebPsDyn.aspx";
49
+ };
50
+ const FRENCH_MONTHS = {
51
+ Janvier: 1,
52
+ Février: 2,
53
+ Mars: 3,
54
+ Avril: 4,
55
+ Mai: 5,
56
+ Juin: 6,
57
+ Juillet: 7,
58
+ Août: 8,
59
+ Septembre: 9,
60
+ Octobre: 10,
61
+ Novembre: 11,
62
+ Décembre: 12,
63
+ };
64
+ const FRENCH_DAYS = {
65
+ Lundi: 1,
66
+ Mardi: 2,
67
+ Mercredi: 3,
68
+ Jeudi: 4,
69
+ Vendredi: 5,
70
+ Samedi: 6,
71
+ Dimanche: 0,
72
+ };
73
+ const WEEK_DAYS = [
74
+ "Sunday",
75
+ "Monday",
76
+ "Tuesday",
77
+ "Wednesday",
78
+ "Thursday",
79
+ "Friday",
80
+ "Saturday",
81
+ ];
82
+ export class WigorProvider extends BaseTimetableProvider {
83
+ get id() {
84
+ return "wigor";
85
+ }
86
+ get name() {
87
+ return "Wigor";
88
+ }
89
+ get logo() {
90
+ return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAA1CAYAAADh5qNwAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIvSURBVHgB7Zm/SgNBEMZXCSRoCBaJWAQMxCo2Cip2Wltrrz6JDyDYCLa+g2ArgpUWNiaVwQipTAoJMUQQlDHZsH/mLpfdFZwwv+puMnc3385+e5tk5uzm4FtMGbNiCmFRVGBRVGBRVGBRVGBRVGBRVGBRVEgJB3ZWDsV6cU+LXdwdic+vDyt3f+1EFBcqo/N6+15cPZ1aebnMojjePtdij81rcft8KSbFqVPN95oVUwtXKWRLRt5qorzBc6rCBUdR9sOwYiGWTs1psXRqHhVQzm8gz7EHLwlOomCatboNoRe1aeUVssvo9VhXTaFwf2w6J8F5oTBHMZcp/HZBpZzfQq81BwD8ZIpy7RIQTBRgFotNMyyOda7efhCueIiyfaUWi/lJAh1VPYiJMqf3JDiLgvluClM7FbUaSlS/mYsMzAJXPwFeL99W91U7V30VtXRL5ACAn+A6/b4N4YOXKGzey2LHd6oUmefjJ8CzUw0rBkViXTJzpa9C+wnwEoX5KqpQbLuDDYCvnwDvDS32vqos7WqxTv9tWGxPi8NUDe0nILgowCxU5sBmVgV7j/n6CfAWNdjO9GJzpKgkuwTXTayKt6jBPvAlNkcWOq5gn62RSpAviXHFgJ86/dbwuDU6xu/j3yXgz0WZn8UV/s86VY30lS2qFnufEAT7jSLKV2ahUatbqC4BwURhxap+ksDCgvnKXO59mOE/sonAoqjAoqjAoqjAoqjAoqjAoqjAoqjwAxN68XM4/01cAAAAAElFTkSuQmCC";
91
+ }
92
+ get schools() {
93
+ return [
94
+ {
95
+ id: "3a",
96
+ name: "3A",
97
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/3a.png",
98
+ },
99
+ {
100
+ id: "american-business-college",
101
+ name: "American Business College",
102
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/american_business_college.png",
103
+ },
104
+ {
105
+ id: "business-science-institute",
106
+ name: "Business Science Institute",
107
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/business_science_institute.png",
108
+ },
109
+ {
110
+ id: "cnva",
111
+ name: "CNVA",
112
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/cnva.png",
113
+ },
114
+ {
115
+ id: "ecm",
116
+ name: "ECM",
117
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ecm.png",
118
+ },
119
+ {
120
+ id: "emi",
121
+ name: "EMI",
122
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/emi.png",
123
+ },
124
+ {
125
+ id: "epsi",
126
+ name: "EPSI",
127
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/epsi.png",
128
+ },
129
+ {
130
+ id: "esa",
131
+ name: "ESA",
132
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/esa.png",
133
+ },
134
+ {
135
+ id: "esail",
136
+ name: "ESAIL",
137
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/esail.png",
138
+ },
139
+ {
140
+ id: "esam",
141
+ name: "ESAM",
142
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/esam.png",
143
+ },
144
+ {
145
+ id: "icd-business-school",
146
+ name: "ICD Business School",
147
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/icd_business_school.png",
148
+ },
149
+ {
150
+ id: "icl",
151
+ name: "ICL",
152
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/icl.png",
153
+ },
154
+ {
155
+ id: "idrac-business-school",
156
+ name: "IDRAC Business School",
157
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/idrac_business_school.png",
158
+ },
159
+ {
160
+ id: "ieft",
161
+ name: "IEFT",
162
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ieft.png",
163
+ },
164
+ {
165
+ id: "iet",
166
+ name: "IET",
167
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/iet.png",
168
+ },
169
+ {
170
+ id: "ifag",
171
+ name: "IFAG",
172
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ifag.png",
173
+ },
174
+ {
175
+ id: "igefi",
176
+ name: "IGEFI",
177
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/igefi.png",
178
+ },
179
+ {
180
+ id: "igensia-rh",
181
+ name: "IGENSIA RH",
182
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/igensia_rh.png",
183
+ },
184
+ {
185
+ id: "ihedrea",
186
+ name: "IHEDREA",
187
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ihedrea.png",
188
+ },
189
+ {
190
+ id: "ileri",
191
+ name: "ILERI",
192
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ileri.png",
193
+ },
194
+ {
195
+ id: "imis",
196
+ name: "IMIS",
197
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/imis.png",
198
+ },
199
+ {
200
+ id: "imsi",
201
+ name: "IMSI",
202
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/imsi.png",
203
+ },
204
+ {
205
+ id: "ipi",
206
+ name: "IPI",
207
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ipi.png",
208
+ },
209
+ {
210
+ id: "iscpa",
211
+ name: "ISCPA",
212
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/iscpa.png",
213
+ },
214
+ {
215
+ id: "ismm",
216
+ name: "ISMM",
217
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/ismm.png",
218
+ },
219
+ {
220
+ id: "sup-de-com",
221
+ name: "SUP DE COM",
222
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/sup_de_com.png",
223
+ },
224
+ {
225
+ id: "viva-mundi",
226
+ name: "Viva Mundi",
227
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/viva_mundi.png",
228
+ },
229
+ {
230
+ id: "wis",
231
+ name: "WIS",
232
+ logo: "https://raw.githubusercontent.com/kaelianbaudelet/WSPS/main/public/schools/wis.png",
233
+ },
234
+ ];
235
+ }
236
+ async validateCredentials(credentials) {
237
+ try {
238
+ const isCasAvailable = await this.checkCasAvailability(LOGIN_SERVER);
239
+ if (!isCasAvailable) {
240
+ return false;
241
+ }
242
+ const jar = new CookieJar();
243
+ const client = wrapper(axios.create({ jar, withCredentials: true }));
244
+ const getRes = await client.get(LOGIN_SERVER, {
245
+ params: { service: "" },
246
+ headers: { "User-Agent": "nodejs-client", Accept: "text/html" },
247
+ });
248
+ const hidden = await this.extractHiddenFields(getRes.data);
249
+ const form = new URLSearchParams();
250
+ form.append("username", credentials.identifier);
251
+ form.append("password", credentials.password || "");
252
+ for (const [k, v] of Object.entries(hidden)) {
253
+ if (k !== "username" && k !== "password")
254
+ form.append(k, v);
255
+ }
256
+ if (!form.get("_eventId"))
257
+ form.append("_eventId", "submit");
258
+ const postRes = await client.post(LOGIN_SERVER, form.toString(), {
259
+ headers: {
260
+ "Content-Type": "application/x-www-form-urlencoded",
261
+ "User-Agent": "nodejs-client",
262
+ Accept: "text/html",
263
+ },
264
+ maxRedirects: 0,
265
+ validateStatus: () => true,
266
+ });
267
+ if (postRes.status >= 300 && postRes.status < 400) {
268
+ }
269
+ if (postRes.status === 200) {
270
+ // Check if we are actually logged in (CAS usually shows a specific page or redirects)
271
+ if (postRes.data.includes("success") ||
272
+ postRes.data.includes("Log Out") ||
273
+ postRes.data.includes("Vous êtes connecté")) {
274
+ return true;
275
+ }
276
+ // Note: CAS might return 200 on failure with an error message in the HTML
277
+ if (postRes.data.includes("incorrect") ||
278
+ postRes.data.includes("erreur")) {
279
+ return false;
280
+ }
281
+ // If it's a 200 and no error message, it might be a success depending on the CAS config
282
+ return true;
283
+ }
284
+ return false;
285
+ }
286
+ catch (err) {
287
+ console.error(`[Wigor] Error during validation:`, err);
288
+ return false;
289
+ }
290
+ }
291
+ async getSchedule(credentials, from, to) {
292
+ const isCasAvailable = await this.checkCasAvailability(LOGIN_SERVER);
293
+ if (!isCasAvailable) {
294
+ throw new Error("CAS server unavailable");
295
+ }
296
+ const query = {
297
+ action: "posEDTLMS",
298
+ serverID: "C",
299
+ hashURL: "3771E093EFD5A0DB1204B280BBC7F09097D3A41521007FAEB9EAC5AD8905F07DBB230E9FFE9D3A6BF40B157D22E842F91708A3D7950855E83F70CF9A8A4A1CF8",
300
+ Tel: credentials.identifier,
301
+ };
302
+ const limit = pLimit(10);
303
+ const allEvents = [];
304
+ const effectiveStart = from;
305
+ const effectiveEnd = to;
306
+ let currentMonday = this.getMonday(effectiveStart);
307
+ const endDateObj = effectiveEnd;
308
+ const endFriday = this.addDays(this.getMonday(endDateObj), 4);
309
+ const weeks = [];
310
+ while (currentMonday <= endFriday) {
311
+ const mondayStr = `${(currentMonday.getUTCMonth() + 1)
312
+ .toString()
313
+ .padStart(2, "0")}/${currentMonday
314
+ .getUTCDate()
315
+ .toString()
316
+ .padStart(2, "0")}/${currentMonday.getUTCFullYear()}`;
317
+ weeks.push(mondayStr);
318
+ currentMonday = this.addDays(currentMonday, 7);
319
+ }
320
+ const scheduleServer = getScheduleServer(credentials.schoolId);
321
+ const promises = weeks.map((mondayStr) => limit(async () => {
322
+ const client = await this.createClient(LOGIN_SERVER, credentials);
323
+ let valid = false;
324
+ let events = [];
325
+ for (let attempt = 1; attempt <= 3 && !valid; attempt++) {
326
+ try {
327
+ const html = await this.fetchEDTHtml(client, scheduleServer, {
328
+ ...query,
329
+ date: mondayStr,
330
+ });
331
+ events = this.parseEdtHtml(html, mondayStr);
332
+ valid = this.areEventsValid(events);
333
+ }
334
+ catch (_err) {
335
+ console.warn(`[Wigor] Failed to fetch/parse week ${mondayStr} (Attempt ${attempt})`);
336
+ }
337
+ }
338
+ return valid ? events : [];
339
+ }));
340
+ const results = await Promise.allSettled(promises);
341
+ for (const result of results) {
342
+ if (result.status === "fulfilled") {
343
+ allEvents.push(...result.value);
344
+ }
345
+ }
346
+ return allEvents.map((event) => ({
347
+ hash: event.hash,
348
+ subject: event.title,
349
+ start: new Date(event.startTime),
350
+ end: new Date(event.endTime),
351
+ location: event.classroom || event.campus || "Inconnu",
352
+ teacher: event.instructor,
353
+ color: event.color,
354
+ }));
355
+ }
356
+ // Helper methods
357
+ async checkCasAvailability(loginServer) {
358
+ try {
359
+ const response = await axios.head(loginServer, {
360
+ headers: { "User-Agent": "nodejs-client", Accept: "text/html" },
361
+ validateStatus: (status) => status === 200,
362
+ });
363
+ return response.status === 200;
364
+ }
365
+ catch (_err) {
366
+ return false;
367
+ }
368
+ }
369
+ async extractHiddenFields(html) {
370
+ const $ = cheerio.load(html);
371
+ const fields = {};
372
+ $('input[type="hidden"]').each((_, el) => {
373
+ const name = $(el).attr("name");
374
+ const value = $(el).attr("value") ?? "";
375
+ if (name) {
376
+ fields[name] = value;
377
+ }
378
+ });
379
+ return fields;
380
+ }
381
+ async createClient(loginServer, credentials) {
382
+ const jar = new CookieJar();
383
+ const client = wrapper(axios.create({ jar, withCredentials: true }));
384
+ const getRes = await client.get(loginServer, {
385
+ params: { service: "" },
386
+ headers: { "User-Agent": "nodejs-client", Accept: "text/html" },
387
+ });
388
+ const hidden = await this.extractHiddenFields(getRes.data);
389
+ const form = new URLSearchParams();
390
+ form.append("username", credentials.identifier);
391
+ form.append("password", credentials.password || "");
392
+ for (const [k, v] of Object.entries(hidden)) {
393
+ if (k !== "username" && k !== "password")
394
+ form.append(k, v);
395
+ }
396
+ if (!form.get("_eventId"))
397
+ form.append("_eventId", "submit");
398
+ await client.post(loginServer, form.toString(), {
399
+ headers: {
400
+ "Content-Type": "application/x-www-form-urlencoded",
401
+ "User-Agent": "nodejs-client",
402
+ Accept: "text/html",
403
+ },
404
+ maxRedirects: 0,
405
+ validateStatus: (s) => s >= 200 && s < 400,
406
+ });
407
+ return client;
408
+ }
409
+ isErrorPage(html) {
410
+ return (html.includes("<title>Error 500</title>") ||
411
+ html.includes("<h1>500</h1>") ||
412
+ html.includes("Unexpected Error"));
413
+ }
414
+ async fetchEDTHtml(client, scheduleServer, query, maxRetries = 3) {
415
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
416
+ try {
417
+ const params = new URLSearchParams(query).toString();
418
+ const url = `${scheduleServer}?${params}`;
419
+ const res = await client.get(url, {
420
+ headers: { "User-Agent": "nodejs-client", Accept: "text/html" },
421
+ });
422
+ const html = res.data;
423
+ if (!this.isErrorPage(html)) {
424
+ return html;
425
+ }
426
+ }
427
+ catch (_err) {
428
+ // Ignore error and retry
429
+ }
430
+ if (attempt < maxRetries) {
431
+ await new Promise((resolve) => setTimeout(resolve, 1000));
432
+ }
433
+ }
434
+ throw new Error("Failed to fetch EDT");
435
+ }
436
+ capitalizeName(name) {
437
+ return name
438
+ .split(" ")
439
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
440
+ .join(" ");
441
+ }
442
+ parseFrenchDate(dayText, baseYear, queryDateObj) {
443
+ const parts = dayText.trim().split(/\s+/);
444
+ if (parts.length < 3)
445
+ throw new Error("Invalid date format");
446
+ const dayName = parts[0];
447
+ if (!dayName || !(dayName in FRENCH_DAYS))
448
+ throw new Error("Invalid day name");
449
+ const dayNumStr = parts[1];
450
+ if (!dayNumStr)
451
+ throw new Error("Missing day number");
452
+ const dayNum = parseInt(dayNumStr, 10);
453
+ if (Number.isNaN(dayNum))
454
+ throw new Error("Invalid day number");
455
+ const monthNameRaw = parts[2];
456
+ if (!monthNameRaw)
457
+ throw new Error("Missing month name");
458
+ const monthName = monthNameRaw.charAt(0).toUpperCase() +
459
+ monthNameRaw.slice(1).toLowerCase();
460
+ const month = FRENCH_MONTHS[monthName];
461
+ if (!month)
462
+ throw new Error("Invalid month name");
463
+ const weekday = FRENCH_DAYS[dayName];
464
+ let bestDate = null;
465
+ let minDiff = Infinity;
466
+ for (const y of [baseYear - 1, baseYear, baseYear + 1]) {
467
+ const d = new Date(Date.UTC(y, month - 1, dayNum));
468
+ if (d.getUTCDay() === weekday) {
469
+ const diff = Math.abs(d.getTime() - queryDateObj.getTime());
470
+ if (diff < minDiff) {
471
+ minDiff = diff;
472
+ bestDate = d;
473
+ }
474
+ }
475
+ }
476
+ if (!bestDate)
477
+ throw new Error("No matching date found");
478
+ const iso = bestDate.toISOString();
479
+ const datePart = iso.split("T")[0];
480
+ if (!datePart)
481
+ throw new Error("Invalid ISO date format");
482
+ return datePart;
483
+ }
484
+ getMonday(date) {
485
+ const d = new Date(date);
486
+ const day = d.getDay();
487
+ const diff = (day === 0 ? -6 : 1) - day;
488
+ d.setDate(d.getDate() + diff);
489
+ return d;
490
+ }
491
+ addDays(date, days) {
492
+ const d = new Date(date);
493
+ d.setDate(d.getDate() + days);
494
+ return d;
495
+ }
496
+ calculateDuration(startTime, endTime, date) {
497
+ const start = new Date(`${date}T${startTime}:00Z`);
498
+ const end = new Date(`${date}T${endTime}:00Z`);
499
+ return (end.getTime() - start.getTime()) / (1000 * 60);
500
+ }
501
+ parseEdtHtml(html, queryDate) {
502
+ const $ = cheerio.load(html);
503
+ const events = [];
504
+ const queryParts = queryDate.split("/");
505
+ if (queryParts.length !== 3)
506
+ throw new Error("Invalid query date format");
507
+ const baseYearStr = queryParts[2];
508
+ if (!baseYearStr)
509
+ throw new Error("Missing year in query date");
510
+ const baseYear = parseInt(baseYearStr, 10);
511
+ if (Number.isNaN(baseYear))
512
+ throw new Error("Invalid year in query date");
513
+ const monthStr = queryParts[0];
514
+ const dayStr = queryParts[1];
515
+ if (!monthStr || !dayStr)
516
+ throw new Error("Missing month or day in query date");
517
+ const month = parseInt(monthStr, 10);
518
+ const day = parseInt(dayStr, 10);
519
+ if (Number.isNaN(month) || Number.isNaN(day))
520
+ throw new Error("Invalid month or day in query date");
521
+ const queryDateObj = new Date(Date.UTC(baseYear, month - 1, day));
522
+ const dayMap = new Map();
523
+ $(".Jour").each((_, el) => {
524
+ const $el = $(el);
525
+ const style = $el.attr("style") || "";
526
+ const leftMatch = style.match(/left:([\d.]+)%/);
527
+ if (!leftMatch || !leftMatch[1]) {
528
+ return;
529
+ }
530
+ const left = parseFloat(leftMatch[1]);
531
+ if (left < 100 || left >= 200) {
532
+ return;
533
+ }
534
+ const dayText = $el.find(".TCJour").text().trim();
535
+ try {
536
+ const parsedDate = this.parseFrenchDate(dayText, baseYear, queryDateObj);
537
+ dayMap.set(left, parsedDate);
538
+ }
539
+ catch (_err) {
540
+ // Skip invalid days
541
+ }
542
+ });
543
+ const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b);
544
+ $(".Case").each((_, element) => {
545
+ const $case = $(element);
546
+ const style = $case.attr("style") || "";
547
+ const leftMatch = style.match(/left:([\d.]+)%/);
548
+ if (!leftMatch || !leftMatch[1]) {
549
+ return;
550
+ }
551
+ const caseLeft = parseFloat(leftMatch[1]);
552
+ if (caseLeft < 100 || caseLeft >= 200) {
553
+ return;
554
+ }
555
+ const dayLeft = sortedDays.filter((l) => l <= caseLeft).pop();
556
+ if (dayLeft === undefined) {
557
+ return;
558
+ }
559
+ const eventDate = dayMap.get(dayLeft);
560
+ if (!eventDate) {
561
+ return;
562
+ }
563
+ const time = $case.find(".TChdeb").text().trim().split(" - ");
564
+ if (time.length !== 2 || !time[0] || !time[1]) {
565
+ return;
566
+ }
567
+ const profContents = $case
568
+ .find(".TCProf")
569
+ .contents()
570
+ .filter(function () {
571
+ return this.type === "text" && $(this).text().trim() !== "";
572
+ })
573
+ .map(function () {
574
+ return $(this).text().trim();
575
+ })
576
+ .get();
577
+ const classroomInfo = $case.find(".TCSalle").text().trim();
578
+ const courseName = $case
579
+ .find("td.TCase")
580
+ .contents()
581
+ .filter(function () {
582
+ return this.type === "text" && $(this).text().trim() !== "";
583
+ })
584
+ .text()
585
+ .trim();
586
+ const borderColor = $case
587
+ .find(".innerCase")
588
+ .attr("style")
589
+ ?.match(/border:3px solid\s*([^;]+)/)?.[1] || "";
590
+ if (!courseName) {
591
+ return;
592
+ }
593
+ const specParts = profContents[1] ? profContents[1].split(" - ") : [];
594
+ let classroom = classroomInfo.replace("Salle:", "").split("(")[0]?.trim() || null;
595
+ let campus = classroomInfo.match(/\(([^)]+)\)/)?.[1] || null;
596
+ let sessionType = "in_person";
597
+ if (classroomInfo.includes("(DISTANCIEL)") ||
598
+ classroomInfo.includes("Aucune")) {
599
+ classroom = null;
600
+ campus = null;
601
+ if (classroomInfo.includes("(DISTANCIEL)"))
602
+ sessionType = "remote";
603
+ }
604
+ const dateObj = new Date(eventDate);
605
+ if (Number.isNaN(dateObj.getTime()))
606
+ throw new Error("Invalid event date");
607
+ const weekDay = WEEK_DAYS[dateObj.getUTCDay()];
608
+ if (!weekDay)
609
+ throw new Error("Invalid weekday");
610
+ const startTime = `${eventDate}T${time[0]}:00`;
611
+ const endTime = `${eventDate}T${time[1]}:00`;
612
+ const instructor = profContents[0]
613
+ ? this.capitalizeName(profContents[0])
614
+ : "";
615
+ // Generate stable hash from content
616
+ // We use a combination of stable fields to ensure the same course gives the same hash
617
+ const hashContent = `${courseName}|${startTime}|${endTime}|${classroom}|${instructor}`;
618
+ const hash = crypto
619
+ .createHash("sha256")
620
+ .update(hashContent)
621
+ .digest("hex");
622
+ const event = {
623
+ title: courseName.replace(/(\n|\t|\s\s+)/g, " ").trim(),
624
+ instructor,
625
+ program: specParts[1]?.trim() || "",
626
+ startTime,
627
+ endTime,
628
+ duration: this.calculateDuration(time[0], time[1], eventDate),
629
+ weekDay,
630
+ classroom,
631
+ campus: campus || "Arras",
632
+ deliveryMode: sessionType,
633
+ color: borderColor || "#808080",
634
+ classGroup: specParts[0]?.trim() || "",
635
+ hash,
636
+ };
637
+ events.push(event);
638
+ });
639
+ return events;
640
+ }
641
+ areEventsValid(events) {
642
+ return events.every((event) => {
643
+ return (event.title &&
644
+ event.title.trim() !== "" &&
645
+ event.instructor &&
646
+ event.instructor.trim() !== "" &&
647
+ event.startTime &&
648
+ event.startTime.trim() !== "" &&
649
+ event.endTime &&
650
+ event.endTime.trim() !== "" &&
651
+ event.weekDay &&
652
+ event.weekDay.trim() !== "");
653
+ });
654
+ }
655
+ }
656
+ //# sourceMappingURL=index.js.map