Skip to content
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

Add exporting to .ics #22

Merged
merged 3 commits into from
Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@types/react": "^17.0.48",
"@types/react-dom": "^17.0.17",
"html-entities": "^2.3.3",
"ics": "^2.41.0",
"msgpack-lite": "^0.1.26",
"nanoid": "^3.3.4",
"react": "^18.2.0",
Expand Down
8 changes: 5 additions & 3 deletions src/components/Footers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useRef, useState } from "react";

import { COLOR_SCHEME_PRESETS } from "../lib/colors";
import { State } from "../lib/state";
import { useCalendarExport } from "../lib/gapi";
import { useICSExport } from "../lib/gapi";
import { DEFAULT_PREFERENCES, Preferences } from "../lib/schema";

function PreferencesModal(props: {
Expand Down Expand Up @@ -145,8 +145,7 @@ export function LeftFooter(props: {

const [isExporting, setIsExporting] = useState(false);
// TODO: fix gcal export
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const onCalendarExport = useCalendarExport(
const onICSExport = useICSExport(
state,
() => setIsExporting(false),
() => setIsExporting(false)
Expand Down Expand Up @@ -176,6 +175,9 @@ export function LeftFooter(props: {
<Image src="img/calendar-button.png" alt="Sign in with Google" />
)}
</Tooltip>
<Button onClick={onICSExport}>
{isExporting ? <Spinner m={3} /> : "Generate .ics file"}
</Button>
</Flex>
<Text>Last updated: {state.lastUpdated}.</Text>
<Flex gap={4}>
Expand Down
84 changes: 81 additions & 3 deletions src/lib/gapi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useGoogleLogin } from "@react-oauth/google";
import { EventAttributes, DateArray, createEvents } from "ics";

import { Activity } from "./activity";
import { CALENDAR_COLOR } from "./colors";
Expand Down Expand Up @@ -26,6 +27,34 @@ function toISOString(date: Date): string {
].join("");
}

/** Returns a date as a UTC date array */
function toDateArray(date: Date): DateArray {
return [
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
];
}

/** Downloads a file with the given text data */
function download(filename: string, text: string) {
var element = document.createElement("a");
element.setAttribute(
"href",
"data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
element.setAttribute("download", filename);

element.style.display = "none";
document.body.appendChild(element);

element.click();

document.body.removeChild(element);
}

/** Returns a date as an RRULE string without a timezone. */
function toRRuleString(date: Date): string {
return Array.from(toISOString(date))
Expand All @@ -34,7 +63,7 @@ function toRRuleString(date: Date): string {
}

/** Return a list of events for an activity that happen on a given term. */
function toEvents(
function toGoogleCalendarEvents(
activity: Activity,
term: Term
): Array<gapi.client.calendar.Event> {
Expand All @@ -61,8 +90,35 @@ function toEvents(
);
}

function toICSEvents(activity: Activity, term: Term): Array<EventAttributes> {
return activity.events.flatMap((event) =>
event.slots.map((slot) => {
const startDate = term.startDateFor(slot.startSlot);
const startDateEnd = term.startDateFor(slot.endSlot);
const endDate = term.endDateFor(slot.startSlot);
const exDates = term.exDatesFor(slot.startSlot);
const rDate = term.rDateFor(slot.startSlot);
console.log(event.name, startDate);
return {
title: event.name,
location: event.room,
start: toDateArray(startDate),
startInputType: "utc",
end: toDateArray(startDateEnd),
endInputType: "utc",
recurrenceRule: [
// for some reason, gcal wants UNTIL to be a date, not time
`FREQ=WEEKLY;UNTIL=${toRRuleString(endDate).split("T")[0]}`,
`EXDATE;TZID=${TIMEZONE}:${exDates.map(toRRuleString).join(",")}`,
rDate && `RDATE;TZID=${TIMEZONE}:${toRRuleString(rDate)}`,
].filter((t): t is string => t !== undefined)[0],
};
})
);
}

/** Hook that returns an export calendar function. */
export function useCalendarExport(
export function useGoogleCalendarExport(
state: State,
onSuccess?: () => void,
onError?: () => void
Expand Down Expand Up @@ -93,7 +149,7 @@ export function useCalendarExport(
const addCalendarEvents = async (calendarId: string) => {
const batch = gapi.client.newBatch();
state.selectedActivities
.flatMap((activity) => toEvents(activity, state.term))
.flatMap((activity) => toGoogleCalendarEvents(activity, state.term))
.forEach((resource) =>
batch.add(
gapi.client.calendar.events.insert({
Expand Down Expand Up @@ -128,3 +184,25 @@ export function useCalendarExport(

return onCalendarExport;
}

export function useICSExport(
state: State,
onSuccess?: () => void,
onError?: () => void
): () => void {
return async () => {
const events = state.selectedActivities.flatMap((activity) =>
toICSEvents(activity, state.term)
);
const calendarName = `Hydrant: ${state.term.niceName}`;
events.forEach((event) => {
event.calName = calendarName;
});
console.log(events);
createEvents(events, (error, value) => {
if (error) onError?.();
download(`${state.term.urlName}.ics`, value);
onSuccess?.();
});
};
}