-
Notifications
You must be signed in to change notification settings - Fork 9
#4232 import external calendar availability #4258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
staysgt
wants to merge
8
commits into
develop
Choose a base branch
from
#4232-import-gcal-availability
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bbbccca
#4232 import gcal availability
staysgt 7f2c5fc
#4232 import gcal availailability
staysgt 3788a90
Merge branch 'develop' into #4232-import-gcal-availability
staysgt 33f4c9d
#4232 fix test data
staysgt 974bbb9
#4232 fixes
staysgt e6d6866
#4232 fix lint
staysgt ac51b15
#4232 encrypt and add type to ics utils
staysgt ab48160
#4232 prettier
staysgt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletions
2
src/backend/src/prisma/migrations/20260602212459_import_ics_url/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| -- AlterTable | ||
| ALTER TABLE "Schedule_Settings" ADD COLUMN "importedIcsCalendarUrl" TEXT NOT NULL DEFAULT ''; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,7 @@ | ||
| import ical, { ICalEventStatus } from 'ical-generator'; | ||
| import { Event, wbsPipe } from 'shared'; | ||
| import nodeIcal, { CalendarComponent, VEvent } from 'node-ical'; | ||
| import { IcsBusyInterval, Event, wbsPipe } from 'shared'; | ||
| import { HttpException } from './errors.utils.js'; | ||
|
|
||
| export const generateIcsFeed = (events: Event[]): string => { | ||
| const cal = ical({ name: 'Northeastern Electric Racing' }); | ||
|
|
@@ -41,3 +43,171 @@ export const generateIcsFeed = (events: Event[]): string => { | |
|
|
||
| return cal.toString(); | ||
| }; | ||
|
|
||
| // checks if a given host is blocked (used to mitigate ssrf attacks) | ||
| const isBlockedHost = (host: string): boolean => { | ||
|
staysgt marked this conversation as resolved.
|
||
| const h = host.toLowerCase(); | ||
| return ( | ||
| h === 'localhost' || | ||
| h === '127.0.0.1' || | ||
| h === '0.0.0.0' || | ||
| h === '::1' || | ||
| h.endsWith('.local') || | ||
| /^10\./.test(h) || | ||
| /^192\.168\./.test(h) || | ||
| /^172\.(1[6-9]|2\d|3[0-1])\./.test(h) || | ||
| /^169\.254\./.test(h) || | ||
| h.startsWith('::ffff:') || | ||
| /^fe80:/i.test(h) || | ||
| /^fc[0-9a-f]{2}:/i.test(h) || | ||
| /^fd[0-9a-f]{2}:/i.test(h) | ||
| ); | ||
| }; | ||
|
|
||
| // checks if a give ics url is valid, throws if invalid | ||
| export const validateIcsUrl = (url: string): URL => { | ||
| let parsed: URL; | ||
| try { | ||
| parsed = new URL(url); | ||
| } catch { | ||
| throw new HttpException(400, 'Invalid ICS URL'); | ||
| } | ||
|
|
||
| if (parsed.protocol === 'webcal:') parsed.protocol = 'https:'; | ||
| if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { | ||
| throw new HttpException(400, 'ICS URL must use http or https'); | ||
| } | ||
| if (isBlockedHost(parsed.hostname)) { | ||
| throw new HttpException(400, 'ICS URL host is not allowed'); | ||
| } | ||
| return parsed; | ||
| }; | ||
|
|
||
| // fetches the text from the ics url | ||
| const fetchIcsText = async (url: URL): Promise<string> => { | ||
| // timeout after 10,000 ms | ||
| const fetchTimeoutMs = 10000; | ||
| const controller = new AbortController(); | ||
| const timeout = setTimeout(() => controller.abort(), fetchTimeoutMs); | ||
| try { | ||
| const res = await fetch(url, { signal: controller.signal, redirect: 'error' }); | ||
| if (!res.ok) throw new HttpException(502, `Failed to fetch ICS feed (status ${res.status})`); | ||
| return await res.text(); | ||
| } catch (err) { | ||
| if (err instanceof HttpException) throw err; | ||
| if (err instanceof Error && err.name === 'AbortError') { | ||
| throw new HttpException(504, 'ICS feed fetch timed out'); | ||
| } | ||
| throw new HttpException(502, 'Failed to fetch ICS feed'); | ||
| } finally { | ||
| clearTimeout(timeout); | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Fetches an ICS calendar feed and returns busy intervals overlapping [rangeStart, rangeEnd). | ||
| * Expands RRULE recurrences, applies EXDATE exclusions, and honors per-occurrence overrides | ||
| * (RECURRENCE-ID). Skips events marked CANCELLED or TRANSPARENT (free). | ||
| */ | ||
| export const fetchIcsBusyTimes = async (url: string, rangeStart: Date, rangeEnd: Date): Promise<IcsBusyInterval[]> => { | ||
| const validUrl = validateIcsUrl(url); | ||
| const icsText = await fetchIcsText(validUrl); | ||
|
|
||
| let parsed: Record<string, CalendarComponent | undefined>; | ||
| try { | ||
| parsed = nodeIcal.sync.parseICS(icsText); | ||
| } catch { | ||
| throw new HttpException(400, 'ICS feed could not be parsed'); | ||
| } | ||
|
|
||
| const busy: IcsBusyInterval[] = []; | ||
|
|
||
| for (const component of Object.values(parsed)) { | ||
| if (!component || component.type !== 'VEVENT') continue; | ||
| const ev = component as VEvent; | ||
|
|
||
| if (ev.status === 'CANCELLED') continue; | ||
| if ((ev as unknown as { transparency?: string }).transparency === 'TRANSPARENT') continue; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. there are a ton of unknowns in this file, can you make them have a type |
||
|
|
||
| const baseStart = ev.start as Date | undefined; | ||
| const baseEnd = ev.end as Date | undefined; | ||
| if (!baseStart || !baseEnd) continue; | ||
|
|
||
| const { rrule } = ev as unknown as { rrule?: { between: (a: Date, b: Date, inc: boolean) => Date[] } }; | ||
|
|
||
| if (!rrule) { | ||
| if (baseEnd > rangeStart && baseStart < rangeEnd) { | ||
| busy.push({ start: baseStart, end: baseEnd }); | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| const durationMs = baseEnd.getTime() - baseStart.getTime(); | ||
| const occurrences = rrule.between(rangeStart, rangeEnd, true); | ||
|
|
||
| const exdateMap = (ev as unknown as { exdate?: Record<string, Date> }).exdate ?? {}; | ||
| const exdateTimes = new Set<number>(Object.values(exdateMap).map((d) => d.getTime())); | ||
|
|
||
| const recurrenceMap = (ev as unknown as { recurrences?: Record<string, VEvent> }).recurrences ?? {}; | ||
| const recurrencesByTime = new Map<number, VEvent>(); | ||
| for (const override of Object.values(recurrenceMap)) { | ||
| const recId = (override as unknown as { recurrenceid?: Date }).recurrenceid ?? (override.start as Date); | ||
| if (recId) recurrencesByTime.set(recId.getTime(), override); | ||
| } | ||
|
|
||
| for (const occ of occurrences) { | ||
| const occTime = occ.getTime(); | ||
| if (exdateTimes.has(occTime)) continue; | ||
|
|
||
| const override = recurrencesByTime.get(occTime); | ||
| if (override) { | ||
| if (override.status === 'CANCELLED') continue; | ||
| const oStart = override.start as Date | undefined; | ||
| const oEnd = override.end as Date | undefined; | ||
| if (oStart && oEnd && oEnd > rangeStart && oStart < rangeEnd) { | ||
| busy.push({ start: oStart, end: oEnd }); | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| const occEnd = new Date(occTime + durationMs); | ||
| if (occEnd > rangeStart && occ < rangeEnd) { | ||
| busy.push({ start: occ, end: occEnd }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return busy; | ||
| }; | ||
|
|
||
| // converts ics date to utc midnight for that day | ||
| export const localDayStartForDateSet = (dateSet: Date | string): Date => { | ||
| const date = new Date(dateSet); | ||
| return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); | ||
| }; | ||
|
|
||
| // converts the ics busy intervals into availability slots (0-11) | ||
| export const busyIntervalsToSlots = (busy: IcsBusyInterval[], dateSet: Date | string): Set<number> => { | ||
| const dayStart = localDayStartForDateSet(dateSet); | ||
| const busySlots = new Set<number>(); | ||
|
|
||
| const availabilityStart = 10; | ||
| const numAvailabilitySlots = 12; | ||
|
|
||
| for (let slot = 0; slot < numAvailabilitySlots; slot++) { | ||
| const slotStart = new Date(dayStart); | ||
| slotStart.setHours(availabilityStart + slot, 0, 0, 0); | ||
| const slotEnd = new Date(slotStart); | ||
| slotEnd.setHours(slotEnd.getHours() + 1); | ||
|
|
||
| if (busy.some((interval) => interval.start < slotEnd && interval.end > slotStart)) { | ||
| busySlots.add(slot); | ||
| } | ||
| } | ||
|
|
||
| return busySlots; | ||
| }; | ||
|
|
||
| // returns given availability with ics busy slots removed | ||
| export const removeBusySlotsFromAvailability = (availability: number[], busySlots: Set<number>): number[] => | ||
| availability.filter((slot) => !busySlots.has(slot)); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.