-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbase.js
More file actions
598 lines (559 loc) · 16.9 KB
/
Copy pathbase.js
File metadata and controls
598 lines (559 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// ==UserScript==
// @name CELCAT to .ics
// @namespace http://tampermonkey.net/
// @version 1.2
// @description This is a custom browser script that converts CELCAT calendar data into iCalendar (.ics) format that can be exported and used in other schedule management applications.
// @homepageURL https://github.com/kotomax24/CELCAT-to-.ics
// @updateURL https://raw.githubusercontent.com/kotomax24/CELCAT-to-.ics/main/base.js
// @downloadURL https://raw.githubusercontent.com/kotomax24/CELCAT-to-.ics/main/base.js
// @author Kotomax24
// @match https://edt.univ-tlse3.fr/calendar2/*
// @grant
// ==/UserScript==
/**
* conver a json object to a HTML element
* @param data json object to convert to html
* @returns HTMLElement from the json object
*/
function jsonToHTML(data) {
const element = document.createElement(data.elementType)
for (let [key, object] of Object.entries(data)){
if (object == undefined) continue
switch (key) {
case "elementType":
break
case "content":
element.appendChild(document.createTextNode(object))
break
case "class":
element.classList.add(...object)
break
case "childs":
object.forEach(child => {
if (child == undefined) return
element.appendChild(jsonToHTML(child))
})
break
case "events":
for (let [event, callback] of Object.entries(object)){
element.addEventListener(event, callback)
}
break
default:
element.setAttribute(key, object)
break
}
}
return element
}
function filterClick(name) {
return (event) => {
if (event.target.classList.contains("modal")) {
hideDialog(name)
}
}
}
const selectedLanguage = document.querySelector('#requestCulture_RequestCulture_UICulture_Name').value;
const messages = {
'en-US': {
exportButtonLabel: 'Export',
errorDialogTitle: 'Error',
errorDialogMessage: 'An error occurred.',
okButtonLabel: 'Ok',
cancelButtonLabel: 'Cancel',
notConnectedMessage: 'You must be connected to use this script',
},
'fr-FR': {
exportButtonLabel: 'Exporter',
errorDialogTitle: 'Erreur',
errorDialogMessage: 'Une erreur s\'est produite.',
okButtonLabel: 'Ok',
cancelButtonLabel: 'Annuler',
notConnectedMessage: 'Vous devez être connecté pour utiliser ce script',
},
'en-GB': {
exportButtonLabel: 'Export',
errorDialogTitle: 'Error',
errorDialogMessage: 'An error occurred.',
okButtonLabel: 'Ok',
cancelButtonLabel: 'Cancel',
notConnectedMessage: 'You must be connected to use this script',
}
};
/**
* show a dialog with the given name
* @param name name of the dialog to show
*/
function showDialog(name) {
const dialog = document.getElementById(`customDialog-${name}`);
document.body.classList.add("modal-open");
document.body.appendChild(modalFadeIn);
dialog.style.display = "block";
dialog.style.paddingLeft = "0px";
setTimeout(() => {
dialog.classList.add("in");
document.querySelector(`#customDialog-${name} .btn-default`).style.display = "none";
}, 200);
}
function dialogShowEvent(name) {
return () => {
showDialog(name)
}
}
/**
* hide a dialog with the given name
* @param name name of the dialog to hide
*/
function hideDialog(name) {
// GM_log(`Hiding dialog ${name}`)
const dialog = document.getElementById(`customDialog-${name}`)
dialog.classList.remove("in")
modalFadeIn.classList.remove("in")
setTimeout(() => {
dialog.style.display = "none"
document.body.classList.remove("modal-open")
document.body.removeChild(modalFadeIn)
modalFadeIn.classList.add("in")
}, 200)
}
function dialogHideEvent(name) {
return () => {
hideDialog(name)
}
}
/**
* Generate a new dialog with all the appropriate styles, events and animations and add it to the page
*
* @param name name of the dialog to create
* @param title title to display in the dialog header
* @param description description which is displayer above the dialog content
* @param dataValidation function to call when the user click on the validation button
* @param jsonHTMLContent dialog body content
* @returns HTMLElement the created dialog
*/
function buildDialog(name, title, description, dataValidation, jsonHTMLContent) {
const dialog = jsonToHTML({
elementType: "div",
class: ["modal", "fade"],
tabindex: -1,
role: "dialog",
"aria-labelledby": "eventFilterModalLabel",
id: `customDialog-${name}`,
events: {
"click": filterClick(name)
},
childs: [
{
elementType: "div",
class: ["modal-dialog"],
role: "document",
childs: [
{
elementType: "div",
class: ["modal-content"],
childs: [
{
elementType: "div",
class: ["modal-header"],
childs: [
{
elementType: "button",
class: ["close"],
type: "button",
"data-dismiss": "modal",
"aria-label": "Close",
events: {
"click": dialogHideEvent(name)
},
childs: [
{
elementType: "span",
"aria-hidden": "true",
content: "×"
}
]
},
{
elementType: "h4",
class: ["modal-title"],
content: title
}
]
},
{
elementType: "div",
class: ["modal-body"],
childs: [
{
elementType: "p",
content: description
},
jsonHTMLContent
]
},
{
elementType: "div",
class: ["modal-footer"],
childs: [
{
elementType: "button",
class: ["btn", "btn-default"],
type: "button",
"data-dismiss": "modal",
content: selectedLanguage === 'fr-FR' ? "Exporter" : "Export",
events: {
"click": () => {
if (!dataValidation()) return
hideDialog(name)
}
}
},
{
elementType: "button",
class: ["btn", "btn-default"],
type: "button",
"data-dismiss": "modal",
content: selectedLanguage === 'fr-FR' ? "Annuler" : "Cancel",
events: {
"click": dialogHideEvent(name)
}
}
]
}
]
}
]
}
]
})
document.getElementById("mainContentDiv").appendChild(dialog)
return dialog
}
const mainDialog = buildDialog(
"mainDialog",
selectedLanguage === 'fr-FR' ? "Exporter en .ics" : "Export to .ics",
selectedLanguage === 'fr-FR' ? "Sélectionner les dates de l'export que vous voulez faire." : "Select the export dates you want to use.",
exportData,
{
elementType: "form",
role: "form",
events: {
"submit": (event) => {
event.preventDefault()
return false
}
},
childs: [
{
elementType: "div",
class: ["form-group"],
childs: [
{
elementType: "label",
for: "startDate",
content: selectedLanguage === 'fr-FR' ? "Date de début:" : "Start Date:",
},
{
elementType: "input",
class: ["form-control"],
tabindex: -1,
"aria-hidden": true,
type: "date",
id: "startDate",
name: "startDate",
value: new Date().toISOString().split("T")[0]
}
]
},
{
elementType: "div",
class: ["form-group"],
childs: [
{
elementType: "label",
for: "endDate",
content: selectedLanguage === 'fr-FR' ? "Date de fin:" : "End Date:",
},
{
elementType: "input",
class: ["form-control"],
tabindex: -1,
"aria-hidden": true,
type: "date",
id: "endDate",
name: "endDate",
value: new Date().toISOString().split("T")[0]
}
]
},
{
elementType: "div",
class: ["errorMessage", "alert", "alert-danger", "hidden"],
role: "alert",
childs: [
{
elementType: "span",
class: ["glyphicon", "glyphicon-exclamation-sign"],
"aria-hidden": "true"
},
{
elementType: "span",
class: ["sr-only"],
content: "Error:"
},
{
elementType: "span",
class: ["errorMessageContent"],
content: selectedLanguage === 'fr-FR' ? "Message d'erreur" : "Error message",
}
]
}
]
}
)
mainDialog.setErrorMessage = (message) => {
if (!message) {
mainDialog.querySelector(".errorMessage").classList.add("hidden")
return
}
mainDialog.querySelector(".modal-body p").textContent = messages[selectedLanguage].errorDialogMessage;
mainDialog.querySelector(".errorMessage").classList.remove("hidden")
}
const errorDialog = buildDialog(
"errorDialog",
messages[selectedLanguage].errorDialogTitle,
messages[selectedLanguage].notConnectedMessage,
() => true,
{}
);
errorDialog.show = (message) => {
errorDialog.querySelector(".modal-body p").textContent = message
showDialog("errorDialog")
}
const modalFadeIn = jsonToHTML({
elementType: "div",
class: ["modal-backdrop", "fade", "in"]
})
/************
* MAIN CODE *
************/
/**
* check if the user is logged in
* @returns true if the user is logged in, false otherwise
*/
function isConnected() {
const textContent = document.querySelector(".logInOrOut").innerText;
return /Déconnexion - [0-9]+|Log Out - [0-9]+/i.test(textContent);
}
function getFederalId() {
const textContent = document.querySelector(".logInOrOut").innerText;
const match = textContent.match(/Déconnexion - ([0-9]+)|Log Out - ([0-9]+)/i);
if (match) {
return match[1] || match[2];
}
return null;
}
/**
* reset error visual and message in the main dialog
*/
function resetMainDialogError() {
mainDialog.setErrorMessage()
document.getElementById("startDate").parentElement.classList.remove("has-error")
document.getElementById("startDate").parentElement.classList.remove("has-error")
}
/**
* fetch json data of the user CELCAT calendar
* @param startDate the start date of the export
* @param endDate the end date of the export
* @returns the json data fetched from the CELCAT api
*/
async function getData(startDate, endDate) {
const headers = new Headers()
headers.append("Content-Type", "application/x-www-form-urlencoded")
const params = {
method: "POST",
headers: headers,
mode: "cors",
body: new URLSearchParams({
start: startDate.toISOString().split("T")[0],
end: endDate.toISOString().split("T")[0],
resType: "104",
calView: "agendaWeek",
"federationIds[]": getFederalId(),
colourScheme: "3"
})
}
const result = await fetch("https://edt.univ-tlse3.fr/calendar2/Home/GetCalendarData", params)
return result.json()
}
/**
* clean the data fetched from the CELCAT api by removing <br/> tags and repetitive \n or \r
* @param description the description of the event
* @returns cleaned description
*/
function cleanDescription(description) {
return description.replace(/(<br \/>|[\r])/g, "")
.replace(/[\n]+/g, "\n")
.replace(/è/g,"è")
.replace(/é/g,"è")
.replace(/â/g,"â")
}
/**
* take and iso date given by the CELCAT api or javascript date and convert it to ISO 8601 format
* @param dateString the date in ISO format
* @returns the date in the format YYYYMMDDTHHmmss (ISO 8601)
*/
function formatDate(dateString) {
return dateString.replace(/([-:]|\.[0-9]+)/g, "")
}
/**
* parse event description to get the location, the event type, the room, and the couse id and name
* @param description the description of the event
* @returns the parsed data
*/
function parseDescription(description) {
const details = description.split("\n")
return {
type: details[0],
title: details[1].split(" - ")[0],
course: details[1].split(" - ")[1],
room: details[2],
group: details[3]
}
}
function dataToIcal(data) {
let result = "BEGIN:VCALENDAR\r\n"
result += "VERSION:2.0\r\n"
result += "PRODID:-//Robotechnic//Univ Toulouse III//CELCAT//FR\r\n"
result += "CALSCALE:GREGORIAN\r\n"
result += "METHOD:PUBLISH\r\n"
result += "X-WR-CALNAME:CELCAT-EDT\r\n"
result += "X-WR-TIMEZONE:Europe/Paris\r\n"
const dstamp = `DTSTAMP:${formatDate(new Date().toISOString())}\r\n`
for (const event of data) {
if (event.eventCategory == "CONGES" || event.eventCategory == "FERIE" || event.eventCategory == "PONT") continue
event.description = cleanDescription(event.description)
const details = parseDescription(event.description)
const categoryColor = getCategoryColor(event.eventCategory);
result += "BEGIN:VEVENT\r\n"
result += `UID:${event.id}\r\n`
result += dstamp
result += `DTSTART:${formatDate(event.start)} \r\n`
result += `DTEND:${formatDate(event.end)} \r\n`
result += `SUMMARY:${details.course || 'Undefined Event'} \r\n`
result += `DESCRIPTION:${event.description.replace(/\n/g,"\\n")}\r`
result += `LOCATION:${details.room} \r\n`
result += `CATEGORIES:${event.eventCategory} \r\n`
result += `COLOR:${categoryColor}\r\n`;
result += "END:VEVENT\r\n"
}
result += "END:VCALENDAR\r\n"
return result
}
function getCategoryColor(category) {
switch (category) {
case "COURS":
return "#8080ff";
case "TD":
return "#ff8080";
case "TP":
return "#408080";
case "REUNION / RENCONTRE":
return "#ffff80";
case "CONTROLE CONTINU":
return "#808000";
default:
return "#ffc4c4";
}
}
/**
* export dat to iCalendar format and download it
* @returns true if the exportation is a success, false otherwise
*/
function exportData() {
const startElement = document.getElementById("startDate")
const startDate = new Date(startElement.value)
const endElement = document.getElementById("endDate")
const endDate = new Date(endElement.value)
resetMainDialogError()
if (startDate == "Invalid Date") {
mainDialog.setErrorMessage("La date de début est invalide.")
startElement.parentElement.classList.add("has-error")
startElement.focus()
return false
}
if (endDate == "Invalid Date") {
mainDialog.setErrorMessage("La date de fin est invalide.")
endElement.parentElement.classList.add("has-error")
endElement.focus()
return false
}
if (startDate > endDate) {
mainDialog.setErrorMessage("La date de début doit être avant la date de fin.")
startElement.parentElement.classList.add("has-error")
endElement.parentElement.classList.add("has-error")
startElement.focus()
return false
}
resetMainDialogError()
//GM_log(`Exporting data from ${startDate} to ${endDate}`)
getData(startDate, endDate)
.then(data => {
const ical = dataToIcal(data)
const link = document.createElement("a")
link.setAttribute("href", `data:text/calendar;charset=utf-8,${encodeURIComponent(ical)}`)
link.download = `export-${startDate.toISOString().split("T")[0]}-${endDate.toISOString().split("T")[0]}.ics`
link.click()
})
.catch(error => {
errorDialog.show(error)
//GM_log(error)
})
return true;
}
/**
* Add the export button to the page interface
*/
function addButton() {
const navBar = document.querySelector("#main-navbar-collapse .navbar-nav");
const button = jsonToHTML({
elementType: "li",
class: ["navbar-link"],
childs: [
{
elementType: "a",
id: "iCalendarGeneration",
content: messages[selectedLanguage].exportButtonLabel,
style: "cursor:pointer;",
events: {
"click": () => {
if (isConnected()) {
showDialog("mainDialog");
} else {
errorDialog.show(messages[selectedLanguage].notConnectedMessage);
}
}
}
}
]
});
navBar.appendChild(button);
mainDialog.querySelector(".modal-footer").prepend(
jsonToHTML({
elementType: "button",
class: ["btn", "btn-default"],
type: "button",
"data-dismiss": "modal",
content: messages[selectedLanguage].exportButtonLabel,
events: {
"click": () => {
if (!exportData()) return;
hideDialog("mainDialog");
}
}
})
);
}
(function() {
addButton()
})();