-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcarleton-timetables.js
More file actions
1052 lines (979 loc) · 45.1 KB
/
carleton-timetables.js
File metadata and controls
1052 lines (979 loc) · 45.1 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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Retrieves Carleton timetable settings and privacy policy agreement from Chrome storage
* @returns {Promise<Object>} Promise that resolves to storage results containing carleton and privacy_policy_agreement data
* @throws {Error} Throws error if storage access fails
*/
async function getCarletonAndPrivacyPolicy() {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.get(['carleton', 'privacy_policy_agreement'], (results) => {
if (chrome.runtime.lastError) {
// Storage error
reject(chrome.runtime.lastError);
} else {
resolve(results);
}
});
} catch (err) {
// Error in getCarletonAndPrivacyPolicy
reject(err);
}
});
}
(async () => {
let results;
try {
results = await getCarletonAndPrivacyPolicy();
} catch (err) {
alert('Failed to load settings. Please try again.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
return;
}
let r;
let pa;
try {
if (!results || typeof results !== 'object') {
r = getDefaultTerm();
alert(`No default term found; Using: ${r}`);
} else {
r = Array.isArray(results['carleton']) ? results['carleton'] : getDefaultTerm();
pa = Array.isArray(results['privacy_policy_agreement']) ? results['privacy_policy_agreement'] : undefined;
}
} catch (err) {
// Error processing results
alert('Error processing settings.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
return;
}
const termSelector = document.getElementById('term_id');
const bigFatHeader = 'body > div.pagetitlediv > table > tbody > tr:nth-child(1) > td:nth-child(1) > h2';
const timetableNav = 'body > div.footerlinksdiv > span > map > p:nth-child(2) > a:nth-child(2)';
const calendarNav = 'body > div.pagebodydiv > table.menuplaintable > tbody > tr:nth-child(3) > td:nth-child(2) > span > ul > li:nth-child(1) > a:nth-child(4)';
const targetTerm = String(r[1]) + String(r[0]);
const exportCombined = !!r[2];
const submitBtn = document.querySelector('input[type=submit]');
const tableElement = 'table.datadisplaytable[summary="This table lists the scheduled meeting times and assigned instructors for this class.."]';
try {
if (document.title.trim() == 'Sign In') {
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempLoginCU'})
}
else if (document.title.trim() == 'Sign out') {
// chrome.runtime.sendMessage({action:'redirect', href:'https://ssoman.carleton.ca/ssomanager/c/SSB?pkg=bwskfshd.P_CrseSchd'})
window.location.href = 'https://ssoman.carleton.ca/ssomanager/c/SSB?pkg=bwskfshd.P_CrseSchd';
}
else if (document.title.trim() == 'Main Menu') {
waitForElmText(calendarNav, 'Student Timetable').then(
() => {
try {
document.querySelector(calendarNav).click();
} catch (err) {
// Error clicking calendarNav
alert('Navigation error.\n\nNeuroNest');
}
}
).catch(err => {
// waitForElmText error
alert('Failed to find Student Timetable link.\n\nNeuroNest');
});
}
else if (document.title.trim() == 'Student Timetable') {
// chrome.runtime.sendMessage({action:'timetable1', node:'carleton', case:'student-calendar', tab:tab[0],script:'armory/carleton-timetable.js'})
waitForElmText(timetableNav, 'Detail Schedule').then(
() => {
try {
document.querySelector(timetableNav).click();
} catch (err) {
// Error clicking timetableNav
alert('Navigation error.\n\nNeuroNest');
}
}
).catch(err => {
// waitForElmText error
alert('Failed to find Detail Schedule link.\n\nNeuroNest');
});
}
else if (document.title.trim() == 'Registration Term') {
waitForElm('#term_id').then(() => {
try {
if (termSelector && isValidTerm(termSelector, targetTerm)) {
termSelector.value = targetTerm;
submitBtn.click();
} else {
alert(`Request failed: Term [${mapTerm(r)}] Not Found\n\nTimetable Tools`);
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
}
} catch (err) {
// Error in Registration Term
alert('Error selecting term.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
}
}).catch(err => {
// waitForElm error
alert('Failed to find term selector.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
});
}
else if (document.title.trim() == 'Student Detail Schedule') {
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempLoginCU'});
waitForElm(bigFatHeader).then((elm) => {
try {
run();
} catch (err) {
// Error running timetable extraction
alert('Failed to process timetable.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
}
}).catch(err => {
// waitForElm error
alert('Failed to find timetable header.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
});
}
else {
// chrome.runtime.sendMessage({action:'timetable1', node:'carleton', case:'sign-in', tab:tab[0], script:'armory/carleton-timetable.js'})
}
} catch (err) {
// Unhandled error in main navigation
alert('Unexpected error occurred.\n\nNeuroNest');
chrome.runtime.sendMessage({action:'end-timetable-request'});
// chrome.runtime.sendMessage({action:'closeTempTabs', type:'tempTimetableCU'});
}
/**
* Waits for a DOM element to appear on the page
* @param {string} selector - CSS selector for the element to wait for
* @returns {Promise<Element>} Promise that resolves with the found element
* @throws {Error} Throws error if element not found within 10 seconds
*/
async function waitForElm(selector) {
return new Promise((resolve, reject) => {
try {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
observer.disconnect();
resolve(document.querySelector(selector));
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
setTimeout(() => {
observer.disconnect();
reject(new Error('Timeout waiting for element: ' + selector));
}, 10000);
} catch (err) {
// waitForElm error
reject(err);
}
});
}
/**
* Waits for a DOM element with specific text content to appear
* @param {string} selector - CSS selector for the element
* @param {string} text - Expected text content of the element
* @param {number} [maxWaitTime=5000] - Maximum wait time in milliseconds
* @returns {Promise<Element>} Promise that resolves with the found element
* @throws {Error} Throws error if element with text not found within maxWaitTime
*/
async function waitForElmText(selector, text, maxWaitTime = 5000) {
const start = Date.now();
try {
while (Date.now() - start < maxWaitTime) {
const element = document.querySelector(selector);
if (element && element.textContent.trim() === text) {
return element;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
throw new Error('Timeout waiting for element text');
} catch (err) {
// waitForElmText error
throw err;
}
}
/**
* Validates if a term exists in the term selector dropdown
* @param {HTMLSelectElement} termSelector - The term selector dropdown element
* @param {string} targetTerm - The term code to validate (e.g., "202410")
* @returns {boolean} True if term exists in selector, false otherwise
*/
const isValidTerm = (termSelector, targetTerm) => {
try {
const options = termSelector.options;
for (let i = 0; i < options.length; i++) {
if (options[i].value == targetTerm) {
return true;
}
}
return false;
} catch (err) {
// isValidTerm error
return false;
}
}
/**
* Main function that processes the timetable data and generates calendar files
* Extracts course information from Carleton's timetable page and creates ICS files
* @returns {Promise<void>} Promise that completes when timetable processing is done
*/
const run = async () => {
try {
if (pa && pa[0]) {
const tables = [];
const log = [];
let staticHeadersDiv, userInfo2, userInfo3;
try {
staticHeadersDiv = document.querySelector('.staticheaders');
userInfo2 = staticHeadersDiv ? staticHeadersDiv.innerHTML.split('<br>')[1].trim().split(' ').slice(0, 2).join(' ') : 'Nameless';
userInfo3 = staticHeadersDiv ? staticHeadersDiv.innerHTML.split('<br>')[0].trim().split(' ').slice(1).join(' ') : 'Unknown User';
} catch (err) {
// Error extracting user info
userInfo2 = 'Nameless';
userInfo3 = 'Unknown User';
}
/**
* Extracts content from a specific table row
* @param {HTMLTableElement} table - The table element to search in
* @param {number} rowIndex - The row index to extract content from (1-based)
* @returns {string} The text content of the row, or 'N/A' if not found
*/
const getRowContent = (table, rowIndex) => {
try {
const row = table.querySelector(`tr:nth-of-type(${rowIndex}) td`);
return !(row == '') ? row.textContent.trim() : 'N/A';
} catch (err) {
// getRowContent error
return 'N/A';
}
}
document.querySelectorAll('table.datadisplaytable').forEach((table, index) => {
try {
const section = {};
const meta = {};
meta['table-num'] = index;
if (table.querySelector('a')) {
table.querySelectorAll('tr').forEach((r) => {
const headerElement = r.querySelector('th');
const valueElement = r.querySelector('td');
if (headerElement && valueElement) {
let header = headerElement.textContent.slice(0, -1).trim();
let value = valueElement.textContent.trim();
meta[header] = value;
}
});
let courseData = table.querySelector('a').textContent.trim().split(' - ').reverse();
let courseCode = courseData[1] || '';
let courseSection = courseData[0] || '';
let courseName = courseData.slice(2).join(' - ');
let crn = getRowContent(table, 3);
let instructor = getRowContent(table, 5);
section.courseName = courseName;
section.courseCode = courseCode;
section.courseSection = courseSection;
section.crn = crn;
section.instructor = instructor.trim() ? instructor.trim() : 'Instructor: N/A';
const targetIndex = Math.floor(index / 2);
if (!tables[targetIndex]) tables[targetIndex] = {};
//Store meta data with section for component type access
section.meta = meta;
Object.assign(tables[targetIndex], section);
log.push(meta);
} else {
const row = table.querySelector('tr:nth-of-type(2)');
if (!row) throw new Error('Missing row in table');
const cells = row.querySelectorAll('td');
const timeCell = cells[1] ? cells[1].textContent.trim() : '';
section.classStartTime = timeCell == 'TBA' ? 'N/A' : (timeCell.split(' - ')[0] || 'N/A');
section.classEndTime = timeCell == 'TBA' ? 'N/A' : (timeCell.split(' - ')[1] || 'N/A');
section.daysOfTheWeek = cells[2] ? cells[2].textContent.trim() : '';
const loc = cells[3] ? cells[3].textContent.trim() : '';
section.location = loc == 'TBA' ? '' : loc;
const dateCell = cells[4] ? cells[4].textContent.trim() : '';
const dateParts = dateCell.split(' - ');
section.startDate = new Date(dateParts[0] || Date.now());
section.endDate = new Date(dateParts[1] || Date.now());
const targetIndex = Math.floor(index / 2);
if (!tables[targetIndex]) tables[targetIndex] = {};
Object.assign(tables[targetIndex], section);
table.querySelectorAll('th').forEach((r, o) => {
let header = r.textContent.trim();
let value = cells[o] ? cells[o].textContent.trim() : '';
meta[header] = value;
});
//Store meta data with section for component type access
section.meta = meta;
Object.assign(tables[targetIndex], section);
log.push(meta);
}
} catch (err) {
// Error parsing table
}
});
const timetable = tables;
/**
* Determines recurrence pattern based on schedule type
* @param {Object} node - Course node with meta data
* @param {string} dayOfWeek - Day of week code (MO, TU, etc.)
* @param {string} untilDate - End date in UTC format
* @returns {string} RRULE string for recurrence
*/
const getRecurrenceRule = (node, dayOfWeek, untilDate) => {
try {
// Check if this is a lab based on Schedule Type
const scheduleType = node.meta && node.meta['Schedule Type'] ? node.meta['Schedule Type'].toLowerCase() : '';
const isLab = scheduleType.includes('lab') || scheduleType.includes('laboratory');
if (isLab) {
// Labs are typically biweekly (every 2 weeks)
return `FREQ=WEEKLY;INTERVAL=2;BYDAY=${dayOfWeek};UNTIL=${untilDate};WKST=SU`;
} else {
// Lectures and tutorials are weekly
return `FREQ=WEEKLY;BYDAY=${dayOfWeek};UNTIL=${untilDate};WKST=SU`;
}
} catch (err) {
// Default to weekly if error
return `FREQ=WEEKLY;BYDAY=${dayOfWeek};UNTIL=${untilDate};WKST=SU`;
}
};
/**
* Creates iCalendar (.ics) files from timetable data
* @param {Array<Object>} timetable - Array of course objects containing schedule information
*/
const createICal = (timetable) => {
try {
if (!Array.isArray(timetable) || timetable.length === 0) {
alert('No timetable data to export.\n\nNeuroNest');
return;
}
if (exportCombined) {
let icsContent = 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//NeuroNest//CU_Timetable//EN\n';
let count = 0;
let allCourses = '';
let processedEvents = [];
timetable.forEach(node => {
try {
if (!node || !node.daysOfTheWeek) return;
const daysMap = { 'M': 'MO', 'T': 'TU', 'W': 'WE', 'R': 'TH', 'F': 'FR' };
const startTime = node.classStartTime == 'N/A' ? 'none' : convertTo24Hour(node.classStartTime).split(':');
const endTime = node.classEndTime == 'N/A' ? 'none' : convertTo24Hour(node.classEndTime).split(':');
const startHour = parseInt(startTime[0], 10);
const startMinute = parseInt(startTime[1], 10);
const endHour = parseInt(endTime[0], 10);
const endMinute = parseInt(endTime[1], 10);
const timeNoSpace = node.classStartTime.replace(/\s/g,'');
const timeNoSpace2 = node.classEndTime.replace(/\s/g, '');
// Create separate events for each day
node.daysOfTheWeek.split('').forEach(day => {
const dayOfWeek = daysMap[day];
if (dayOfWeek && startTime != 'none') {
// Adjust start date to this specific day
const adjustedStartDate = adjustStartDateToDay(new Date(node.startDate), day, node);
const startDate = new Date(adjustedStartDate);
const endDate = new Date(adjustedStartDate);
const untilDate = new Date(node.endDate);
untilDate.setDate(untilDate.getDate() + 1);
startDate.setHours(startHour, startMinute, 0, 0);
endDate.setHours(endHour, endMinute, 0, 0);
const courseInfo = `${node.courseCode} - ${node.courseSection}\n${timeNoSpace} - ${timeNoSpace2}\n${node.location ? node.location : 'Location: N/A'}\n${node.courseName}\n${node.instructor}\n${node.crn}\n...\n`;
allCourses += courseInfo;
processedEvents.push({
// Neutral format
title: `${node.courseCode}-${node.courseSection}`,
description: `${node.courseName}\n${node.courseCode} - ${node.courseSection}\n${node.instructor}\n${node.crn}\n${timeNoSpace} - ${timeNoSpace2}\n${node.location ? node.location : 'Location: N/A'}`,
location: node.location || 'Location: N/A',
startDateTime: startDate,
endDateTime: endDate,
recurrenceRule: getRecurrenceRule(node, dayOfWeek, formatDateUTC(untilDate)),
timezone: 'America/Toronto'
});
icsContent += 'BEGIN:VEVENT\n';
icsContent += `DTSTART;TZID=America/Toronto:${formatDateLocal(startDate)}\n`;
icsContent += `DTEND;TZID=America/Toronto:${formatDateLocal(endDate)}\n`;
icsContent += `RRULE:${getRecurrenceRule(node, dayOfWeek, formatDateUTC(untilDate))}\n`;
icsContent += `SUMMARY:${node.courseCode}-${node.courseSection}\n`;
icsContent += `DESCRIPTION:${node.courseName}\\n${node.courseCode} - ${node.courseSection}\\n${node.instructor}\\n${node.crn}\\n${timeNoSpace} - ${timeNoSpace2}\\n${node.location ? node.location : 'Location: N/A'}\n`;
icsContent += `LOCATION:${node.location}\n`;
icsContent += 'END:VEVENT\n';
count++;
}
});
} catch (err) {
// Error creating iCal event
}
});
icsContent += 'END:VCALENDAR';
if (count > 0) {
// Check selected calendar type and export accordingly
chrome.storage.local.get(['selected-calendar'], (result) => {
const selectedCalendar = result['selected-calendar'] || 'ics';
if (selectedCalendar === 'google') {
// Export to Google Calendar
createGoogleCalendarEvents(processedEvents, userInfo2);
} else if (selectedCalendar === 'outlook') {
// Export to Outlook Calendar
createOutlookCalendarEvents(processedEvents, userInfo2);
} else if (selectedCalendar === 'apple') {
// Export to Apple Calendar via CalDAV
createAppleCalendarEvents(processedEvents, userInfo2);
} else {
// Export as ICS file (default for ics and fallback)
try {
const blob = new Blob([icsContent], { type: 'text/calendar' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = userInfo2 + '.ics';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
// Error downloading iCal
alert('Failed to download calendar file.\n\nNeuroNest');
}
}
const currentDate = new Date().toLocaleString('en-US', { timeZone: 'America/Toronto', hour12: false });
logCalendar([userInfo3, currentDate, 'carleton', userInfo2, allCourses, icsContent]);
});
} else {
alert('Nothing to see here...\n\nNeuroNest');
}
} else {
/*let totalCount = 0;
let totalIcs = '';
let allCourses = '';
let processedEvents = []; // Array to collect events for Google Calendar
timetable.forEach(node => {
try {
let icsContent = 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//NeuroNest//Timetable//EN\n';
let count = 0;
if (!node || !node.daysOfTheWeek) return;
const daysMap = { 'M': 'MO', 'T': 'TU', 'W': 'WE', 'R': 'TH', 'F': 'FR' };
const startTime = node.classStartTime == 'N/A' ? 'none' : convertTo24Hour(node.classStartTime).split(':');
const endTime = node.classEndTime == 'N/A' ? 'none' : convertTo24Hour(node.classEndTime).split(':');
const startHour = parseInt(startTime[0], 10);
const startMinute = parseInt(startTime[1], 10);
const endHour = parseInt(endTime[0], 10);
const endMinute = parseInt(endTime[1], 10);
const timeNoSpace = node.classStartTime.replace(/\s/g, '');
const timeNoSpace2 = node.classEndTime.replace(/\s/g, '');
// Create separate events for each day
node.daysOfTheWeek.split('').forEach(day => {
const dayOfWeek = daysMap[day];
if (dayOfWeek && startTime != 'none') {
// Adjust start date to this specific day
const adjustedStartDate = adjustStartDateToDay(new Date(node.startDate), day);
const startDate = new Date(adjustedStartDate);
const endDate = new Date(adjustedStartDate);
const untilDate = new Date(node.endDate);
untilDate.setDate(untilDate.getDate() + 1);
startDate.setHours(startHour, startMinute, 0, 0);
endDate.setHours(endHour, endMinute, 0, 0);
const courseInfo = `${node.courseCode} - ${node.courseSection}\n${timeNoSpace} - ${timeNoSpace2}\n${node.location ? node.location : 'Location: N/A'}\n${node.courseName}\n${node.instructor}\n${node.crn}\n...\n`;
allCourses += courseInfo;
// Store processed event data for Google Calendar
processedEvents.push({
summary: `${node.courseCode}-${node.courseSection}`,
description: `${node.courseName}\n${node.courseCode} - ${node.courseSection}\n${node.instructor}\n${node.crn}\n${timeNoSpace} - ${timeNoSpace2}\n${node.location ? node.location : 'Location: N/A'}`,
location: node.location || 'Location: N/A',
start: {
dateTime: startDate.toISOString(),
timeZone: 'America/Toronto'
},
end: {
dateTime: endDate.toISOString(),
timeZone: 'America/Toronto'
},
recurrence: [`RRULE:FREQ=WEEKLY;BYDAY=${dayOfWeek};UNTIL=${formatDateUTC(untilDate)};WKST=SU`]
});
icsContent += 'BEGIN:VEVENT\n';
icsContent += `DTSTART;TZID=America/Toronto:${formatDateLocal(startDate)}\n`;
icsContent += `DTEND;TZID=America/Toronto:${formatDateLocal(endDate)}\n`;
icsContent += `RRULE:FREQ=WEEKLY;BYDAY=${dayOfWeek};UNTIL=${formatDateUTC(untilDate)};WKST=SU;\n`;
icsContent += `SUMMARY:${node.courseCode}-${node.courseSection}\n`;
icsContent += `DESCRIPTION:${node.courseName}\\n${node.courseCode} - ${node.courseSection}\\n${node.instructor}\\n${node.crn}\\n${timeNoSpace} - ${timeNoSpace2}\\n${node.location ? node.location : 'Location: N/A'}\n`;
icsContent += `LOCATION:${node.location}\n`;
icsContent += 'END:VEVENT\n';
count++;
totalCount++;
}
});
icsContent += 'END:VCALENDAR';
if (count > 0) {
totalIcs += icsContent + '\n\n';
totalCount++;
// Check selected calendar type and export accordingly
chrome.storage.local.get(['selected-calendar'], (result) => {
const selectedCalendar = result['selected-calendar'] || 'ics';
if (selectedCalendar === 'google') {
// For Google Calendar, collect events but don't download individual files
// Events will be created in batch after processing all courses
} else if (selectedCalendar === 'outlook') {
// For Outlook Calendar, collect events but don't download individual files
// Events will be created in batch after processing all courses
} else if (selectedCalendar === 'apple') {
// For Apple Calendar, collect events but don't download individual files
// Events will be created in batch after processing all courses
} else {
// Export as ICS file (default for ics and fallback)
try {
const blob = new Blob([icsContent], { type: 'text/calendar' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${node.courseCode}-${node.courseSection}` + '.ics';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
// Error downloading iCal
alert('Failed to download calendar file.\n\nNeuroNest');
}
}
});
}
} catch (err) {
// Error creating iCal event
}
});
const currentDate = new Date().toLocaleString('en-US', { timeZone: 'America/Toronto', hour12: false });
logCalendar([userInfo3, currentDate, 'carleton', userInfo2, allCourses, totalIcs]);
// Handle calendar export for individual mode
chrome.storage.local.get(['selected-calendar'], (result) => {
const selectedCalendar = result['selected-calendar'] || 'ics';
if (selectedCalendar === 'google' && processedEvents.length > 0) {
// Create all events in Google Calendar
createGoogleCalendarEvents(processedEvents, 'All Courses');
} else if (selectedCalendar === 'outlook' && processedEvents.length > 0) {
// Create all events in Outlook Calendar
createOutlookCalendarEvents(processedEvents, 'All Courses');
} else if (selectedCalendar === 'apple' && processedEvents.length > 0) {
// Create all events in Apple Calendar
createAppleCalendarEvents(processedEvents, 'All Courses');
} else if (totalCount <= 0) {
alert('No classes found\n\nNeuroNest');
}
});*/
// Individual export mode disabled - only combined export supported
alert('Individual course export is currently disabled. Please use combined export mode.\n\nTimetable Tools');
return;
}
}catch (err) {
// createICal error
alert('Failed to generate calendar file.\n\nNeuroNest');
}
}
/**
* Adjusts a start date to match the first occurrence of specified days of the week
* @param {Date} startDate - The initial start date
* @param {string} daysOfTheWeek - String containing day codes (M, T, W, R, F)
* @returns {Date} Adjusted date that falls on the first specified day
*/
const adjustStartDateToDay = (startDate, dayCode, node) => {
try {
const daysMap = { 'M': 1, 'T': 2, 'W': 3, 'R': 4, 'F': 5 };
if (!dayCode || dayCode.length === 0) return startDate;
const dayOfWeek = daysMap[dayCode];
const currentDay = startDate.getDay();
let diff = dayOfWeek - currentDay;
const wasNegative = diff < 0; // Track if target day was earlier in week
if (diff < 0) diff += 7;
// Check if this is a tutorial or lab that should start in second week
const scheduleType = node && node.meta && node.meta['Schedule Type'] ? node.meta['Schedule Type'].toLowerCase() : '';
const isLab = scheduleType.includes('laboratory') || scheduleType.includes('lab');
const isTutorial = scheduleType.includes('tutorial') || scheduleType.includes('tut');
if (isLab || isTutorial) {
if (!wasNegative) {
// Target day wasn't earlier in week than term start - add 7 for second week
diff += 7;
}
}
startDate.setDate(startDate.getDate() + diff);
return startDate;
} catch (err) {
// adjustStartDateToDay error
return startDate;
}
}
if (!pa[2]) {
try {
updateAgreement([
userInfo3,
"NeuroNest",
pa[1],
`${new Date().toLocaleString('en-US', { timeZone: 'America/Toronto', hour12: false })}`,
`${pa[0] ? "Yes" : "No"}`
]);
} catch (err) {
// updateAgreement error
}
}
/**
* Formats a Date object for iCalendar local time format
* @param {Date} date - Date object to format
* @returns {string} Formatted date string in YYYYMMDDTHHMMSS format
*/
const formatDateLocal = (date) => {
try {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}${month}${day}T${hours}${minutes}${seconds}`;
} catch (err) {
// formatDateLocal error
return '';
}
};
/**
* Formats a Date object for iCalendar UTC time format
* @param {Date} date - Date object to format
* @returns {string} Formatted date string in YYYYMMDDTHHMMSSZ format
*/
const formatDateUTC = (date) => {
try {
return date.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
} catch (err) {
// formatDateUTC error
return '';
}
};
/**
* Converts 12-hour time format to 24-hour format
* @param {string} time12h - Time in 12-hour format (e.g., "2:30 pm")
* @returns {string} Time in 24-hour format (e.g., "14:30")
*/
const convertTo24Hour = (time12h) => {
try {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') hours = '00';
if (modifier === 'pm') hours = parseInt(hours, 10) + 12;
return `${hours}:${minutes}`;
} catch (err) {
// convertTo24Hour error
return '00:00';
}
};
createICal(timetable);
chrome.runtime.sendMessage({ action: 'end-timetable-request' });
// chrome.runtime.sendMessage({ action: 'closeTempTabs', type: 'tempTimetableCU' });
} else {
alert("ERROR: Privacy Policy Agreement not found, aborting!\n\n NeuroNest");
chrome.runtime.sendMessage({ action: 'end-timetable-request' });
// chrome.runtime.sendMessage({ action: 'closeTempTabs', type: 'tempTimetableCU' });
}
} catch (err) {
// run() error
alert('Unexpected error during timetable processing.\n\nNeuroNest');
chrome.runtime.sendMessage({ action: 'end-timetable-request' });
// chrome.runtime.sendMessage({ action: 'closeTempTabs', type: 'tempTimetableCU' });
}
}
/**
* Maps term code to human-readable semester name
* @param {Array} term - Array containing term code and year [termCode, year]
* @returns {string} Human-readable term string (e.g., "Fall 2024")
*/
const mapTerm = (term) => {
try {
let sem;
switch (term[0]) {
case '30':
sem = 'Fall';
break;
case '20':
sem = 'Summer';
break;
case '10':
sem = 'Winter';
break;
default:
// Invalid semester code
return;
}
return `${sem} ${term[1]}`;
} catch (err) {
// mapTerm error
return '';
}
}
/**
* Determines the default term based on current date
* @returns {Array} Array containing [termCode, year, exportCombined] for current term
*/
const getDefaultTerm = () => {
try {
const currentDate = new Date();
const month = currentDate.getMonth() + 1;
let year = String(currentDate.getFullYear());
let term;
if (month >= 1 && month <= 3) {
term = '10';
} else if (month >= 4 && month <= 7) {
term = '20';
} else if (month >= 8 && month <= 11) {
term = '30';
} else if (month === 12) {
term = '10';
year = String(Number(year) + 1);
} else {
term = '10';
// Month not found
}
return [term, year, true];
} catch (err) {
// getDefaultTerm error
return ['10', String(new Date().getFullYear()), true];
}
}
/**
* Converts neutral event format to Google Calendar API format
* @param {Object} neutralEvent - Event in neutral format
* @returns {Object} Event in Google Calendar format
*/
function convertToGoogleFormat(neutralEvent) {
return {
summary: neutralEvent.title,
description: neutralEvent.description,
location: neutralEvent.location,
start: {
dateTime: neutralEvent.startDateTime.toISOString(),
timeZone: neutralEvent.timezone
},
end: {
dateTime: neutralEvent.endDateTime.toISOString(),
timeZone: neutralEvent.timezone
},
recurrence: [`RRULE:${neutralEvent.recurrenceRule}`]
};
}
/**
* Formats a Date object for Microsoft Graph API
* @param {Date} date - Date object to format (assumed to be in correct local time)
* @returns {string} Formatted date string (YYYY-MM-DDTHH:mm:ss.000)
*/
function formatDateForOutlook(date) {
// Use the date as-is since it's already created in the correct timezone context
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000`;
}
/**
* Converts neutral event format to Microsoft Graph API format
* @param {Object} neutralEvent - Event in neutral format
* @returns {Object} Event in Microsoft Graph format
*/
function convertToOutlookFormat(neutralEvent) {
// Parse recurrence rule to extract components
let recurrencePattern = null;
if (neutralEvent.recurrenceRule) {
const rrule = neutralEvent.recurrenceRule;
const dayMatch = rrule.match(/BYDAY=([^;]+)/);
const untilMatch = rrule.match(/UNTIL=([^;]+)/);
const intervalMatch = rrule.match(/INTERVAL=(\d+)/);
if (dayMatch && untilMatch) {
// Map day codes from RRULE to Outlook format
const dayMapping = {
'MO': 'monday',
'TU': 'tuesday',
'WE': 'wednesday',
'TH': 'thursday',
'FR': 'friday'
};
const days = dayMatch[1].split(',').map(day => dayMapping[day]).filter(Boolean);
const until = new Date(untilMatch[1].replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/, '$1-$2-$3T$4:$5:$6Z'));
const interval = intervalMatch ? parseInt(intervalMatch[1]) : 1;
if (days.length > 0) {
recurrencePattern = {
pattern: {
type: 'weekly',
interval: interval, // Use extracted interval (1 for weekly, 2 for biweekly)
daysOfWeek: days
},
range: {
type: 'endDate',
startDate: neutralEvent.startDateTime.toISOString().split('T')[0],
endDate: until.toISOString().split('T')[0]
}
};
}
}
}
const outlookEvent = {
subject: neutralEvent.title || 'Untitled Event',
body: {
contentType: 'text',
content: neutralEvent.description || ''
},
start: {
dateTime: formatDateForOutlook(neutralEvent.startDateTime),
timeZone: neutralEvent.timezone || 'America/Toronto'
},
end: {
dateTime: formatDateForOutlook(neutralEvent.endDateTime),
timeZone: neutralEvent.timezone || 'America/Toronto'
}
};
// Only add location if it exists and is not empty
if (neutralEvent.location && neutralEvent.location.trim()) {
outlookEvent.location = {
displayName: neutralEvent.location
};
}
// Only add recurrence if it was successfully parsed
if (recurrencePattern) {
outlookEvent.recurrence = recurrencePattern;
}
return outlookEvent;
}
/**
* Gets Google Calendar OAuth token using message passing to background script
* @returns {Promise<string>} OAuth access token
*/
async function getGoogleCalendarToken() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ action: 'getGoogleCalendarToken' }, (response) => {
if (response && response.success) {
resolve(response.token);
} else {
reject(new Error(`Authentication failed: ${response?.error?.message || 'Unknown error'}`));
}
});
});
}
/**
* Gets Outlook Calendar OAuth token using message passing to popup script
* @returns {Promise<string>} OAuth access token
*/
async function getOutlookCalendarToken() {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ action: 'getOutlookCalendarToken' }, (response) => {
if (response && response.success) {
resolve(response.token);
} else {
reject(new Error(`Authentication failed: ${response?.error?.message || 'Unknown error'}`));
}
});
});
}
/**
* Creates events in Google Calendar using the Calendar API
* @param {Array} events - Array of event objects to create
* @param {string} calendarName - Name for the calendar (used in success message)
*/
async function createGoogleCalendarEvents(events, calendarName) {
try {
const token = await getGoogleCalendarToken();
let successCount = 0;
let errorCount = 0;
// Create events sequentially to avoid rate limiting
for (const event of events) {
try {
const response = await fetch('https://www.googleapis.com/calendar/v3/calendars/primary/events', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(convertToGoogleFormat(event))
});
if (response.ok) {
successCount++;
} else {
console.error('Failed to create event:', await response.text());
errorCount++;
}
} catch (eventError) {
console.error('Error creating individual event:', eventError);
errorCount++;
}
// Small delay to avoid rate limiting
await new Promise(resolve => setTimeout(resolve, 100));
}
// Show success/error message
if (successCount > 0) {
const message = errorCount > 0
? `Successfully created ${successCount} events in Google Calendar. ${errorCount} events failed to create.`
: `Successfully created ${successCount} events in Google Calendar!`;
alert(message);
} else {
alert('Failed to create any events in Google Calendar. Please try again.');
}
} catch (error) {
console.error('Google Calendar integration error:', error);
alert(`Failed to connect to Google Calendar: ${error.message}`);
}
}
/**
* Creates events in Outlook Calendar using the Microsoft Graph API
* @param {Array} events - Array of event objects to create
* @param {string} calendarName - Name for the calendar (used in success message)
*/
async function createOutlookCalendarEvents(events, calendarName) {
try {
const token = await getOutlookCalendarToken();
let successCount = 0;
let errorCount = 0;