-
Notifications
You must be signed in to change notification settings - Fork 45
/
common.ts
166 lines (143 loc) Β· 4.99 KB
/
common.ts
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
import RRule from 'rrule';
export interface IcalOutput {
[key: string]: string | string[] | IcalOutput[];
}
function cleanIcalKey(key: string): string {
if (key.startsWith('DTSTART')) return 'DTSTART';
if (key.startsWith('DTEND')) return 'DTEND';
return key;
}
/**
* Checks to see if the given date is observing daylight savings time.
* @param date The date to be checked
* @returns true if the date observes daylight savings time, false otherwise.
* @see https://stackoverflow.com/a/30280636
*/
function checkDateObservesDST(date: Date): boolean {
const jan = new Date(date.getFullYear(), 0, 1);
const jul = new Date(date.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()) > date.getTimezoneOffset();
}
/**
* The code in this function is derived from
* https://github.com/adrianlee44/ical2json.
* @param source The raw calendar data in ICAL format.
* @returns The parsed ICAL data.
*/
export function parseRawIcal(source: string): IcalOutput {
const output: IcalOutput = {};
const lines = source.split(/\r\n|\n|\r/);
const parents: IcalOutput[] = [];
let parent: IcalOutput = {};
let current: IcalOutput = output;
let currentKey = '';
for (const line of lines) {
let currentValue = '';
if (line.charAt(0) === ' ') {
current[currentKey] += line.substr(1);
} else {
const splitAt = line.indexOf(':');
if (splitAt < 0) {
continue;
}
currentKey = cleanIcalKey(line.substr(0, splitAt));
currentValue = line.substr(splitAt + 1);
switch (currentKey) {
case 'BEGIN': {
parents.push(parent);
parent = current;
if (parent[currentValue] == null) {
parent[currentValue] = [];
}
// Create a new object, store the reference for future uses.
current = {};
(parent[currentValue] as IcalOutput[]).push(current);
break;
}
case 'END': {
current = parent;
parent = parents.pop() as IcalOutput;
break;
}
default: {
if (current[currentKey]) {
if (!Array.isArray(current[currentKey])) {
current[currentKey] = [current[currentKey]] as string[];
}
(current[currentKey] as string[]).push(currentValue);
} else {
(current[currentKey] as string) = currentValue;
}
}
}
}
}
return output;
}
/**
* This function parses the raw ICAL datetime string into a Date object.
* @param datetime Example: October 31st, 2021 = "20211031T000000"
* @returns The parsed Date object.
*/
function parseRawIcalDatetime(datetime: string): Date {
const fullYear = datetime.slice(0, 4);
const month = datetime.slice(4, 6);
const day = datetime.slice(6, 8);
const hours = datetime.slice(9, 11);
const minutes = datetime.slice(11, 13);
const seconds = datetime.slice(13, 15);
const date = new Date();
date.setFullYear(Number(fullYear), Number(month) - 1, Number(day));
// The timezone determines how many hours the date is relative of UTC.
const observingDST = checkDateObservesDST(date);
const tzHoursOffset = observingDST ? -7 : -8; // PST
date.setHours(Number(hours) + tzHoursOffset, Number(minutes), Number(seconds));
return date;
}
export function computeIcalDatetime(event: IcalOutput): Date {
const rawDatetime = event['DTSTART'];
const rawRrule = event['RRULE'];
if (rawRrule !== undefined) {
try {
const ruleSrc = `DTSTART:${rawDatetime}Z\nRRULE:${rawRrule}`;
const recurrence = RRule.fromString(ruleSrc);
const date = recurrence.after(new Date());
date.setHours(date.getHours());
return date;
// eslint-disable-next-line no-empty
} catch {}
}
return parseRawIcalDatetime(rawDatetime as string);
}
export function slugifyEvent(summary: string, month: string, day: number): string {
const cleanedSummary = summary.replace(/[^\w\s_]/g, '').replace(/(\s|-|_)+/g, '-');
const slug = [cleanedSummary, month, day].join('-').toLowerCase();
return slug;
}
export function checkForRecurrence(raw?: string): boolean {
if (raw === undefined) return false;
try {
const recurrence = RRule.fromString(raw);
return recurrence.isFullyConvertibleToText();
// eslint-disable-next-line no-empty
} catch {}
return false;
}
export function parseDescription(content: string): Record<string, string> {
const result = {};
for (const line of content.split('\n')) {
const [key, value] = line.split('=');
result[key.trim()] = value;
}
return result;
}
export function sortByDate(): (a: { date: Date }, b: { date: Date }) => 1 | -1 {
return ({ date: date1 }, { date: date2 }) => (date1.valueOf() > date2.valueOf() ? 1 : -1);
}
export function filterIfPassed(now: number, offset = 0) {
return ({ date }: { date: Date }): boolean => date.valueOf() + offset > now;
}
export function cleanSummary(summary?: string): string {
if (summary === undefined) return 'Unnamed Event';
return summary.replace(/\\/g, '');
}