forked from jens-maus/node-ical
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathical.js
More file actions
559 lines (480 loc) · 18.5 KB
/
ical.js
File metadata and controls
559 lines (480 loc) · 18.5 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
/* eslint-disable max-depth, max-params, no-warning-comments */
const uuid = require('uuid/v4');
const moment = require('moment-timezone');
const rrule = require('rrule').RRule;
/** **************
* A tolerant, minimal icalendar parser
* (http://tools.ietf.org/html/rfc5545)
*
* <peterbraden@peterbraden.co.uk>
* ************* */
// Unescape Text re RFC 4.3.11
const text = function (t) {
t = t || '';
return t
.replace(/\\,/g, ',')
.replace(/\\;/g, ';')
.replace(/\\[nN]/g, '\n')
.replace(/\\\\/g, '\\');
};
const parseValue = function (val) {
if (val === 'TRUE') {
return true;
}
if (val === 'FALSE') {
return false;
}
const number = Number(val);
if (!isNaN(number)) {
return number;
}
return val;
};
const parseParams = function (p) {
const out = {};
for (let i = 0; i < p.length; i++) {
if (p[i].indexOf('=') > -1) {
const segs = p[i].split('=');
out[segs[0]] = parseValue(segs.slice(1).join('='));
}
}
// Sp is not defined in this scope, typo?
// original code from peterbraden
// return out || sp;
return out;
};
const storeValParam = function (name) {
return function (val, curr) {
const current = curr[name];
if (Array.isArray(current)) {
current.push(val);
return curr;
}
if (typeof (current) === 'undefined') {
curr[name] = val;
} else {
curr[name] = [current, val];
}
return curr;
};
};
const storeParam = function (name) {
return function (val, params, curr) {
let data;
if (params && params.length > 0 && !(params.length === 1 && params[0] === 'CHARSET=utf-8')) {
data = {params: parseParams(params), val: text(val)};
} else {
data = text(val);
}
return storeValParam(name)(data, curr);
};
};
const addTZ = function (dt, params) {
const p = parseParams(params);
if (params && p && dt) {
dt.tz = p.TZID;
if (dt.tz !== undefined) {
// Remove surrouding quotes if found at the begining and at the end of the string
// (Occurs when parsing Microsoft Exchange events containing TZID with Windows standard format instead IANA)
dt.tz = dt.tz.replace(/^"(.*)"$/, '$1');
}
}
return dt;
};
const typeParam = function (name) {
// Typename is not used in this function?
return function (val, params, curr) {
let ret = 'date-time';
if (params && params.indexOf('VALUE=DATE') > -1 && params.indexOf('VALUE=DATE-TIME') === -1) {
ret = 'date';
}
return storeValParam(name)(ret, curr);
};
};
const dateParam = function (name) {
return function (val, params, curr) {
let newDate = text(val);
if (params && params.indexOf('VALUE=DATE') > -1 && params.indexOf('VALUE=DATE-TIME') === -1) {
// Just Date
const comps = /^(\d{4})(\d{2})(\d{2}).*$/.exec(val);
if (comps !== null) {
// No TZ info - assume same timezone as this computer
newDate = new Date(comps[1], parseInt(comps[2], 10) - 1, comps[3]);
newDate = addTZ(newDate, params);
newDate.dateOnly = true;
// Store as string - worst case scenario
return storeValParam(name)(newDate, curr);
}
}
// Typical RFC date-time format
const comps = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)?$/.exec(val);
if (comps !== null) {
if (comps[7] === 'Z') {
// GMT
newDate = new Date(
Date.UTC(
parseInt(comps[1], 10),
parseInt(comps[2], 10) - 1,
parseInt(comps[3], 10),
parseInt(comps[4], 10),
parseInt(comps[5], 10),
parseInt(comps[6], 10)
)
);
// TODO add tz
} else if (params && params[0] && params[0].indexOf('TZID=') > -1 && params[0].split('=')[1]) {
const tz = params[0].split('=')[1];
// Lookup tz
const found = moment.tz.names().filter(zone => {
return zone === tz;
})[0];
if (found) {
const zoneDate = moment.tz(val, 'YYYYMMDDTHHmmss', tz);
newDate = zoneDate.toDate();
} else {
// Fallback if tz not found
newDate = new Date(
parseInt(comps[1], 10),
parseInt(comps[2], 10) - 1,
parseInt(comps[3], 10),
parseInt(comps[4], 10),
parseInt(comps[5], 10),
parseInt(comps[6], 10)
);
}
} else {
newDate = new Date(
parseInt(comps[1], 10),
parseInt(comps[2], 10) - 1,
parseInt(comps[3], 10),
parseInt(comps[4], 10),
parseInt(comps[5], 10),
parseInt(comps[6], 10)
);
}
newDate = addTZ(newDate, params);
}
// Store as string - worst case scenario
return storeValParam(name)(newDate, curr);
};
};
const geoParam = function (name) {
return function (val, params, curr) {
storeParam(val, params, curr);
const parts = val.split(';');
curr[name] = {lat: Number(parts[0]), lon: Number(parts[1])};
return curr;
};
};
const categoriesParam = function (name) {
const separatorPattern = /\s*,\s*/g;
return function (val, params, curr) {
storeParam(val, params, curr);
if (curr[name] === undefined) {
curr[name] = val ? val.split(separatorPattern) : [];
} else if (val) {
curr[name] = curr[name].concat(val.split(separatorPattern));
}
return curr;
};
};
// EXDATE is an entry that represents exceptions to a recurrence rule (ex: "repeat every day except on 7/4").
// The EXDATE entry itself can also contain a comma-separated list, so we make sure to parse each date out separately.
// There can also be more than one EXDATE entries in a calendar record.
// Since there can be multiple dates, we create an array of them. The index into the array is the ISO string of the date itself, for ease of use.
// i.e. You can check if ((curr.exdate != undefined) && (curr.exdate[date iso string] != undefined)) to see if a date is an exception.
// NOTE: This specifically uses date only, and not time. This is to avoid a few problems:
// 1. The ISO string with time wouldn't work for "floating dates" (dates without timezones).
// ex: "20171225T060000" - this is supposed to mean 6 AM in whatever timezone you're currently in
// 2. Daylight savings time potentially affects the time you would need to look up
// 3. Some EXDATE entries in the wild seem to have times different from the recurrence rule, but are still excluded by calendar programs. Not sure how or why.
// These would fail any sort of sane time lookup, because the time literally doesn't match the event. So we'll ignore time and just use date.
// ex: DTSTART:20170814T140000Z
// RRULE:FREQ=WEEKLY;WKST=SU;INTERVAL=2;BYDAY=MO,TU
// EXDATE:20171219T060000
// Even though "T060000" doesn't match or overlap "T1400000Z", it's still supposed to be excluded? Odd. :(
// TODO: See if this causes any problems with events that recur multiple times a day.
const exdateParam = function (name) {
return function (val, params, curr) {
const separatorPattern = /\s*,\s*/g;
curr[name] = curr[name] || [];
const dates = val ? val.split(separatorPattern) : [];
dates.forEach(entry => {
const exdate = [];
dateParam(name)(entry, params, exdate);
if (exdate[name]) {
if (typeof exdate[name].toISOString === 'function') {
curr[name][exdate[name].toISOString().substring(0, 10)] = exdate[name];
} else {
console.error('No toISOString function in exdate[name]', exdate[name]);
}
}
});
return curr;
};
};
// RECURRENCE-ID is the ID of a specific recurrence within a recurrence rule.
// TODO: It's also possible for it to have a range, like "THISANDPRIOR", "THISANDFUTURE". This isn't currently handled.
const recurrenceParam = function (name) {
return dateParam(name);
};
const addFBType = function (fb, params) {
const p = parseParams(params);
if (params && p) {
fb.type = p.FBTYPE || 'BUSY';
}
return fb;
};
const freebusyParam = function (name) {
return function (val, params, curr) {
const fb = addFBType({}, params);
curr[name] = curr[name] || [];
curr[name].push(fb);
storeParam(val, params, fb);
const parts = val.split('/');
['start', 'end'].forEach((name, index) => {
dateParam(name)(parts[index], params, fb);
});
return curr;
};
};
module.exports = {
objectHandlers: {
BEGIN(component, params, curr, stack) {
stack.push(curr);
return {type: component, params};
},
END(val, params, curr, stack) {
// Original end function
const originalEnd = function (component, params, curr, stack) {
// Prevents the need to search the root of the tree for the VCALENDAR object
if (component === 'VCALENDAR') {
// Scan all high level object in curr and drop all strings
let key;
let obj;
for (key in curr) {
if (!{}.hasOwnProperty.call(curr, key)) {
continue;
}
obj = curr[key];
if (typeof obj === 'string') {
delete curr[key];
}
}
return curr;
}
const par = stack.pop();
if (curr.uid) {
// If this is the first time we run into this UID, just save it.
if (par[curr.uid] === undefined) {
par[curr.uid] = curr;
} else if (curr.recurrenceid === undefined) {
// If we have multiple ical entries with the same UID, it's either going to be a
// modification to a recurrence (RECURRENCE-ID), and/or a significant modification
// to the entry (SEQUENCE).
// TODO: Look into proper sequence logic.
// If we have the same UID as an existing record, and it *isn't* a specific recurrence ID,
// not quite sure what the correct behaviour should be. For now, just take the new information
// and merge it with the old record by overwriting only the fields that appear in the new record.
let key;
for (key in curr) {
if (key !== null) {
par[curr.uid][key] = curr[key];
}
}
}
// If we have recurrence-id entries, list them as an array of recurrences keyed off of recurrence-id.
// To use - as you're running through the dates of an rrule, you can try looking it up in the recurrences
// array. If it exists, then use the data from the calendar object in the recurrence instead of the parent
// for that day.
// NOTE: Sometimes the RECURRENCE-ID record will show up *before* the record with the RRULE entry. In that
// case, what happens is that the RECURRENCE-ID record ends up becoming both the parent record and an entry
// in the recurrences array, and then when we process the RRULE entry later it overwrites the appropriate
// fields in the parent record.
if (typeof (curr.recurrenceid) !== 'undefined') {
// TODO: Is there ever a case where we have to worry about overwriting an existing entry here?
// Create a copy of the current object to save in our recurrences array. (We *could* just do par = curr,
// except for the case that we get the RECURRENCE-ID record before the RRULE record. In that case, we
// would end up with a shared reference that would cause us to overwrite *both* records at the point
// that we try and fix up the parent record.)
const recurrenceObj = {};
let key;
for (key in curr) {
if (key !== null) {
recurrenceObj[key] = curr[key];
}
}
if (typeof (recurrenceObj.recurrences) !== 'undefined') {
delete recurrenceObj.recurrences;
}
// If we don't have an array to store recurrences in yet, create it.
if (par[curr.uid].recurrences === undefined) {
par[curr.uid].recurrences = {};
}
// Save off our cloned recurrence object into the array, keyed by date but not time.
// We key by date only to avoid timezone and "floating time" problems (where the time isn't associated with a timezone).
// TODO: See if this causes a problem with events that have multiple recurrences per day.
if (typeof curr.recurrenceid.toISOString === 'function') {
par[curr.uid].recurrences[curr.recurrenceid.toISOString().substring(0, 10)] = recurrenceObj;
} else {
console.error('No toISOString function in curr.recurrenceid', curr.recurrenceid);
}
}
// One more specific fix - in the case that an RRULE entry shows up after a RECURRENCE-ID entry,
// let's make sure to clear the recurrenceid off the parent field.
if (typeof (par[curr.uid].rrule) !== 'undefined' && typeof (par[curr.uid].recurrenceid) !== 'undefined') {
delete par[curr.uid].recurrenceid;
}
} else {
par[uuid()] = curr;
}
return par;
};
// Recurrence rules are only valid for VEVENT, VTODO, and VJOURNAL.
// More specifically, we need to filter the VCALENDAR type because we might end up with a defined rrule
// due to the subtypes.
if (val === 'VEVENT' || val === 'VTODO' || val === 'VJOURNAL') {
if (curr.rrule) {
let rule = curr.rrule.replace('RRULE:', '');
if (rule.indexOf('DTSTART') === -1) {
if (curr.start.length === 8) {
const comps = /^(\d{4})(\d{2})(\d{2})$/.exec(curr.start);
if (comps) {
curr.start = new Date(comps[1], comps[2] - 1, comps[3]);
}
}
if (typeof curr.start.toISOString === 'function') {
try {
rule += `;DTSTART=${curr.start.toISOString().replace(/[-:]/g, '')}`;
rule = rule.replace(/\.[0-9]{3}/, '');
} catch (err) {
console.error('ERROR when trying to convert to ISOString', err);
}
} else {
console.error('No toISOString function in curr.start', curr.start);
}
}
curr.rrule = rrule.fromString(rule);
}
}
return originalEnd.call(this, val, params, curr, stack);
},
SUMMARY: storeParam('summary'),
DESCRIPTION: storeParam('description'),
URL: storeParam('url'),
UID: storeParam('uid'),
LOCATION: storeParam('location'),
DTSTART(val, params, curr) {
curr = dateParam('start')(val, params, curr);
return typeParam('datetype')(val, params, curr);
},
DTEND: dateParam('end'),
EXDATE: exdateParam('exdate'),
' CLASS': storeParam('class'), // Should there be a space in this property?
TRANSP: storeParam('transparency'),
GEO: geoParam('geo'),
'PERCENT-COMPLETE': storeParam('completion'),
COMPLETED: dateParam('completed'),
CATEGORIES: categoriesParam('categories'),
FREEBUSY: freebusyParam('freebusy'),
DTSTAMP: dateParam('dtstamp'),
CREATED: dateParam('created'),
'LAST-MODIFIED': dateParam('lastmodified'),
'RECURRENCE-ID': recurrenceParam('recurrenceid'),
RRULE(val, params, curr, stack, line) {
curr.rrule = line;
return curr;
}
},
handleObject(name, val, params, ctx, stack, line) {
const self = this;
if (self.objectHandlers[name]) {
return self.objectHandlers[name](val, params, ctx, stack, line);
}
// Handling custom properties
if (name.match(/X-[\w-]+/) && stack.length > 0) {
// Trimming the leading and perform storeParam
name = name.substring(2);
return storeParam(name)(val, params, ctx, stack, line);
}
return storeParam(name.toLowerCase())(val, params, ctx);
},
parseLines(lines, limit, ctx, stack, lastIndex, cb) {
const self = this;
if (!cb && typeof ctx === 'function') {
cb = ctx;
ctx = undefined;
}
ctx = ctx || {};
stack = stack || [];
let limitCounter = 0;
let i = lastIndex || 0;
for (let ii = lines.length; i < ii; i++) {
let l = lines[i];
// Unfold : RFC#3.1
while (lines[i + 1] && /[ \t]/.test(lines[i + 1][0])) {
l += lines[i + 1].slice(1);
i++;
}
const exp = /([^":;]+)((?:;(?:[^":;]+)(?:=(?:(?:"[^"]*")|(?:[^":;]+))))*):(.*)/;
let kv = l.match(exp);
if (kv === null) {
// Invalid line - must have k&v
continue;
}
kv = kv.slice(1);
const value = kv[kv.length - 1];
const name = kv[0];
const params = kv[1] ? kv[1].split(';').slice(1) : [];
ctx = self.handleObject(name, value, params, ctx, stack, l) || {};
if (++limitCounter > limit) {
break;
}
}
if (i >= lines.length) {
// Type and params are added to the list of items, get rid of them.
delete ctx.type;
delete ctx.params;
}
if (cb) {
if (i < lines.length) {
setImmediate(() => {
self.parseLines(lines, limit, ctx, stack, i + 1, cb);
});
} else {
setImmediate(() => {
cb(null, ctx);
});
}
} else {
return ctx;
}
},
getLineBreakChar(string) {
const indexOfLF = string.indexOf('\n', 1); // No need to check first-character
if (indexOfLF === -1) {
if (string.indexOf('\r') !== -1) {
return '\r';
}
return '\n';
}
if (string[indexOfLF - 1] === '\r') {
return '\r?\n';
}
return '\n';
},
parseICS(str, cb) {
const self = this;
const lineEndType = self.getLineBreakChar(str);
const lines = str.split(lineEndType === '\n' ? /\n/ : /\r?\n/);
let ctx;
if (cb) {
// Asynchronous execution
self.parseLines(lines, 2000, cb);
} else {
// Synchronous execution
ctx = self.parseLines(lines, lines.length);
return ctx;
}
}
};