-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeTableToIcs.ps1
791 lines (688 loc) · 29.9 KB
/
timeTableToIcs.ps1
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
<#
.SYNOPSIS
Gets and converts a WebUntis timetable to an ICS calendar file.
.DESCRIPTION
This script retrieves timetable data from the WebUntis API and converts it into a subscribable ICS calendar file format.
It allows specifying a date range for the timetable data.
.PARAMETER baseUrl
The base URL of the WebUntis API.
.PARAMETER elementType
The type of element to filter by (default is 1, this should return a timetable).
.PARAMETER elementId
The classes timetable ID.
.PARAMETER dates
An array of dates (either as strings or DateTime objects) for which to retrieve timetable data.
The default is the current week and the next three weeks.
.PARAMETER OutputFilePath
The file path where the ICS file will be saved. The default is "calendar.ics".
.PARAMETER dontCreateMultiDayEvents
If set, generating "summary" multi-day events will be skipped.
.PARAMETER overrideSummaries
A hashtable to override the summaries of the courses. The key is the original course (short)name, the value is the new course name.
.PARAMETER appendToPreviousICSat
The path to an existing ICS file to which the new timetable data should be appended.
.PARAMETER splitByCourse
If set, the timetable data will be split into separate ICS files for each course.
.PARAMETER splitByOverrides
If set, the timetable data will be split into separate ICS files for each course defined in overrideSummaries and the remaining misc. classes.
.PARAMETER outAllFormats
If set, the timetable data will be output in all formats.
.PARAMETER cookie
The cookie value for the WebUntis session.
.PARAMETER tenantId
The tenant ID for the WebUntis session.
.EXAMPLE
.\timeTableToIcs.ps1 -baseUrl "your.webuntis.url" -elementType 1 -elementId 12345 -dates "2023-01-01", "2023-01-08" -OutputFilePath "mycalendar.ics" -cookie "your_cookie" -tenantId "your_tenant_id"
.NOTES
Author: Chaos_02
Date: 2024-09-28
Version: 1.5
#>
param (
[ValidateNotNullOrEmpty()]
[Alias('URL')]
[string]$baseUrl,
[int]$elementType = 1,
[Alias('TimeTableID')]
[int]$elementId,
[Parameter(Mandatory = $false)]
[Alias('Date')]
[ValidateScript({
if ($_.GetType().Name -eq 'String') {
if (-not [datetime]::TryParse($_, [ref] $null)) {
throw 'Invalid date format. Please provide a valid date string.'
}
} elseif ($_.GetType().Name -ne 'DateTime') {
throw 'Invalid date format. Provide a date string or DateTime object.'
}
$true
})]
[System.Object[]]$dates = @( (@(-7, 0, 7, 14) | ForEach-Object { (Get-Date).AddDays($_) }) ),
[switch]$dontCreateMultiDayEvents,
[Parameter(
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Output file path.'
)]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[ValidateScript({ $_.EndsWith('.ics') })]
[string]$OutputFilePath = 'calendar.ics',
# Specifies a path to one or more locations.
[ValidateNotNullOrEmpty()]
[Parameter(
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'A hashtable to override the summaries of the courses. The key is the original course (short)name, the value is the new course name.'
#Mandatory = {$splitByOverride}
)]
[hashtable]$overrideSummaries,
[Parameter(
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Path to an existing ICS file to which the new timetable data should be appended.'
)]
[ValidateNotNullOrEmpty()]
[ValidateScript({
if (-not (Test-Path $_)) {
throw "File does not exist: $_"
}
$content = Get-Content $_ -Raw
if ($content -notmatch '^BEGIN:VCALENDAR' -or $content -notmatch 'END:VCALENDAR\s*$') {
throw "Invalid .ics file: $_"
}
if ($_.Count -gt 4) {
throw 'The maximum number of weeks is 4. (Limit by WebUntis API)'
}
$true
})]
[string]$appendToPreviousICSat,
[Parameter(
ParameterSetName = 'OutputControl',
HelpMessage = 'Split the timetable data into separate ICS files for each course.'
#Mandatory = {$splitByOverride}
)]
[switch]$splitByCourse,
[Parameter(
ParameterSetName = 'OutputControl',
HelpMessage = 'Split only by courses defined in overrideSummaries and misc. classes.'
)]
[switch]$splitByOverrides,
[Parameter(ParameterSetName = 'OutputControl')]
[switch]$outAllFormats,
[ValidateNotNullOrEmpty()]
[string]$cookie,
[ValidateNotNullOrEmpty()]
[string]$tenantId
)
if ($splitBySummaries -and -not $overrideSummaries) {
throw 'The parameter splitBySummaries requires the parameter overrideSummaries to be set.'
}
if ($outAllFormats) {
$splitByCourse = $true
}
# Convert any string inputs to DateTime objects
$dates = $dates | ForEach-Object {
if ($_ -is [string]) { [datetime]::Parse($_) } else { $_ }
}
function Get-SingleElement {
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[System.Object[]]$collection
)
process {
if ($collection.Length -eq 0) {
throw [System.InvalidOperationException]::new("No elements match the predicate. Call stack: $((Get-PSCallStack | Out-String).Trim())")
} elseif ($collection.Length -gt 1) {
throw [System.InvalidOperationException]::new("More than one element matches the predicate. Call stack: $((Get-PSCallStack | Out-String).Trim())")
}
return $collection[0]
}
}
# Function to calculate the week start date (Monday) for a given date
function Get-WeekStartDate($date) {
$offset = ($date.DayOfWeek.value__ + 6) % 7
return $date.Date.AddDays(-$offset)
}
$headers = @{
'authority' = "$baseUrl"
'accept' = 'application/json'
'accept-encoding' = 'gzip, deflate, br, zstd'
'accept-language' = 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
'cache-control' = 'max-age=0'
'dnt' = '1'
'pragma' = 'no-cache'
'priority' = 'u=0, i'
'sec-ch-ua' = "`"Google Chrome`";v=`"131`", `"Chromium`";v=`"131`", `"Not_A Brand`";v=`"24`""
'sec-ch-ua-mobile' = '?0'
'sec-ch-ua-platform' = "`"Windows`""
'sec-fetch-dest' = 'document'
'sec-fetch-mode' = 'navigate'
'sec-fetch-site' = 'none'
'sec-fetch-user' = '?1'
'upgrade-insecure-requests' = '1'
}
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$session.UserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
$session.Cookies.Add((New-Object System.Net.Cookie('schoolname', "`"$cookie`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('Tenant-Id', "`"$tenantId`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('schoolname', "`"$cookie==`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('Tenant-Id', "`"$tenantId`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('schoolname', "`"$cookie==`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('Tenant-Id', "`"$tenantId`"", '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('traceId', '9de4710537aa097594b039ee3a591cfc22a6dd99', '/', "$baseUrl")))
$session.Cookies.Add((New-Object System.Net.Cookie('JSESSIONID', 'B9ED9B2D36BE7D25A7A9EF21E8144D3F', '/', "$baseUrl")))
$periods = [System.Collections.Generic.List[PeriodEntry]]::new()
$courses = [System.Collections.Generic.List[Course]]::new()
$rooms = [System.Collections.Generic.List[Room]]::new()
$legende = [System.Collections.Generic.List[PeriodTableEntry]]::new();
# Check whether the current date is in Daylight Saving Time
$isDaylightSavingTime = (Get-Date).IsDaylightSavingTime()
foreach ($date in $dates) {
Write-Verbose "Getting Data for week of $($date.ToString('yyyy-MM-dd'))"
$url = "https://$baseUrl/WebUntis/api/public/timetable/weekly/data?elementType=$elementType&elementId=$elementId&date=$($date.ToString('yyyy-MM-dd'))&formatId=14"
$response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Get -WebSession $session -Headers $headers
$object = $response | ConvertFrom-Json -ErrorAction Stop
$class = [PeriodTableEntry]
try {
$object.data.result.data.elements | ForEach-Object {
if ($legende.FindAll({ param($e) $e.id -eq $_.id -and $e.type -eq $_.type }).Count -eq 0) {
# prevent duplicates
$legende.Add([PeriodTableEntry]::new($_))
}
}
$legende | Where-Object { $_.type -eq 4 } | ForEach-Object {
if ($rooms.FindAll({ param($e) $e.id -eq $_.id }).Count -eq 0) {
# prevent duplicates
$rooms.Add([Room]::new($_))
}
}
$legende | Where-Object { $_.type -eq 3 } | ForEach-Object {
if ($courses.FindAll({ param($e) $e.id -eq $_.id }).Count -eq 0) {
# prevent duplicates
if ($overrideSummaries) {
if ($overrideSummaries.Contains($_.name)) {
$_.longName = $overrideSummaries[$_.name]
}
}
$courses.Add([Course]::new($_))
}
}
$class = ($legende.Where({ $_.id -eq $elementId }) | Get-SingleElement)
$class = [PSCustomObject]@{
name = $class.name
longName = $class.longName
displayname = $class.displayname
alternatename = $class.alternatename
backColor = $class.backColor
}
$object.data.result.data.elementPeriods.$elementId | ForEach-Object {
try {
$element = $_
$periods.Add([PeriodEntry]::new($_, $rooms, $courses))
} catch {
#[FormatException] {
Write-Error ($element | Format-List | Out-String)
throw
}
}
} catch [FormatException] {
Write-Error 'Invalid Response regarding datetime format:'
throw
exit 1
}
}
$periods = $periods | Sort-Object -Property startTime
if (-not $dontCreateMultiDayEvents) {
# Add WeekStartDate property to each period
$periods | ForEach-Object {
$_ | Add-Member -NotePropertyName WeekStartDate -NotePropertyValue (Get-WeekStartDate $_.startTime) -Force
}
# Group periods by WeekStartDate
$periodsGroupedByWeek = $periods | Group-Object -Property WeekStartDate
# Initialize an array to hold the new multi-day elements
$multiDayEvents = [System.Collections.Generic.List[PeriodEntry]]::new()
# Process each week group
foreach ($group in $periodsGroupedByWeek) {
$firstPeriod = $group.Group[0]
$lastPeriod = $group.Group[-1]
$culture = [System.Globalization.CultureInfo]::CurrentCulture
$calendar = $culture.Calendar
$weekOfYear = $calendar.GetWeekOfYear($firstPeriod.startTime, $culture.DateTimeFormat.CalendarWeekRule, $culture.DateTimeFormat.FirstDayOfWeek)
do {
$id = [System.Math]::Abs([System.BitConverter]::ToInt32([System.Guid]::NewGuid().ToByteArray(), 0))
} while ($periods.Where({ $_.id -eq $id }).Count -ne 0)
# Create a new JSON object with necessary properties
$newJsonObject = [PSCustomObject]@{
id = $id
date = $firstPeriod.startTime.Date.ToString('yyyyMMdd')
startTime = $firstPeriod.startTime.ToString('hhmm')
endTime = $lastPeriod.endTime
location = ''
summary = "Calendar Week $weekOfYear" # FIXME: $period.course.course.longName is used for the summary...
substText = "for setting longer notifications after some weeks of absence`nRefreshed at $(Get-Date)"
lessonCode = 'SUMMARY'
cellstate = 'ADDITIONAL'
}
# Create the new PeriodEntry
$newElement = [PeriodEntry]::new($newJsonObject, $rooms, $courses)
# Add the new element to the array
$multiDayEvents.Add($newElement)
}
$periods = ($multiDayEvents + $periods)
}
foreach ($period in $group.Group) {
if ($isDaylightSavingTime) {
$period.startTime = $period.startTime.AddHours(-1)
$period.endTime = $period.endTime.AddHours(-1)
}
}
$existingPeriods = [System.Collections.Generic.List[PeriodEntry]]::new()
if ($appendToPreviousICSat) {
Write-Information "Appending to previous ICS file $appendToPreviousICSat"
$content = Get-Content $appendToPreviousICSat -Raw
$veventPattern = '(?s)BEGIN:VEVENT.*?END:VEVENT'
$existingEntries = [regex]::Matches($content, $veventPattern) | ForEach-Object { $_.Value }
foreach ($entry in $existingEntries) {
$previousIcsEvent = [IcsEvent]::new($entry)
if ($previousIcsEvent.Category -ne 'SUMMARY') {
$previousPeriod = [PeriodEntry]::new($previousIcsEvent, $rooms, $courses)
if ($periods.where({ $_.ID -eq $previousPeriod.ID }).Count -lt 1) {
$existingPeriods.Add($previousPeriod)
} else {
Write-Verbose "Skipping existing entry $($previousPeriod.ID) ($($previousPeriod.StartTime) - $($previousPeriod.EndTime))"
}
} else { Write-Verbose "Skipping SUMMARY entry $($previousIcsEvent.StartTime) - $($previousIcsEvent.EndTime)" }
}
$periods = ($existingPeriods + $periods)
}
if ($splitByCourse -and -not $splitByOverride) {
$tmpPeriods = $periods
$periods = $periods | Group-Object -Property { if (-not [string]::IsNullOrEmpty($_.course.course.name)) {
$_.course.course.name
} else {
$_.lessonCode
} }
if ($outAllFormats) {
$periods += ($tmpPeriods | Group-Object -Property { 'All' })
}
} elseif ($splitByOverride) {
$tmpPeriods = $periods
$periods = $periods | Group-Object -Property { if (-not [string]::IsNullOrEmpty($_.course.course.name)) {
Write-Verbose "Checking for override: $($_.course.course.name) $($overrideSummaries.Keys -contains $_.course.course.name)"
if ($overrideSummaries.Keys -contains $_.course.course.name) {
($overrideSummaries[$_.course.course.name] -split ',')[0]
} else {
'Misc'
}
} else {
$_.lessonCode
} }
if ($outAllFormats) {
$periods += ($tmpPeriods | Group-Object -Property { 'All' })
}
} else {
$periods = $periods | Group-Object -Property { 'All' }
}
foreach ($group in $periods) {
$calendarEntries = [System.Collections.Generic.List[IcsEvent]]::new()
# Iterate over each period and create calendar entries
foreach ($period in $group.Group) {
$calendarEntries.Add([IcsEvent]::new($period))
}
# Get all properties except StartTime and EndTime
$properties = $calendarEntries | Get-Member -MemberType Properties | Where-Object {
$_.Name -ne 'StartTime' -and $_.Name -ne 'EndTime' -and $_.Name -ne 'Description' -and $_.Name -ne 'UID' -and $_.Name -ne 'preExist'
} | Select-Object -ExpandProperty Name
if ($splitByCourse) {
Write-Host "ICS content for $($group.Name):`n========================"
}
# Use Select-Object to reorder properties and add calculated properties
$calendarEntries | Select-Object (@(
@{ Name = 'pre'; Expression = { if ($_.preExist) { '[X]' } else { '[ ]' } } },
@{ Name = 'StartTimeF'; Expression = { [DateTime]::ParseExact($_.StartTime, 'yyyyMMddTHHmmss', $null).ToString('dd.MM.yy HH:mm') } },
@{ Name = 'EndTimeF'; Expression = { [DateTime]::ParseExact($_.EndTime, 'yyyyMMddTHHmmss', $null).ToString('dd.MM.yy HH:mm') } }
) + $properties + @{
Name = 'DescriptionF';
Expression = {
$_.Description -replace '`n', ';; '
}
}
) | Format-Table -Wrap -AutoSize | Out-String -Width 4096
if ($splitByCourse) {
Write-Host "`n"
}
$IcsEntries = [System.Collections.Generic.List[string]]::new()
foreach ($icsEvent in $calendarEntries) {
$IcsEntries += $icsEvent.ToIcsEntry()
}
# Create the .ics file content
$icsContent = @"
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Chaos_02//WebUntisToIcs//EN
REFRESH-INTERVAL;VALUE=DURATION:PT3H
X-PUBLISHED-TTL:PT12H
X-WR-CALNAME:$(if (-not $splitByCourse) {$class.displayname} else {$class.displayname + " - $($group.Name)"})
BEGIN:VTIMEZONE
TZID:Europe/Berlin
BEGIN:STANDARD
DTSTART:19710101T030000
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:CET
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19710101T020000
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:CEST
END:DAYLIGHT
END:VTIMEZONE
$(($IcsEntries -join "`n"))
END:VCALENDAR
"@
try {
if ($OutputFilePath) {
# Write the .ics content to a file
if ($splitByCourse) {
if ($group.Name -ne 'All') {
$OutputPath = $OutputFilePath.Insert($OutputFilePath.LastIndexOf('.'), "_$($group.Name -replace '[^a-zA-Z0-9]', '_')")
} else {
$OutputPath = $OutputFilePath
}
} else {
$OutputPath = $OutputFilePath
}
Set-Content -Path $OutputPath -Value $icsContent
Write-Output "ICS file created at $((Get-Item -Path $OutputPath).FullName)"
} else {
# for writing the .ics content to a variable
Write-Output $icsContent
if (-not $splitByCourse) {
return $icsContent
} else {
# TODO: return after all period groups
}
}
} catch {
Write-Error "An error occurred while creating the ICS file: $_"
throw
}
}
####### Class definitions #######
class IcsEvent {
[string]$UID
[string]$StartTime
[string]$EndTime
[string]$Location
[string]$Summary
[string]$Description
[string]$Status
[string]$Category
[bool]$preExist = $false
IcsEvent([PeriodEntry]$period) {
$this.preExist = $period.preExist
$this.UID = $period.id
if ($period.lessonCode -ne 'SUMMARY') {
$this.startTime = ';TZID=Europe/Berlin:' + $period.startTime.ToString('yyyyMMddTHHmmss')
$this.endTime = ';TZID=Europe/Berlin:' + $period.endTime.ToString('yyyyMMddTHHmmss')
} else {
$this.startTime = ';VALUE=DATE:' + $period.startTime.ToString('yyyyMMdd')
$this.endTime = ';VALUE=DATE:' + $period.endTime.AddDays(1).ToString('yyyyMMdd')
}
$this.location = $period.room.room.longName
$this.summary = $period.course.course.longName
$this.description = $period.substText
if ($null -ne $period.rescheduleInfo) {
$this.description += "`nReschedule:`n" + $period.rescheduleInfo.ToString()
}
$this.status = switch ($period.cellState) {
'STANDARD' { 'CONFIRMED' }
'ADDITIONAL' { 'TENTATIVE' }
'CANCEL' { 'CANCELLED' }
'CONFIRMED' { $_ }
'TENTATIVE' { $_ }
'CANCELLED' { $_ }
default { 'CONFIRMED' }
}
$this.category = switch ($period.lessonCode) {
'UNTIS_ADDITIONAL' { 'Additional' }
default { $_ }
}
}
IcsEvent([string]$icsText) {
if ($icsText -notmatch 'BEGIN:VEVENT' -or ($icsText -match 'BEGIN:VEVENT' -and ($icsText -match 'BEGIN:VEVENT.*BEGIN:VEVENT'))) {
throw 'Invalid Syntax in ICS entry. Only one VEVENT element is allowed.'
}
if ($icsText -notmatch 'END:VEVENT' -or ($icsText -match 'END:VEVENT' -and ($icsText -match 'END:VEVENT.*END:VEVENT'))) {
throw 'Invalid Syntax in ICS entry. Only one VEVENT element is allowed.'
}
$this.preExist = $true
if ($icsText -match 'UID:(.*)') { $this.UID = $matches[1].Trim() } else { throw 'UID not found in ICS entry.' }
if ($icsText -match 'DTSTART;(?:TZID=.*|VALUE=DATE):(.*)') { $this.StartTime = $matches[1].Trim() } else { throw 'StartTime not found in ICS entry.' }
if ($icsText -match 'DTEND;(?:TZID=.*|VALUE=DATE):(.*)') { $this.EndTime = $matches[1].Trim() } else { throw 'EndTime not found in ICS entry.' }
if ($icsText -match 'LOCATION:(.*)') { $this.Location = $matches[1].Trim() } else { throw 'Location not found in ICS entry.' }
if ($icsText -match 'SUMMARY:(.*)') { $this.Summary = $matches[1].Trim() } else { throw 'Summary not found in ICS entry.' }
if ($icsText -match 'DESCRIPTION:(.*)') { $this.Description = $matches[1].Trim() } else { throw 'Description not found in ICS entry.' }
if ($icsText -match 'STATUS:(.*)') { $this.Status = $matches[1].Trim() } else { throw 'Status not found in ICS entry.' }
if ($icsText -match 'CATEGORIES:(.*)') { $this.Category = $matches[1].Trim() } else { throw 'Category not found in ICS entry.' }
}
[string] ToIcsEntry() {
return @"
BEGIN:VEVENT
UID:$($this.UID)
DTSTART$($this.StartTime)
DTEND$($this.EndTime)
LOCATION:$($this.Location)
SUMMARY:$($this.Summary)
DESCRIPTION:$($this.Description)
STATUS:$($this.Status)
CATEGORIES:$($this.Category)
END:VEVENT
"@
}
}
class rescheduleInfo {
[datetime]$startTime
[datetime]$endTime
[bool]$isSource
[datetime] date() {
return $this.startTime.Date
}
rescheduleInfo([PSCustomObject]$jsonObject) {
$this.startTime = [datetime]::ParseExact($jsonObject.date.ToString(), 'yyyyMMdd', $null).Add([timespan]::ParseExact($jsonObject.startTime.ToString().PadLeft(4, '0'), 'hhmm', $null))
$this.endTime = $this.date().Add([timespan]::ParseExact($jsonObject.endTime.ToString().PadLeft(4, '0'), 'hhmm', $null))
$this.isSource = $jsonObject.isSource
}
[string] ToString() {
return "Start Time: $($this.startTime), End Time: $($this.endTime), Is Source: $($this.isSource)"
}
}
class PeriodEntry {
[int]$id
[int]$lessonId
[int]$lessonNumber
[string]$lessonCode
[string]$lessonText
[string]$periodText
[bool]$hasPeriodText
[string]$periodInfo
[array]$periodAttachments
[string]$substText
[datetime]$startTime
[datetime]$endTime
[RoomEntry]$room
[CourseEntry]$course
[string]$studentGroup
[int]$code
[string]$cellState
[int]$priority
[bool]$isStandard
[bool]$isCancelled
[bool]$isEvent
[rescheduleInfo]$rescheduleInfo
[int]$roomCapacity
[int]$studentCount
[bool]$preExist = $false
[datetime] date() {
return $this.startTime.Date
}
PeriodEntry([PSCustomObject]$jsonObject, [System.Collections.Generic.List[Room]]$rooms, [System.Collections.Generic.List[Course]]$courses) {
$this.id = $jsonObject.id
$this.lessonId = $jsonObject.lessonId
$this.lessonNumber = $jsonObject.lessonNumber
$this.lessonCode = $jsonObject.lessonCode
$this.lessonText = $jsonObject.lessonText
$this.periodText = $jsonObject.periodText
$this.hasPeriodText = $jsonObject.hasPeriodText
$this.periodInfo = $jsonObject.periodInfo
$this.periodAttachments = $jsonObject.periodAttachments
$this.substText = $jsonObject.substText
$this.startTime = [datetime]::ParseExact($jsonObject.date.ToString(), 'yyyyMMdd', $null).Add([timespan]::ParseExact($jsonObject.startTime.ToString().PadLeft(4, '0'), 'hhmm', $null))
if ($jsonObject.endTime -is [DateTime]) {
$this.endTime = $jsonObject.endTime
} else {
$this.endTime = $this.date().Add([timespan]::ParseExact($jsonObject.endTime.ToString().PadLeft(4, '0'), 'hhmm', $null))
}
$this.room = [RoomEntry]::new(($jsonObject.elements | Where-Object { $_.type -eq 4 } | Get-SingleElement), $rooms)
$this.course = [CourseEntry]::new(($jsonObject.elements | Where-Object { $_.type -eq 3 } | Get-SingleElement), $courses)
$this.studentGroup = $jsonObject.studentGroup
$this.code = $jsonObject.code
$this.cellState = $jsonObject.cellState
$this.priority = $jsonObject.priority
$this.isCancelled = $jsonObject.is.cancelled
$this.isStandard = $jsonObject.is.standard
$this.isEvent = $jsonObject.is.event
if ($null -ne $jsonObject.rescheduleInfo) {
$this.rescheduleInfo = [rescheduleInfo]::new($jsonObject.rescheduleInfo)
} else {
$this.rescheduleInfo = $null
}
$this.roomCapacity = $jsonObject.roomCapacity
$this.studentCount = $jsonObject.studentCount
}
PeriodEntry([IcsEvent]$icsEvent, [System.Collections.Generic.List[Room]]$rooms, [System.Collections.Generic.List[Course]]$courses) {
$this.preExist = $true
$this.id = $icsEvent.UID
$this.course = [CourseEntry]::new(($courses.Where({ $_.longName -eq $icsEvent.Summary }) | Get-SingleElement))
$this.room = [RoomEntry]::new(($rooms.Where({ $_.longName -eq $icsEvent.Location }) | Get-SingleElement))
$this.lessonCode = $icsEvent.Category
$this.substText = $icsEvent.Description
$this.cellState = $icsEvent.Status
try {
$this.startTime = [datetime]::ParseExact($icsEvent.StartTime, 'yyyyMMddTHHmmss', $null)
$this.endTime = [datetime]::ParseExact($icsEvent.EndTime, 'yyyyMMddTHHmmss', $null)
} catch {
$this.startTime = [datetime]::ParseExact($icsEvent.StartTime, 'yyyyMMdd', $null)
$this.endTime = [datetime]::ParseExact($icsEvent.EndTime, 'yyyyMMdd', $null)
}
#[datetime]::ParseExact($icsEvent.StartTime, "yyyyMMdd", $null)
#[datetime]::ParseExact($icsEvent.StartTime, @("yyyyMMddTHHmmss", "yyyyMMdd
}
[string] ToString() {
return "ID: $($this.id), Lesson ID: $($this.lessonId), Lesson Number: $($this.lessonNumber), Lesson Code: $($this.lessonCode), Lesson Text: $($this.lessonText), Period Text: $($this.periodText), Has Period Text: $($this.hasPeriodText), Period Info: $($this.periodInfo), Period Attachments: $($this.periodAttachments), Subst Text: $($this.substText), Date: $($this.date), Start Time: $($this.startTime), End Time: $($this.endTime), Elements: $($this.elements), Student Group: $($this.studentGroup), Code: $($this.code), Cell State: $($this.cellState), Priority: $($this.priority), Is Standard: $($this.isStandard), Is Event: $($this.isEvent), Room Capacity: $($this.roomCapacity), Student Count: $($this.studentCount)"
}
}
class RoomEntry {
[Room]$room
[int]$orgId
[bool]$missing
[string]$state
RoomEntry([PSCustomObject]$jsonObject, [System.Collections.Generic.List[Room]]$rooms) {
Write-Debug "RoomEntry: $($jsonObject)"
$problemObject = $jsonObject
$tmp = $rooms | Where-Object { $_.id -eq $jsonObject.id } | Get-SingleElement
$this.room = $tmp
$this.orgId = $jsonObject.orgId
$this.missing = $jsonObject.missing
$this.state = $jsonObject.state
}
RoomEntry([Room]$room) {
$this.room = $room
$this.orgId = $null
$this.missing = $null
$this.state = $null
}
}
class Room {
[int]$id
[string]$name
[string]$longName
[string]$displayname
[string]$alternatename
[int]$roomCapacity
Room([PeriodTableEntry]$legende) {
if ($legende.type -ne 4) {
throw [System.ArgumentException]::new('The provided object is not a room.')
}
$this.id = $legende.id
$this.name = $legende.name
$this.longName = $legende.longName
$this.displayname = $legende.displayname
$this.alternatename = $legende.alternatename
$this.roomCapacity = $legende.roomCapacity
}
}
class CourseEntry {
[Course]$course
[int]$orgId
[bool]$missing
[string]$state
CourseEntry([PSCustomObject]$jsonObject, [System.Collections.Generic.List[Course]]$courses) {
$this.course = $courses | Where-Object { $_.id -eq $jsonObject.id } | Get-SingleElement
$this.orgId = $jsonObject.orgId
$this.missing = $jsonObject.missing
$this.state = $jsonObject.state
}
CourseEntry([Course]$course) {
$this.course = $course
$this.orgId = $null
$this.missing = $null
$this.state = $null
}
}
class Course {
[int]$id
[string]$name
[string]$longName
[string]$displayname
[string]$alternatename
[int]$courseCapacity
Course([PeriodTableEntry]$legende) {
if ($legende.type -ne 3) {
throw [System.ArgumentException]::new('The provided object is not a course.')
}
$this.id = $legende.id
$this.name = $legende.name
$this.longName = $legende.longName
$this.displayname = $legende.displayname
$this.alternatename = $legende.alternatename
$this.courseCapacity = $legende.courseCapacity
}
}
class PeriodTableEntry {
[int]$type
[int]$id
[string]$name
[string]$longName
[string]$displayname
[string]$alternatename
[string]$backColor
[bool]$canViewTimetable
[int]$roomCapacity
PeriodTableEntry([PSCustomObject]$jsonObject) {
$this.type = $jsonObject.type
$this.id = $jsonObject.id
$this.name = $jsonObject.name
$this.longName = $jsonObject.longName
$this.displayname = $jsonObject.displayname
$this.alternatename = $jsonObject.alternatename
$this.backColor = $jsonObject.backColor
$this.canViewTimetable = $jsonObject.canViewTimetable
$this.roomCapacity = $jsonObject.roomCapacity
}
[string] ToString() {
return "Type: $($this.type), ID: $($this.id), Name: $($this.name), Long Name: $($this.longName), Display Name: $($this.displayname), Alternate Name: $($this.alternatename), Back Color: $($this.backColor), Can View Timetable: $($this.canViewTimetable), Room Capacity: $($this.roomCapacity)"
}
}