forked from iobroker-community-adapters/ioBroker.ical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1585 lines (1427 loc) · 67.5 KB
/
main.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
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ioBroker.iCal
* Copyright 2015-2020, bluefox <[email protected]>
*
* Based on ccu.io vader722 adapter.
* https://github.com/hobbyquaker/ccu.io/tree/master/adapter/ical
*
*/
/* jshint -W097 */
/* jshint strict:false */
/* jshint esversion: 6 */
/* jslint node: true */
'use strict';
// Get common adapter utils
const utils = require('@iobroker/adapter-core');
const RRule = require('rrule').RRule;
const ical = require('node-ical');
const ce = require('cloneextend');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const adapterName = require('./package.json').name.split('.').pop();
const request = require('request');
let adapter;
let stopped = false;
let killTimeout = null;
function startAdapter(options) {
options = options || {};
Object.assign(options,{
name: adapterName,
stateChange: async function (id, state) {
if (!id || !state || state.ack || !state.val) {
return;
}
if (id === `${adapter.namespace}.trigger`) {
const content = state.val.split(' ');
// One time read all calendars
switch (content[0]) {
case 'read':
if (content[1]) {
adapter.log.info(`reading iCal from URL: "${content[1]}"`);
readOne(content[1]);
} else {
adapter.log.info('reading one time from all calendars');
readAll();
}
break;
// FIXME: checkForEvents not supporting call with only 1 parameter
case 'check':
if (content[1]) {
adapter.log.info(`checking "${content[1]}"`);
await checkForEvents(content[1]);
} else {
adapter.log.warn('check all events');
for (let i = 0; i < adapter.config.events.length; i++) {
await checkForEvents(adapter.config.events[i].name);
}
}
break;
default:
adapter.log.warn(`Unknown command in trigger: "${state.val}"`);
}
}
},
unload: function (callback) {
stopped = true;
callback();
},
ready: function () {
main();
}
});
adapter = new utils.Adapter(options);
return adapter;
}
// set when ready
let normal = '';
const warn = '<span style="font-weight: bold; color: red"><span class="icalWarn">';
const prewarn = '<span style="font-weight: bold; color: orange"><span class="icalPreWarn">';
const preprewarn = '<span style="font-weight: bold; color: yellow"><span class="icalPrePreWarn">';
let datesArray = [];
const events = [];
const dictionary = {
'today': {'en': 'Today', 'it': 'Oggi', 'es': 'Hoy', 'pl': 'Dzisiaj', 'fr': 'Aujourd\'hui', 'de': 'Heute', 'ru': 'Сегодня', 'nl': 'Vandaag'},
'tomorrow': {'en': 'Tomorrow', 'it': 'Domani', 'es': 'Mañana', 'pl': 'Jutro', 'fr': 'Demain', 'de': 'Morgen', 'ru': 'Завтра', 'nl': 'Morgen'},
'dayafter': {'en': 'Day After Tomorrow','it': 'Dopodomani', 'es': 'Pasado mañana', 'pl': 'Pojutrze', 'fr': 'Après demain', 'de': 'Übermorgen', 'ru': 'Послезавтра', 'nl': 'Overmorgen'},
'3days': {'en': 'In 3 days', 'it': 'In 3 giorni', 'es': 'En 3 días', 'pl': 'W 3 dni', 'fr': 'Dans 3 jours', 'de': 'In 3 Tagen', 'ru': 'Через 2 дня', 'nl': 'Over 3 dagen'},
'4days': {'en': 'In 4 days', 'it': 'In 4 giorni', 'es': 'En 4 días', 'pl': 'W 4 dni', 'fr': 'Dans 4 jours', 'de': 'In 4 Tagen', 'ru': 'Через 3 дня', 'nl': 'Over 4 dagen'},
'5days': {'en': 'In 5 days', 'it': 'In 5 giorni', 'es': 'En 5 días', 'pl': 'W ciągu 5 dni', 'fr': 'Dans 5 jours', 'de': 'In 5 Tagen', 'ru': 'Через 4 дня', 'nl': 'Over 5 dagen'},
'6days': {'en': 'In 6 days', 'it': 'In 6 giorni', 'es': 'En 6 días', 'pl': 'W ciągu 6 dni', 'fr': 'Dans 6 jours', 'de': 'In 6 Tagen', 'ru': 'Через 5 дней', 'nl': 'Over 6 dagen'},
'oneweek': {'en': 'In one week', 'it': 'In una settimana', 'es': 'En una semana', 'pl': 'W jeden tydzień', 'fr': 'Dans une semaine', 'de': 'In einer Woche', 'ru': 'Через неделю', 'nl': 'Binnen een week'},
'1week_left':{'en': 'One week left', 'it': 'Manca una settimana', 'es': 'Queda una semana', 'pl': 'Został jeden tydzień', 'fr': 'Reste une semaine', 'de': 'Noch eine Woche', 'ru': 'Ещё неделя', 'nl': 'Over een week'},
'2week_left':{'en': 'Two weeks left', 'it': 'Due settimane rimaste', 'es': 'Dos semanas restantes', 'pl': 'Zostały dwa tygodnie', 'fr': 'Il reste deux semaines', 'de': 'Noch zwei Wochen', 'ru': 'Ещё две недели', 'nl': 'Over twee weken'},
'3week_left':{'en': 'Three weeks left', 'it': 'Tre settimane rimanenti', 'es': 'Tres semanas quedan', 'pl': 'Pozostały trzy tygodnie', 'fr': 'Trois semaines restantes', 'de': 'Noch drei Wochen', 'ru': 'Ещё три недели', 'nl': 'Over drie weken'},
'4week_left':{'en': 'Four weeks left', 'it': 'Quattro settimane rimaste', 'es': 'Cuatro semanas quedan', 'pl': 'Pozostały cztery tygodnie', 'fr': 'Quatre semaines à gauche', 'de': 'Noch vier Wochen', 'ru': 'Ещё три недели', 'nl': 'Over vier weken'},
'5week_left':{'en': 'Five weeks left', 'it': 'Cinque settimane rimaste', 'es': 'Quedan cinco semanas', 'pl': 'Pozostało pięć tygodni', 'fr': 'Cinq semaines à gauche', 'de': 'Noch fünf Wochen', 'ru': 'Ещё пять недель', 'nl': 'Over vijf weken'},
'6week_left':{'en': 'Six weeks left', 'it': 'Sei settimane a sinistra', 'es': 'Seis semanas restantes','pl': 'Pozostało sześć tygodni', 'fr': 'Six semaines à gauche', 'de': 'Noch sechs Wochen','ru': 'Ещё шесть недель', 'nl': 'Over zes weken'},
'left': {'en': 'left', 'it': 'sinistra', 'es': 'izquierda', 'pl': 'lewo', 'fr': 'la gauche', 'de': ' ', 'ru': 'осталось', 'nl': 'over'},
'still': {'en': ' ', 'it': '', 'es': '', 'pl': '', 'fr': '', 'de': 'Noch', 'ru': ' ', 'nl': 'nog'},
'days': {'en': 'days', 'it': 'Giorni', 'es': 'dias', 'pl': 'dni', 'fr': 'journées', 'de': 'Tage', 'ru': 'дней', 'nl': 'dagen'},
'day': {'en': 'day', 'it': 'giorno', 'es': 'día', 'pl': 'dzień', 'fr': 'journée', 'de': 'Tag', 'ru': 'день', 'nl': 'dag'},
'hours': {'en': 'hours', 'it': 'ore', 'es': 'horas', 'pl': 'godziny', 'fr': 'heures', 'de': 'Stunden', 'ru': 'часов', 'nl': 'uren'},
'hour': {'en': 'hour', 'it': 'ora', 'es': 'hora', 'pl': 'godzina', 'fr': 'heure', 'de': 'Stunde', 'ru': 'час', 'nl': 'uur'},
'minute': {'en': 'minute', 'it': 'minuto', 'es': 'minuto', 'pl': 'minuta', 'fr': 'minute', 'de': 'Minute', 'ru': 'минута', 'nl': 'minuut'},
'minutes': {'en': 'minutes', 'it': 'minuti', 'es': 'minutos', 'pl': 'minutos', 'fr': 'minutes', 'de': 'Minuten', 'ru': 'минуты', 'nl': 'minuten'}
};
function _(text) {
if (!text) {
return '';
}
if (dictionary[text]) {
let newText = dictionary[text][adapter.config.language];
if (newText) {
return newText;
} else if (adapter.config.language !== 'en') {
newText = dictionary[text].en;
if (newText) {
return newText;
}
}
} else if (!text.match(/_tooltip$/)) {
adapter.log.debug(`"${text}": {"en": "${text}", "de": "${text}", "ru": "${text}"},`);
}
return text;
}
/* Compare the current date against another date.
*
* @param b {Date} the other date
* @returns -1 : if this < b
* 0 : if this === b
* 1 : if this > b
* NaN : if a or b is an illegal date
*/
Date.prototype.compare = function(b) {
if (b.constructor !== Date) {
throw new Error('invalid_date');
}
return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ?
(this > b) - (this < b) : NaN
);
};
function getICal(urlOrFile, user, pass, sslignore, calName, cb) {
// Is it file or URL
if (!urlOrFile.match(/^https?:\/\//)) {
if (!fs.existsSync(urlOrFile)) {
cb && cb(`File does not exist: "${urlOrFile}"`);
} else {
try {
const data = fs.readFileSync(urlOrFile);
cb && cb(null, data.toString());
} catch (e) {
cb && cb(`Cannot read file "${urlOrFile}": ${e}`);
}
}
} else {
// Find out whether SSL certificate errors shall be ignored
const options = {
uri: urlOrFile
};
if (sslignore === 'ignore' || sslignore === 'true' || sslignore === true) {
options.rejectUnauthorized = false;
}
if (user) {
options.auth = {
user: user,
pass: pass,
sendImmediately: true
};
}
// Call library function with the "auth object" and credentials provided
request(options, (err, r, _data) => {
const calHash = crypto.createHash('md5').update(user + pass + urlOrFile).digest('hex');
const cachedFilename = path.join(__dirname, calHash);
if (err || !_data || (r && r.statusCode !== 200)) {
let cachedContent;
let cachedDate;
try {
if (fs.existsSync(cachedFilename)) {
cachedContent = fs.readFileSync(cachedFilename, 'utf-8');
const stat = fs.statSync(cachedFilename);
cachedDate = stat.mtime;
}
} catch (err) {
adapter.log.info(`Cannot read cached calendar file for "${urlOrFile}": ${err.message}`);
}
if (err) {
adapter.log.warn(`Error reading from URL "${urlOrFile}": ${(err && err.code === 'ENOTFOUND') ? 'address not found!' : err}`);
if (!cachedContent) {
return cb && cb(err || `Cannot read URL: "${urlOrFile}"`);
}
} else if (r) {
adapter.log.warn(`Error reading from URL "${urlOrFile}": Server responded HTTP-Statuscode=${r.statusCode}: ${_data}`);
if (!cachedContent) {
return cb && cb(`Cannot read URL: "${urlOrFile}" HTTP-Status ${r.statusCode}`);
}
}
adapter.log.info(`Use cached File content for for "${urlOrFile}" from ${cachedDate}`);
cb && cb(null, cachedContent);
} else {
try {
fs.writeFileSync(cachedFilename, _data, 'utf-8');
adapter.log.debug(`Successfully cached content for calendar "${urlOrFile}" as ${cachedFilename}`);
} catch (err) {
// Ignore
}
cb && cb(null, _data);
}
});
}
}
function checkICal(urlOrFile, user, pass, sslignore, calName, filter, cb) {
if (stopped) return;
if (typeof user === 'function') {
cb = user;
user = undefined;
}
getICal(urlOrFile, user, pass, sslignore, calName, (err, _data) => {
if (stopped) return;
if (err || !_data) {
adapter.log.warn(`Error reading "${urlOrFile}": ${err}`);
cb(err, calName);
return;
}
adapter.log.debug(`File read successfully ${urlOrFile}`);
try {
ical.parseICS(_data, (err, data) => {
if (stopped) return;
if (data) {
adapter.log.info(`processing URL: ${calName} ${urlOrFile}`);
adapter.log.debug(JSON.stringify(data));
const realnow = new Date();
const startpreview = new Date();
startpreview.setDate(startpreview.getDate() - parseInt(adapter.config.daysPast, 10));
startpreview.setHours(0, 0, 0, 0);
adapter.log.debug(`checkICal: startpreview - ${startpreview}`);
const endpreview = new Date();
endpreview.setDate(endpreview.getDate() + parseInt(adapter.config.daysPreview, 10));
adapter.log.debug(`checkICal: endpreview - ${endpreview}`);
const now2 = new Date();
// clear time
now2.setHours(0, 0, 0, 0);
setImmediate(() =>
processData(data, realnow, startpreview, endpreview, now2, calName, filter, cb));
} else {
// Ready with processing
cb(null, calName);
}
});
} catch (e) {
adapter.log.error(`Cannot parse ics file: ${e}`);
cb(err, calName);
}
});
}
function addOffset(time, offset) {
return new Date(time.getTime() + (offset * 60 * 1000));
}
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
async function processData(data, realnow, startpreview, endpreview, now2, calName, filter, cb) {
if (stopped) return;
let processedEntries = 0;
for (const k in data) {
const ev = data[k];
delete data[k];
// only events with summary and a start date are interesting
if ((ev.summary !== undefined) && (ev.type === 'VEVENT') && ev.start && ev.start instanceof Date) {
adapter.log.debug(`ev: ${JSON.stringify(ev)}`);
if (!ev.end || !(ev.end instanceof Date)) {
ev.end = new Date(ev.start.getTime());
if (ev.start.getHours() === 0 && ev.start.getMinutes() === 0 && ev.start.getSeconds() === 0) {
ev.end.setDate(ev.end.getDate() + 1);
}
}
// aha, it is RRULE in the event --> process it
if (ev.rrule !== undefined) {
let eventLength = treatAsUTC(ev.end.getTime()) - treatAsUTC(ev.start.getTime());
if (ev.datetype === 'date') {
// If "whole day event" correct the eventlength to full days
const calcStart = new Date(ev.start.getTime());
calcStart.setHours(0,0,0,0);
let calcEnd = new Date(ev.end.getTime());
if (calcEnd.getHours() === 0 && calcEnd.getMinutes() === 0 && calcEnd.getSeconds() === 0) {
// if end id 0:0:0 then it is considered exclusive, so reduce by 1s
calcEnd = new Date(ev.end.getTime());
calcEnd.setDate(calcEnd.getDate() - 1);
adapter.log.debug(`Adjust enddate to exclude 0:0:0 for eventlength`);
}
calcEnd.setHours(23,59,59,0);
eventLength = treatAsUTC(calcEnd.getTime()) - treatAsUTC(calcStart.getTime());
eventLength = Math.ceil(eventLength / ( 24 * 60 * 60 * 1000)) * 24 * 60 * 60 * 1000;
adapter.log.debug(`Calculated Date Eventlength = ${eventLength} (${eventLength / ( 24 * 60 * 60 * 1000)} days) for ${calcStart.toString()} - ${calcEnd.toString()}`);
}
const options = RRule.parseString(ev.rrule.toString());
// the following workaround an issue in rule.between() later on where
// the time comparison between dtstart and until does not seem to work
// if both are not in the same DST zone (e.g. dtstart=2021-09-21T15:00:00.000Z
// until=2021-11-09T15:59:59.000Z) so that an event is still considered as TODAY
// even thought it ends one second before the next scheduled one.
if (options.until !== undefined && options.dtstart !== undefined) {
options.until = addOffset(options.until, options.dtstart.getTimezoneOffset() - options.until.getTimezoneOffset());
}
adapter.log.debug(`options: ${JSON.stringify(options)}`);
const rule = new RRule(options);
let now3 = new Date(now2.getTime() - eventLength);
if (now2 < now3) {
now3 = now2;
}
if (startpreview < now3) {
now3 = startpreview;
}
adapter.log.debug(`RRule event:${ev.summary}; start:${ev.start.toString()}; endpreview:${endpreview.toString()}; startpreview:${startpreview.toString()}; now2:${now2.toString()}; now3:${now3.toString()}; rule:${JSON.stringify(rule)}`);
let dates = [];
try {
dates = rule.between(now3, endpreview, true);
} catch(e) {
adapter.log.error(`Issue detected in RRule, event ignored; Please forward debug information to iobroker.ical developer: ${e.stack}
RRule object: ${JSON.stringify(rule)}
now3: ${now3}
endpreview: ${endpreview}
string: ${ev.rrule.toString()}
options: ${JSON.stringify(options)}`
);
}
adapter.log.debug(`dates: ${JSON.stringify(dates)}`);
// event within the time window
if (dates.length > 0) {
for (let i = 0; i < dates.length; i++) {
// use deep-copy otherwise setDate etc. overwrites data from different events
let ev2 = ce.clone(ev);
// we have to move the start time of our clone
// to a time relative to the timezone of the start time
// so that re-currence events are setup correctly and
// that the later exdate check will match correctly.
ev2.start = dates[i];
if (ev.datetype === 'date') {
// make sure to set the time to 00:00:00 so that
// this event will be recognized as a date event
ev2.start.setHours(0,0,0,0);
} else if (ev.datetype === 'date-time') {
// add a time offset which is relative between
// ev2 and ev because rrule seems to return dates in
// local time only. And if not correctly the exdate
// check later will not work correctly.
ev2.start = addOffset(ev2.start, ev2.start.getTimezoneOffset() - ev.start.getTimezoneOffset());
}
// Set end date based on length in ms
ev2.end = new Date(ev2.start.getTime() + eventLength);
if (ev2.start.getTimezoneOffset() !== ev2.end.getTimezoneOffset()) { // DST difference, we need to correct it
ev2.end = addOffset(ev2.end, ev2.end.getTimezoneOffset() - ev2.start.getTimezoneOffset());
}
// we have to check if there is an exdate array
// which defines dates that - if matched - should
// be excluded.
let checkDate = true;
if (ev2.exdate) {
adapter.log.debug(` ${i}: Event (exdate: ${JSON.stringify(Object.keys(ev2.exdate))}): ${ev2.start.toString()} ${ev2.end.toString()}`);
for(const d in ev2.exdate) {
const dd = new Date(ev2.exdate[d]);
if (dd.getTime() === ev2.start.getTime()) {
checkDate = false;
adapter.log.debug(` ${i}: exclude ${dd.toString()}`);
break;
}
}
} else {
adapter.log.debug(` ${i}: Event (NO exdate): ${ev2.start.toString()} ${ev2.end.toString()}`);
}
if (checkDate && ev.recurrences) {
for(const dOri in ev.recurrences) {
const recurEvent = ev.recurrences[dOri];
if (recurEvent.recurrenceid.getTime() === ev2.start.getTime()) {
ev2 = ce.clone(recurEvent);
adapter.log.debug(` ${i}: different recurring found replaced with Event:${ev2.start} ${ev2.end}`);
}
}
}
if (checkDate) {
await checkDates(ev2, endpreview, startpreview, realnow, ' rrule ', calName, filter);
}
}
} else {
adapter.log.debug('no RRule events inside the time interval');
}
} else {
adapter.log.debug(`Single event: ${ev.summary}; start:${ev.start}; end:${ev.end}; endpreview:${endpreview}; startpreview:${startpreview}; realnow:${realnow}`);
// No RRule event
await checkDates(ev, endpreview, startpreview, realnow, ' ', calName, filter);
}
}
if (++processedEntries > 100) {
break;
}
}
if (!Object.keys(data).length) {
cb(null, calName);
} else {
setImmediate(() =>
processData(data, realnow, startpreview, endpreview, now2, calName, filter, cb));
}
}
async function checkDates(ev, endpreview, startpreview, realnow, rule, calName, filter) {
let fullDay = false;
let isPrivate;
let reason;
let date;
// chech if sub parameter exists for outlook
if (Object.prototype.hasOwnProperty.call(ev, 'summary') && Object.prototype.hasOwnProperty.call(ev.summary, 'val')) {
// yes -> read reason
reason = ev.summary.val || '';
} else {
// no
reason = ev.summary || '';
}
const location = ev.location || '';
// check if sub parameter 'class' exists and contains PRIVATE
isPrivate = Object.prototype.hasOwnProperty.call(ev, 'class') && ev.class === "PRIVATE";
// If not start point => ignore it
if (!ev.start || !ev.start instanceof Date) {
return;
}
// If not end point => assume 0:0:0 event and set to same as start
ev.end = new Date(ev.end.getTime()) || new Date(ev.start.getTime());
if (!ev.end || !ev.end instanceof Date) {
return;
}
// If full day
if (ev.start.getHours() === 0 &&
ev.start.getMinutes() === 0 &&
ev.start.getSeconds() === 0 &&
ev.end.getHours() === 0 &&
ev.end.getMinutes() === 0 &&
ev.end.getSeconds() === 0
) {
// interpreted as one day; RFC says end date must be after start date
if (ev.end.getTime() === ev.start.getTime() && ev.datetype === 'date') {
ev.end.setDate(ev.end.getDate() + 1);
}
if (ev.end.getTime() !== ev.start.getTime()) {
fullDay = true;
}
}
// If force Fullday is set
if (adapter.config.forceFullday && !fullDay) {
fullDay = true;
ev.start.setMinutes(0);
ev.start.setSeconds(0);
ev.start.setHours(0);
ev.end.setDate(ev.end.getDate() + 1);
ev.end.setHours(0);
ev.end.setMinutes(0);
ev.end.setSeconds(0);
}
if (filter) {
const content = `SUMMARY:${reason}
DESCRIPTION:${ev.description}
LOCATION:${location}`;
filter = new RegExp(filter.source, filter.flags);
if (filter.test(content)) {
adapter.log.debug(`Event filtered using ${filter} by content: ${content}`);
return;
}
}
// Full day
if (fullDay) {
adapter.log.debug(`Event (full day) processing. Start: ${ev.start} End: ${ev.end}`);
// event start >= startpreview && < previewtime or end > startpreview && < previewtime ---> display
if ((ev.start < endpreview && ev.start >= startpreview) || (ev.end > startpreview && ev.end <= endpreview) || (ev.start < realnow && ev.end > realnow)) {
// check only full day events
if (await checkForEvents(reason, ev, realnow)) {
date = formatDate(ev.start, ev.end, true, true);
insertSorted(datesArray, {
date: date.text,
event: reason,
_class: `ical_${calName} ${date._class}`,
_date: new Date(ev.start.getTime()),
// add additional Objects, so iobroker.occ can use it
_end: new Date(ev.end.getTime()),
_section: ev.description,
_IDID: ev.uid,
_allDay: true,
_private: isPrivate,
_rule: rule,
location: location,
// add additional Objects, so iobroker.occ can use it
_calName: calName,
_calColor: adapter.config.calendars.find(x => x.name === calName).color,
_object: ev
});
adapter.log.debug(`Event (full day) added : ${JSON.stringify(rule)} ${reason} at ${date.text}`);
} else {
adapter.log.debug(`Event (full day) not displayed, because belongs to hidden user events: ${reason}`);
}
} else {
// filtered out, because does not belongs to specified time interval
adapter.log.debug(`Event (full day) ${JSON.stringify(rule)} ${reason} at ${ev.start.toString()} filtered out, does not belong to specified time interval`);
}
} else {
adapter.log.debug(`Event (time) processing. Start: ${ev.start} End: ${ev.end}`);
// Event with time
// Start time >= startpreview && Start time < preview time && End time >= now
if ((ev.start >= startpreview && ev.start < endpreview && ev.end >= realnow) || (ev.end >= realnow && ev.end <= endpreview) || (ev.start < realnow && ev.end > realnow)) {
// Add to list only if not hidden
if (await checkForEvents(reason, ev, realnow)) {
date = formatDate(ev.start, ev.end, true, false);
insertSorted(datesArray, {
date: date.text,
event: reason,
_class: `ical_${calName} ${date._class}`,
_date: new Date(ev.start.getTime()),
// add additional Objects, so iobroker.occ can use it
_end: new Date(ev.end.getTime()),
_section: ev.description,
_IDID: ev.uid,
_allDay: false,
_private: isPrivate,
_rule: rule,
location: location,
// add additional Objects, so iobroker.occ can use it
_calName: calName,
_calColor: adapter.config.calendars.find(x => x.name === calName).color,
_object: ev
});
adapter.log.debug(`Event with time added: ${JSON.stringify(rule)} ${reason} at ${date.text}`);
} else {
adapter.log.debug(`Event does not displayed, because belongs to hidden user events: ${reason}`);
}
} else {
// filtered out, because does not belongs to specified time interval
adapter.log.debug(`Event ${JSON.stringify(rule)} ${reason} at ${ev.start.toString()} filtered out, because does not belongs to specified time interval`);
}
}
}
function colorizeDates(date, today, tomorrow, dayafter, col, calName) {
const result = {
prefix: normal,
suffix: '</span>' + (adapter.config.colorize ? '</span>' : '')
};
const cmpDate = new Date(date.getTime());
cmpDate.setHours(0, 0, 0, 0);
calName = (calName || '').replace(' ', '_');
// colorize if needed
if (adapter.config.colorize) {
// today
if (cmpDate.compare(today) <= 0) {
result.prefix = warn;
// If configured every calendar has own color
if (adapter.config.everyCalOneColor) {
result.suffix += `<span style="font-weight:normal${col ? (`;color:${col}`) : ''}">`;
} else {
result.suffix += '<span style="font-weight:normal;color:red">';
}
result.suffix += `<span class="icalWarn2 iCal-${calName}2">`;
} else
// tomorrow
if (cmpDate.compare(tomorrow) === 0) {
result.prefix = prewarn;
// If configured every calendar has own color
if (adapter.config.everyCalOneColor) {
result.suffix += `<span style="font-weight: normal${col ? (`; color:${col}`) : ''}">`;
} else {
result.suffix += '<span style="font-weight: normal; color: orange">';
}
result.suffix += `<span class='icalPreWarn2 iCal-${calName}2'>`;
} else
// day after tomorrow
if (cmpDate.compare(dayafter) === 0) {
result.prefix = preprewarn;
// If configured every calendar has own color
if (adapter.config.everyCalOneColor) {
result.suffix += `<span style="font-weight: normal${col ? (`; color:${col}`) : ''}">`;
} else {
result.suffix += '<span style="font-weight: normal; color: yellow">';
}
result.suffix += `<span class='icalPrePreWarn2 iCal-${calName}2'>`;
} else
// start time is in the past
if (cmpDate.compare(today) === -1) {
result.prefix = normal;
// If configured every calendar has own color
if (adapter.config.everyCalOneColor) {
result.suffix += `<span style="font-weight: normal${col ? (`; color:${col}`) : ''}">`;
} else {
result.suffix += `<span style="font-weight: normal${adapter.config.defColor ? (`; color:${adapter.config.defColor}`) : ''}">`;
}
result.suffix += `<span class='icalNormal2 iCal-${calName}2'>`;
} else {
// If configured every calendar has own color
if (adapter.config.everyCalOneColor) {
result.suffix += `<span style="font-weight: normal${col ? (`; color:${col}`) : ''}">`;
} else {
result.suffix += `<span style="font-weight: normal${adapter.config.defColor ? (`; color:${adapter.config.defColor}`) : ''}">`;
}
result.suffix += `<span class='icalNormal2 iCal-${calName}2'>`;
}
}
result.prefix = result.prefix.substring(0, result.prefix.length - 2);
result.prefix += ` iCal-${calName}">`;
return result;
}
async function checkForEvents(reason, event, realnow) {
const ignoreCaseInEventname = adapter.config.ignoreCaseInEventname;
// show unknown events
let result = true;
let today = new Date(realnow.getTime());
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today.getTime());
tomorrow.setDate(today.getDate() + 1);
// check if event exists in table
for (let i = 0; i < events.length; i++) {
const ev = events[i];
if ((reason.includes(ev.name)) || (ignoreCaseInEventname && (reason.toLowerCase().includes(ev.name.toLowerCase())))) {
// check if event should shown
result = ev.display;
adapter.log.debug(`found event in table: ${ev.name}, day=${ev.day}`);
const inXDays = new Date(today.getTime());
inXDays.setDate(today.getDate() + ev.day);
const inXDaysPlusOne = new Date(today.getTime());
inXDaysPlusOne.setDate(today.getDate() + ev.day + 1);
// If full day event
// Follow processing only if event is today
if (
((!ev.type || ev.type === 'today') && event.end.getTime() > inXDays.getTime() && event.start.getTime() < inXDaysPlusOne.getTime()) ||
(ev.type === 'now' && event.start <= realnow && realnow <= event.end) ||
(ev.type === 'later' && event.start > realnow && event.start.getTime() < tomorrow.getTime())
) {
adapter.log.debug(`${ev.type ? ev.type : `day ${ev.day}`} Event with time: ${event.start} ${realnow} ${event.end}`);
// If yet processed
if (ev.processed) {
// nothing to do
adapter.log.debug(`Event ${ev.name} already processed`);
} else {
adapter.log.debug(`Checking event ${ev.day} ${ev.type} ${ev.name} = ${ev.processed}, state = ${ev.state}`);
// Process event
ev.processed = true;
if (!ev.state) {
ev.state = true;
const name = `events.${ev.day}.${ev.type ? `${ev.type}.` : ''}${shrinkStateName(ev.name)}`;
adapter.log.info(`Set ${name} to true`);
await adapter.setStateAsync(name, {val: true, ack: true});
if (ev.id) {
await setState(ev.id, ev.on, ev.ack);
}
}
}
}
}
}
return result;
}
function initEvent(name, display, day, type, id, on, off, ack, callback) {
const obj = {
name,
processed: false,
state: null,
display,
day,
type
};
if (type === 'now' && id) {
obj.id = id;
obj.off = off;
obj.on = on;
if (typeof ack !== 'boolean') { // backward compatibility
ack = true;
} else {
ack = !!ack;
}
obj.ack = ack;
}
events.push(obj);
const stateName = `events.${day}.${type ? `${type}.` : ''}${shrinkStateName(name)}`;
adapter.getState(stateName, async (err, state) => {
if (err || !state) {
obj.state = false;
await adapter.setStateAsync(stateName, {val: false, ack: true});
await setState(id, off, ack);
callback && callback(name)
} else {
obj.state = state.val;
callback && callback(name);
}
});
}
function removeNameSpace(id) {
const re = new RegExp(`${adapter.namespace}*.`, 'g');
return id.replace(re, '');
}
function shrinkStateName(v) {
let n = v.replace(/[\s."`'*,\\?<>[\];:]+/g, '');
if ((!n && typeof n != 'number') || 0 === n.length) {
n = 'onlySpecialCharacters';
}
return n;
}
// Create new user events and remove existing, but deleted in config
function syncUserEvents(callback) {
let count = 0;
const days = parseInt(adapter.config.daysPreview, 10) + 1;
// Read all actual events
adapter.getStatesOf('', 'events', async (err, states) => {
if (stopped) return;
const toAdd = [];
const toDel = [];
if (states) {
// Add "to delete" all existing events
for (let j = 0; j < states.length; j++) {
toDel.push({id: removeNameSpace(states[j]._id), name: states[j].common.name});
}
}
// Add "to add" all configured events
for (let i = 0; i < adapter.config.events.length; i++) {
for (let day = 0; day < days; day++) {
const name = adapter.config.events[i].name;
if (!day) {
toAdd.push({id: `events.${day}.later.${shrinkStateName(name)}`, name: name});
toAdd.push({id: `events.${day}.today.${shrinkStateName(name)}`, name: name});
toAdd.push({id: `events.${day}.now.${shrinkStateName(name)}`, name: name});
} else {
toAdd.push({id: `events.${day}.${shrinkStateName(name)}`, name: name});
}
}
}
if (states) {
function removeFromToDel(day, name) {
const pos_ = toDel.indexOf(toDel.find(x => x.id === `events.${day}.${name}`));
if (pos_ !== -1) {
toDel.splice(pos_, 1);
}
}
for (let j = 0; j < states.length; j++) {
for (let i = 0; i < adapter.config.events.length; i++) {
for (let day = 0; day < days; day++) {
if (states[j].common.name === adapter.config.events[i].name) {
// remove it from "toDel"
const name = shrinkStateName(adapter.config.events[i].name);
if (!day) {
removeFromToDel(`${day}.today`, name);
removeFromToDel(`${day}.now`, name);
removeFromToDel(`${day}.later`, name);
} else {
removeFromToDel(day, name);
}
}
}
}
}
function removeFromToAdd(name) {
const pos_ = toAdd.indexOf(toAdd.find(x => x.id === name));
if (pos_ !== -1) {
toAdd.splice(pos_, 1);
}
}
for (let day = 0; day < days; day++) {
for (let i = 0; i < adapter.config.events.length; i++) {
for (let j = 0; j < states.length; j++) {
const event = adapter.config.events[i];
const name = shrinkStateName(event.name);
if (states[j].common.name === event.name &&
((day > 0 && removeNameSpace(states[j]._id) === `events.${day}.${name}`) ||
(!day && (
removeNameSpace(states[j]._id) === `events.${day}.today.${name}` ||
removeNameSpace(states[j]._id) === `events.${day}.now.${name}` ||
removeNameSpace(states[j]._id) === `events.${day}.later.${name}`
)))
) {
if (event.enabled === 'true') {
event.enabled = true;
}
if (event.enabled === 'false') {
event.enabled = false;
}
if (event.display === 'true') {
event.display = true;
}
if (event.display === 'false') {
event.display = false;
}
// if settings does not changed
if (states[j].native &&
states[j].native.enabled === event.enabled &&
states[j].native.display === event.display) {
// remove it from "toAdd"
removeFromToAdd(removeNameSpace(states[j]._id));
}
}
}
}
}
}
// Add states
for (let i = 0; i < toAdd.length; i++) {
for (let j = 0; j < adapter.config.events.length; j++) {
const configItem = adapter.config.events[j];
if (configItem.name === toAdd[i].name) {
if (configItem.enabled === 'true') {
configItem.enabled = true;
}
if (configItem.enabled === 'false') {
configItem.enabled = false;
}
if (configItem.display === 'true') {
configItem.display = true;
}
if (configItem.display === 'false') {
configItem.display = false;
}
// Add or update state
try {
const id = await adapter.setObjectAsync(toAdd[i].id,
{
type: 'state',
common: {
name: toAdd[i].name,
type: 'boolean',
role: 'indicator'
},
native: {
enabled: configItem.enabled,
display: configItem.display
}
});
adapter.log.info(`Event "${id.id}" created`);
} catch (err) {
adapter.log.warn(`Event "${toAdd[i].id}" could ne be created: ${err}`);
}
}
}
}
// Remove states
for (let i = 0; i < toDel.length; i++) {
await adapter.delObjectAsync(toDel[i].id);
await adapter.delStateAsync(toDel[i].id);
}
for (let day = 0; day < days; day++) {
for (let i = 0; i < adapter.config.events.length; i++) {
const event = adapter.config.events[i];
// If event enabled add it to list
if (event.enabled) {
if (!day) {
count += 3;
initEvent(event.name, event.display, 0, 'today', null, null, null, null,() => !--count && callback());
initEvent(event.name, event.display, 0, 'now', event.id, event.on, event.off, event.ack,() => !--count && callback());
initEvent(event.name, event.display, 0, 'later', null, null, null, null,() => !--count && callback());
} else {
count++;
initEvent(event.name, event.display, day, null, null, null, null, null,() => !--count && callback());
}
}
}
}
!count && callback();
});
}
function buildFilter(filter, filterregex) {
let ret = null;
let prep = '';
if (filterregex === 'true' || filterregex === true) {
prep = filter;
} else {
const list = (filter || '').split(';');
for (let i = 0; i < list.length; i++) {
const item = list[i].trim();
if(!item) {
continue;
}
if(prep) {
prep += '|';
}
prep += `(${item})`;
}
if(prep) {
prep = `/${prep}/g`;
}
}
if (prep) {
try {
const s = prep.split('/');
ret = new RegExp(s[1], s[2]);
} catch (e) {
adapter.log.error(`invalid filter: ${prep}`);
}
}
return ret;
}
// Read all calendar
function readAll() {
datesArray = [];
let count = 0;
let errCnt = 0;
// Set all events as not processed
for (let j = 0; j < events.length; j++) {
events[j].processed = false;
}
if (adapter.config.calendars) {