/
event.js
431 lines (352 loc) · 9.67 KB
/
event.js
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
/* Copyright (C) 2018-2019 Greenbone Networks GmbH
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import 'core-js/fn/object/entries';
import 'core-js/fn/object/values';
import ical from 'ical.js';
import uuid from 'uuid/v4';
import Logger from 'gmp/log';
import {isDefined} from '../utils/identity';
import {isEmpty} from '../utils/string';
import date, {duration as createDuration} from './date';
const log = Logger.getLogger('gmp.models.event');
const convertIcalDate = (idate, timezone) => {
if (isDefined(timezone)) {
if (idate.zone === ical.Timezone.localTimezone) {
// assume timezone hasn't been set and date wasn't supposed to use floating and therefore local timezone
return date.tz(idate.toString(), timezone);
}
return date.unix(idate.toUnixTime()).tz(timezone);
}
return date.unix(idate.toUnixTime());
};
const setEventDuration = (event, duration) => {
// setting the duration of an event directly isn't possible in
// ical.js 1.2.2 yet. Therefore add same logic from ical.js master here
if (event.component.hasProperty('dtend')) {
event.component.removeProperty('dtend');
}
event._setProp('duration', duration);
};
const setEventRecurrence = (event, recurrence) => {
event._setProp('rrule', recurrence);
};
const PROD_ID = '-//Greenbone.net//NONSGML Greenbone Security Assistent';
const ICAL_VERSION = '2.0';
export const ReccurenceFrequency = {
YEARLY: 'YEARLY',
MONTHLY: 'MONTHLY',
WEEKLY: 'WEEKLY',
DAILY: 'DAILY',
HOURLY: 'HOURLY',
MINUTELY: 'MINUTELY',
SECONDLY: 'SECONDLY',
};
const ISOWEEKDAY_TO_WEEKDAY = {
1: 'monday',
2: 'tuesday',
3: 'wednesday',
4: 'thursday',
5: 'friday',
6: 'saturday',
7: 'sunday',
};
const ABR_TO_WEEKDAY = {
mo: 'monday',
tu: 'tuesday',
we: 'wednesday',
th: 'thursday',
fr: 'friday',
sa: 'saturday',
su: 'sunday',
};
const getWeekDaysFromRRule = rrule => {
if (!isDefined(rrule)) {
return undefined;
}
const byday = rrule.getComponent('byday');
return byday.length > 0 ? WeekDays.fromByDay(byday) : undefined;
};
const getMonthDaysFromRRule = rrule => {
if (!isDefined(rrule)) {
return undefined;
}
const bymonthday = rrule.getComponent('bymonthday');
return bymonthday.length > 0 ? bymonthday.sort() : undefined;
};
export class WeekDays {
constructor({
monday = false,
tuesday = false,
wednesday = false,
thursday = false,
friday = false,
saturday = false,
sunday = false,
} = {}) {
this._weekdays = {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday,
};
}
static fromByDay(bydate = []) {
const weekdays = new WeekDays();
for (const part of bydate) {
const pday = part.slice(-2).toLowerCase();
const pval = part.slice(0, -2);
const wday = ABR_TO_WEEKDAY[pday];
const val = pval.length === 0 ? true : pval;
if (isDefined(wday)) {
weekdays._setWeekDay(wday, val);
}
}
return weekdays;
}
_setWeekDay(weekday, value = true) {
this._weekdays[weekday] = value;
return this;
}
isDefault() {
return !this.values().some(value => value);
}
copy() {
return new WeekDays({...this._weekdays});
}
entries() {
return Object.entries(this._weekdays);
}
values() {
return Object.values(this._weekdays);
}
getSelectedWeekDay() {
const ret = this.entries().find(([, value]) => value);
return isDefined(ret) ? ret[0] : undefined;
}
get(weekday) {
return this._weekdays[weekday];
}
setWeekDay(weekday, value = true) {
const copy = this.copy();
return copy._setWeekDay(weekday, value);
}
setWeekDayFromDate(curdate, value = true) {
const wday = ISOWEEKDAY_TO_WEEKDAY[curdate.isoWeekday()];
return this.setWeekDay(wday, value);
}
toByDate() {
const byday = [];
for (const [abbr, weekday] of Object.entries(ABR_TO_WEEKDAY)) {
const value = this.get(weekday);
if (value) {
if (value === true) {
byday.push(abbr.toUpperCase());
} else {
byday.push('' + value + abbr.toUpperCase());
}
}
}
return byday;
}
get monday() {
return this.get('monday');
}
get tuesday() {
return this.get('tuesday');
}
get wednesday() {
return this.get('wednesday');
}
get thursday() {
return this.get('thursday');
}
get friday() {
return this.get('friday');
}
get saturday() {
return this.get('saturday');
}
get sunday() {
return this.get('sunday');
}
}
class Event {
constructor(icalevent, timezone) {
this.event = icalevent;
this.timezone = timezone;
}
static fromIcal(icalendar, timezone) {
const jcal = ical.parse(icalendar);
const comp = new ical.Component(jcal);
const vevent = comp.getFirstSubcomponent('vevent');
const event = new ical.Event(vevent);
return new Event(event, timezone);
}
static fromData(
{
description,
duration,
freq,
interval,
monthdays = [],
startDate,
summary,
weekdays,
},
timezone,
) {
const event = new ical.Event();
event.uid = uuid();
event.startDate = ical.Time.fromJSDate(startDate.toDate(), true);
if (isDefined(duration)) {
const eventDuration = new ical.Duration();
eventDuration.days = duration.days();
eventDuration.weeks = duration.weeks();
eventDuration.hours = duration.hours();
eventDuration.minutes = duration.minutes();
eventDuration.seconds = duration.seconds();
setEventDuration(event, eventDuration);
}
if (isDefined(freq)) {
const eventRecur = new ical.Recur();
eventRecur.freq = freq;
eventRecur.interval = interval;
const icalweekdays = isDefined(weekdays) ? weekdays.toByDate() : [];
if (icalweekdays.length > 0) {
eventRecur.setComponent('byday', icalweekdays);
}
if (monthdays.length > 0) {
eventRecur.setComponent('bymonthday', monthdays);
}
setEventRecurrence(event, eventRecur);
}
if (!isEmpty(summary)) {
event.summary = summary;
}
if (!isEmpty(description)) {
event.description = description;
}
return new Event(event, timezone);
}
_getReccurenceRule() {
if (this.isRecurring()) {
const rrule = this.event.component.getFirstPropertyValue('rrule');
return rrule === null ? undefined : rrule;
}
return undefined;
}
get startDate() {
return convertIcalDate(this.event.startDate, this.timezone);
}
get duration() {
return createDuration({...this.event.duration});
}
get durationInSeconds() {
const {
days = 0,
hours = 0,
minutes = 0,
weeks = 0,
seconds = 0,
} = this.event.duration;
return (
seconds +
minutes * 60 +
hours * 60 * 60 +
days * 24 * 60 * 60 +
weeks * 7 * 24 * 60 * 60
);
}
get recurrence() {
const rrule = this._getReccurenceRule();
return {
...rrule,
weekdays: getWeekDaysFromRRule(rrule),
monthdays: getMonthDaysFromRRule(rrule),
};
}
get nextDate() {
if (this.isRecurring()) {
const now = date();
const it = this.event.iterator();
let retries = 0;
while (true && retries <= 5) {
try {
const next = it.next();
if (next.toUnixTime() >= now.unix()) {
return convertIcalDate(next, this.timezone);
}
retries = 0;
} catch (err) {
// ical.js raises an exception if the same date occurs twice
// See https://github.com/mozilla-comm/ical.js/blob/master/lib/ical/recur_iterator.js#L373
// But this may be valid e.g. when last day of month and the 31 of a
// month are set in the rrule. Therefore ignore error and retry to get
// a new date. Fail after 5 unsuccessful attempts
retries++;
if (retries >= 5) {
log.error(
'Error raised while calculating next date.',
'ical event was:\n' + this.event + '\n',
err,
);
}
}
}
}
return undefined;
}
getNextDates(until) {
if (this.isRecurring()) {
const now = date();
const it = this.event.iterator();
const dates = [];
while (true) {
const next = it.next();
if (it.completed || !next) {
return dates;
}
const mnext = convertIcalDate(next);
if (mnext.isAfter(until)) {
return dates;
}
if (mnext.isSameOrAfter(now)) {
dates.push(mnext);
}
}
}
return [];
}
isRecurring() {
return this.event.isRecurring();
}
toIcalString() {
const comp = new ical.Component(['vcalendar', [], []]);
comp.addPropertyWithValue('prodid', PROD_ID);
comp.addPropertyWithValue('version', ICAL_VERSION);
const {component: vevent} = this.event;
comp.addSubcomponent(vevent);
return comp.toString();
}
}
export default Event;
// vim: set ts=2 sw=2 tw=80: