-
Notifications
You must be signed in to change notification settings - Fork 12
/
cronplus.js
2402 lines (2316 loc) · 124 KB
/
cronplus.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
/*
MIT License
Copyright (c) 2019, 2020, 2021, 2022 Steve-Mcl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
const cronstrue = require('cronstrue')
const cronosjs = require('cronosjs')
const prettyMs = require('pretty-ms')
const coordParser = require('coord-parser')
const SunCalc = require('suncalc2')
const path = require('path')
const fs = require('fs')
SunCalc.addTime(-18, 'nightEnd', 'nightStart')
SunCalc.addTime(-6, 'civilDawn', 'civilDusk')
SunCalc.addTime(6, 'morningGoldenHourEnd', 'eveningGoldenHourStart')
const PERMITTED_SOLAR_EVENTS = [
'nightEnd',
// "astronomicalDawn",
'nauticalDawn',
'civilDawn',
// "morningGoldenHourStart",
'sunrise',
'sunriseEnd',
'morningGoldenHourEnd',
'solarNoon',
'eveningGoldenHourStart',
'sunsetStart',
'sunset',
// "eveningGoldenHourEnd",
'civilDusk',
'nauticalDusk',
// "astronomicalDusk",
'nightStart',
'nadir'
]
// accepted commands using topic as the command & (in compatible cases, the payload is the schedule name)
// commands not supported by topic are : add/update & describe
const controlTopics = [
{ command: 'trigger', payloadIsName: true },
{ command: 'status', payloadIsName: true },
{ command: 'list', payloadIsName: true },
{ command: 'export', payloadIsName: true },
{ command: 'stop', payloadIsName: true },
{ command: 'stop-all', payloadIsName: false },
{ command: 'stop-all-dynamic', payloadIsName: false },
{ command: 'stop-all-static', payloadIsName: false },
{ command: 'pause', payloadIsName: true },
{ command: 'pause-all', payloadIsName: false },
{ command: 'pause-all-dynamic', payloadIsName: false },
{ command: 'pause-all-static', payloadIsName: false },
{ command: 'start', payloadIsName: true },
{ command: 'start-all', payloadIsName: false },
{ command: 'start-all-dynamic', payloadIsName: false },
{ command: 'start-all-static', payloadIsName: false },
{ command: 'clear', payloadIsName: false },
{ command: 'remove', payloadIsName: true },
{ command: 'delete', payloadIsName: true },
{ command: 'debug', payloadIsName: true },
{ command: 'next', payloadIsName: false }
]
const addExtendedControlTopics = function (baseCommand) {
controlTopics.push({ command: `${baseCommand}-all`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-all-dynamic`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-all-static`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-active`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-active-dynamic`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-active-static`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-inactive`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-inactive-dynamic`, payloadIsName: false })
controlTopics.push({ command: `${baseCommand}-inactive-static`, payloadIsName: false })
}
addExtendedControlTopics('trigger')
addExtendedControlTopics('status')
addExtendedControlTopics('export')
addExtendedControlTopics('list')
addExtendedControlTopics('remove')
addExtendedControlTopics('delete')
addExtendedControlTopics('debug')
/**
* Humanize a cron express
* @param {string} expression the CRON expression to humanize
* @returns {string}
* A human readable version of the expression
*/
const humanizeCron = function (expression, locale) {
try {
const opt = { use24HourTimeFormat: true }
if (locale) opt.locale = locale
return cronstrue.toString(expression, opt)
} catch (error) {
return `Cannot parse expression '${expression}'`
}
}
/**
* Validate a schedule options. Returns true if OK otherwise throws an appropriate error
* @param {object} opt the options object to validate
* @param {boolean} permitDefaults allow certain items to be a default (missing value)
* @returns {boolean}
*/
function validateOpt (opt, permitDefaults = true) {
if (!opt) {
throw new Error('Schedule options are undefined')
}
if (!opt.name) {
throw new Error('Schedule name property missing')
}
if (!opt.expressionType || opt.expressionType === 'cron' || opt.expressionType === 'dates') { // cron
if (!opt.expression) {
throw new Error(`Schedule '${opt.name}' - expression property missing`)
}
let valid = false
try {
valid = cronosjs.validate(opt.expression)
if (valid) { opt.expressionType = 'cron' }
} catch (error) {
console.debug(error)
}
try {
if (!valid) {
valid = isDateSequence(opt.expression)
if (valid) { opt.expressionType = 'dates' }
}
} catch (error) {
console.debug(error)
}
if (!valid) {
throw new Error(`Schedule '${opt.name}' - expression '${opt.expression}' must be either a cron expression, a date, an a array of dates or a CSV of dates`)
}
} else if (opt.expressionType === 'solar') {
if (!opt.offset) {
opt.offset = 0
}
if (opt.locationType === 'fixed' || opt.locationType === 'env') {
// location comes from node
} else {
if (!opt.location) {
throw new Error(`Schedule '${opt.name}' - location property missing`)
}
}
if (opt.solarType !== 'selected' && opt.solarType !== 'all') {
throw new Error(`Schedule '${opt.name}' - solarType property invalid or mising. Must be either "all" or "selected"`)
}
if (opt.solarType === 'selected') {
if (!opt.solarEvents) {
throw new Error(`Schedule '${opt.name}' - solarEvents property missing`)
}
let solarEvents
if (typeof opt.solarEvents === 'string') {
solarEvents = opt.solarEvents.split(',')
} else if (Array.isArray(opt.solarEvents)) {
solarEvents = opt.solarEvents
} else {
throw new Error(`Schedule '${opt.name}' - solarEvents property is invalid`)
}
if (!solarEvents.length) {
throw new Error(`Schedule '${opt.name}' - solarEvents property is empty`)
}
for (let index = 0; index < solarEvents.length; index++) {
const element = solarEvents[index].trim()
if (!PERMITTED_SOLAR_EVENTS.includes(element)) {
throw new Error(`Schedule '${opt.name}' - solarEvents entry '${element}' is invalid`)
}
}
}
} else {
throw new Error(`Schedule '${opt.name}' - invalid schedule type '${opt.expressionType}'. Expected expressionType to be 'cron', 'dates' or 'solar'`)
}
if (permitDefaults) {
opt.payload = ((opt.payload === null || opt.payload === '') && opt.payloadType === 'num') ? 0 : opt.payload
opt.payload = ((opt.payload === null || opt.payload === '') && opt.payloadType === 'str') ? '' : opt.payload
opt.payload = ((opt.payload === null || opt.payload === '') && opt.payloadType === 'bool') ? false : opt.payload
}
if (!opt.payloadType === 'default' && opt.payload === null) {
throw new Error(`Schedule '${opt.name}' - payload property missing`)
}
const okTypes = ['default', 'flow', 'global', 'str', 'num', 'bool', 'json', 'jsonata', 'bin', 'date', 'env']
// eslint-disable-next-line eqeqeq
const typeOK = okTypes.find(el => { return el == opt.payloadType })
if (!typeOK) {
throw new Error(`Schedule '${opt.name}' - type property '${opt.payloadType}' is not valid. Must be one of the following... ${okTypes.join(',')}`)
}
return true
}
/**
* Tests if a string or array of date like items are a date or date sequence
* @param {String|Array} data An array of date like entries or a CSV string of dates
*/
function isDateSequence (data) {
try {
const ds = parseDateSequence(data)
return (ds && ds.isDateSequence)
// eslint-disable-next-line no-empty
} catch (error) { }
return false
}
/**
* Returns an object describing the parameters.
* @param {string} expression The expressions or coordinates to use
* @param {string} expressionType The expression type ("cron" | "solar" | "dates")
* @param {string} timeZone An optional timezone to use
* @param {number} offset An optional offset to apply
* @param {string} solarType Specifies either "all" or "selected" - related to solarEvents property
* @param {string} solarEvents a CSV of solar events to be included
* @param {date} time Optional time to use (defaults to Date.now() if excluded)
*/
function _describeExpression (expression, expressionType, timeZone, offset, solarType, solarEvents, time, opts) {
const now = time ? new Date(time) : new Date()
opts = opts || {}
let result = { description: undefined, nextDate: undefined, nextDescription: undefined, prettyNext: 'Never' }
const cronOpts = timeZone ? { timezone: timeZone } : undefined
let ds = null
let dsOk = false
let exOk = false
// let now = new Date();
if (solarType === 'all') {
solarEvents = PERMITTED_SOLAR_EVENTS.join(',')
}
if (expressionType === 'solar') {
const opt = {
locationType: opts.locationType || opts.defaultLocationType,
defaultLocationType: opts.defaultLocationType,
defaultLocation: opts.defaultLocation,
expressionType,
location: expression,
offset: offset || 0,
name: 'dummy',
solarType,
solarEvents,
payloadType: 'default',
payload: ''
}
if (validateOpt(opt)) {
const pos = coordParser(opt.location)
const offset = isNumber(opt.offset) ? parseInt(opt.offset) : 0
const nowOffset = new Date(now.getTime() - offset * 60000)
result = getSolarTimes(pos.lat, pos.lon, 0, solarEvents, now, offset)
// eslint-disable-next-line eqeqeq
if (opts.includeSolarStateOffset && offset != 0) {
const ssOffset = getSolarTimes(pos.lat, pos.lon, 0, solarEvents, nowOffset, 0)
result.solarStateOffset = ssOffset.solarState
}
result.offset = offset
result.now = now
result.nowOffset = nowOffset
ds = parseDateSequence(result.eventTimes.map((event) => event.timeOffset))
dsOk = ds && ds.isDateSequence
}
} else {
if (expressionType === 'cron' || expressionType === '') {
exOk = cronosjs.validate(expression)
} else {
ds = parseDateSequence(expression)
dsOk = ds.isDateSequence
}
if (!exOk && !dsOk) {
result.description = 'Invalid expression'
return result
}
}
if (dsOk) {
const task = ds.task
const dates = ds.dates
const dsFutureDates = dates.filter(d => d >= now)
const count = dsFutureDates ? dsFutureDates.length : 0
result.description = 'Date sequence with fixed dates'
if (task && task._sequence && count) {
result.nextDate = dsFutureDates[0]
const ms = result.nextDate.valueOf() - now.valueOf()
result.prettyNext = (result.nextEvent ? result.nextEvent + ' ' : '') + `in ${prettyMs(ms, { secondsDecimalDigits: 0, verbose: true })}`
if (expressionType === 'solar') {
if (solarType === 'all') {
result.description = 'All Solar Events'
} else {
result.description = "Solar Events: '" + solarEvents.split(',').join(', ') + "'"
}
} else {
if (count === 1) {
result.description = 'One time at ' + formatShortDateTimeWithTZ(result.nextDate, timeZone)
} else {
result.description = count + ' Date Sequences starting at ' + formatShortDateTimeWithTZ(result.nextDate, timeZone)
}
result.nextDates = dsFutureDates.slice(0, 5)
}
}
}
if (exOk) {
const ex = cronosjs.CronosExpression.parse(expression, cronOpts)
const next = ex.nextDate()
if (next) {
const ms = next.valueOf() - now.valueOf()
result.prettyNext = `in ${prettyMs(ms, { secondsDecimalDigits: 0, verbose: true })}`
try {
result.nextDates = ex.nextNDates(now, 5)
} catch (error) {
console.debug(error)
}
}
result.description = humanizeCron(expression)
result.nextDate = next
}
return result
}
/**
* Returns a formatted string based on the provided tz.
* If tz is not specified, then Date.toString() is used
* @param {Date | string | number} date The date to format
* @param {string} [tz] Timezone to use (exclude to use system)
* @returns {string}
* The formatted date or empty string if `date` is null|undefined
*/
function formatShortDateTimeWithTZ (date, tz) {
if (!date) {
return ''
}
let dateString
const o = {
timeZone: tz || undefined,
timeZoneName: 'short',
hourCycle: 'h23',
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}
try {
dateString = new Intl.DateTimeFormat('default', o).format(new Date(date))
} catch (error) {
dateString = 'Error. Check timezone setting'
}
return dateString
}
/**
* Determine if a variable is a number
* @param {string|number} n The string or number to test
* @returns {boolean}
*/
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n)
}
/**
* Determine if a variable is a valid object
* NOTE: Arrays are also objects - be sure to use Array.isArray if you need to know the difference
* @param {*} o The variable to test
* @returns {boolean}
*/
function isObject (o) {
return (typeof o === 'object' && o !== null)
}
/**
* Determine if a variable is a valid date
* @param {*} d The variable to test
* @returns {boolean}
*/
function isValidDateObject (d) {
return d instanceof Date && !isNaN(d)
}
/**
* Determine if a variable is a cron like string
* @param {string} expression The variable to test
* @returns {boolean}
*/
function isCronLike (expression) {
if (typeof expression !== 'string') return false
if (expression.includes('*')) return true
const cleaned = expression.replace(/\s\s+/g, ' ')
const spaces = cleaned.split(' ')
return spaces.length >= 4 && spaces.length <= 6
}
/**
* Apply defaults to the cron schedule object
* @param {integer} optionIndex An index number to use for defaults
* @param {object} option The option object to update
*/
function applyOptionDefaults (node, option, optionIndex) {
if (isObject(option) === false) {
return// no point in continuing
}
optionIndex = optionIndex == null ? 0 : optionIndex
// eslint-disable-next-line eqeqeq
if (option.expressionType == '') {
if (isDateSequence(option.expression)) {
option.expressionType = 'dates'
} else {
option.expressionType = 'cron'// if empty, default to cron
}
} else if (['cron', 'dates', 'solar'].indexOf(option.expressionType) < 0) {
// if expressionType is not cron or solar - it might be sunrise or sunset from an older version
if (option.expressionType === 'sunrise') {
option.solarEvents = option.solarEvents || 'sunrise'
option.expressionType = 'solar'
} else if (option.expressionType === 'sunset') {
option.solarEvents = option.solarEvents || 'sunset'
option.expressionType = 'solar'
} else {
option.expressionType = 'cron'
}
}
option.name = option.name || 'schedule' + (optionIndex + 1)
option.topic = option.topic || option.name
option.payloadType = option.payloadType || option.type
if (option.payloadType == null && typeof option.payload === 'string' && option.payload.length) {
option.payloadType = 'str'
}
option.payloadType = option.payloadType || 'default'
delete option.type
if (option.expressionType === 'cron' && !option.expression) option.expression = '0 * * * * * *'
if (option.expressionType === 'solar') {
if (!option.solarType) option.solarType = option.solarEvents ? 'selected' : 'all'
if (!option.solarEvents) option.solarEvents = 'sunrise,sunset'
if (!option.location) option.location = ''
option.locationType = node.defaultLocationType
}
}
function parseDateSequence (expression) {
const result = { isDateSequence: false, expression }
let dates = expression
if (typeof expression === 'string') {
const spl = expression.split(',')
for (let index = 0; index < spl.length; index++) {
spl[index] = spl[index].trim()
if (isCronLike(spl[index])) {
return result// fail
}
}
dates = spl.map(x => {
if (isNumber(x)) {
x = parseInt(x)
}
const d = new Date(x)
return d
})
}
const ds = new cronosjs.CronosTask(dates)
if (ds && ds._sequence) {
result.dates = ds._sequence._dates
result.task = ds
result.isDateSequence = true
}
return result
}
function parseSolarTimes (opt) {
// opt.location = location || ''
const pos = coordParser(opt.location || '0.0,0.0')
const offset = opt.offset ? parseInt(opt.offset) : 0
const date = opt.date ? new Date(opt.date) : new Date()
const events = opt.solarType === 'all' ? PERMITTED_SOLAR_EVENTS : opt.solarEvents
const result = getSolarTimes(pos.lat, pos.lon, 0, events, date, offset)
const task = parseDateSequence(result.eventTimes.map((o) => o.timeOffset))
task.solarEventTimes = result
return task
}
function getSolarTimes (lat, lng, elevation, solarEvents, startDate = null, offset = 0) {
// performance.mark('Start');
const solarEventsPast = [...PERMITTED_SOLAR_EVENTS]
const solarEventsFuture = [...PERMITTED_SOLAR_EVENTS]
const solarEventsArr = []
// get list of usable solar events into solarEventsArr
let solarEventsArrTemp = []
if (typeof solarEvents === 'string') {
solarEventsArrTemp = solarEvents.split(',')
} else if (Array.isArray(solarEvents)) {
solarEventsArrTemp = [...solarEvents]
} else {
throw new Error('solarEvents must be a CSV or Array')
}
for (let index = 0; index < solarEventsArrTemp.length; index++) {
const se = solarEventsArrTemp[index].trim()
if (PERMITTED_SOLAR_EVENTS.includes(se)) {
solarEventsArr.push(se)
}
}
offset = isNumber(offset) ? parseInt(offset) : 0
elevation = isNumber(elevation) ? parseInt(elevation) : 0// not used for now
startDate = startDate ? new Date(startDate) : new Date()
let scanDate = new Date(startDate.toDateString()) // new Date(startDate); //scanDate = new Date(startDate.toDateString())
scanDate.setDate(scanDate.getDate() + 1)// fwd one day to catch times behind of scan day
let loopMonitor = 0
const result = []
// performance.mark('initEnd')
// performance.measure('Start to Now', 'Start', 'initEnd')
// performance.mark('FirstScanStart');
// first scan backwards to get prior solar events
while (loopMonitor < 3 && solarEventsPast.length) {
loopMonitor++
const timesIteration1 = SunCalc.getTimes(scanDate, lat, lng)
// timesIteration1 = new SolarCalc(scanDate,lat,lng);
for (let index = 0; index < solarEventsPast.length; index++) {
const se = solarEventsPast[index]
const seTime = timesIteration1[se]
const seTimeOffset = new Date(seTime.getTime() + offset * 60000)
if (isValidDateObject(seTimeOffset) && seTimeOffset <= startDate) {
result.push({ event: se, time: seTime, timeOffset: seTimeOffset })
solarEventsPast.splice(index, 1)// remove that item
index--
}
}
scanDate.setDate(scanDate.getDate() - 1)
}
scanDate = new Date(startDate.toDateString())
scanDate.setDate(scanDate.getDate() - 1)// back one day to catch times ahead of current day
loopMonitor = 0
// now scan forwards to get future events
while (loopMonitor < 183 && solarEventsFuture.length) {
loopMonitor++
const timesIteration2 = SunCalc.getTimes(scanDate, lat, lng)
// timesIteration2 = new SolarCalc(scanDate,lat,lng);
for (let index = 0; index < solarEventsFuture.length; index++) {
const se = solarEventsFuture[index]
const seTime = timesIteration2[se]
const seTimeOffset = new Date(seTime.getTime() + offset * 60000)
if (isValidDateObject(seTimeOffset) && seTimeOffset > startDate) {
result.push({ event: se, time: seTime, timeOffset: seTimeOffset })
solarEventsFuture.splice(index, 1)// remove that item
index--
}
}
scanDate.setDate(scanDate.getDate() + 1)
}
// performance.mark('SecondScanEnd');
// performance.measure('FirstScanEnd to SecondScanEnd', 'FirstScanEnd', 'SecondScanEnd');
// sort the results to get a timeline
const sorted = result.sort((a, b) => {
if (a.time < b.time) {
return -1
} else if (a.time > b.time) {
return 1
} else {
return 0
}
})
// now scan through sorted solar events to determine day/night/twilight etc
let state = ''; const solarState = {}
for (let index = 0; index < sorted.length; index++) {
const event = sorted[index]
if (event.time < startDate) {
switch (event.event) {
case 'nightEnd':
state = 'Astronomical Twilight'// todo: i18n
updateSolarState(solarState, state, 'rise', false, false, true, false, false, false, false)
break
// case "astronomicalDawn":
// state = "Astronomical Twilight";//todo: i18n
// updateSolarState(solarState,state,"rise",false,false,true,false,false,false,false);
// break;
case 'nauticalDawn':
state = 'Nautical Twilight'
updateSolarState(solarState, state, 'rise', false, false, false, true, false, false, false)
break
case 'civilDawn':
state = 'Civil Twilight'
updateSolarState(solarState, state, 'rise', false, false, false, false, true, true, false)
break
// case "morningGoldenHourStart":
// updateSolarState(solarState,null,"rise",false,false,false,false,true,true,false);
// break;
case 'sunrise':
state = 'Civil Twilight'
updateSolarState(solarState, state, 'rise', false, false, false, false, true, true, false)
break
case 'sunriseEnd':
state = 'Day'
updateSolarState(solarState, state, 'rise', true, false, false, false, false, true, false)
break
case 'morningGoldenHourEnd':
state = 'Day'
updateSolarState(solarState, state, 'rise', true, false, false, false, false, false, false)
break
case 'solarNoon':
updateSolarState(solarState, null, 'fall')
break
case 'eveningGoldenHourStart':
state = 'Day'
updateSolarState(solarState, state, 'fall', true, false, false, false, false, false, true)
break
case 'sunsetStart':
state = 'Day'
updateSolarState(solarState, state, 'fall', true, false, false, false, false, false, true)
break
case 'sunset':
state = 'Civil Twilight'
updateSolarState(solarState, state, 'fall', false, false, false, false, true, false, true)
break
// case "eveningGoldenHourEnd":
// state = "Nautical Twilight";
// updateSolarState(solarState,state,"fall",false,false,false,false,true,false,false);
// break;
case 'civilDusk':
state = 'Nautical Twilight'
updateSolarState(solarState, state, 'fall', false, false, false, true, false, false, false)
break
case 'nauticalDusk':
state = 'Astronomical Twilight'
updateSolarState(solarState, state, 'fall', false, false, true, false, false, false, false)
break
// case "astronomicalDusk":
case 'night':
case 'nightStart':
state = 'Night'
updateSolarState(solarState, state, 'fall', false, true, false, false, false, false, false)
break
case 'nadir':
updateSolarState(solarState, null, 'rise')
break
}
} else {
break
}
}
// update final states
updateSolarState(solarState)// only sending `stateObject` makes updateSolarState() compute dawn/dusk etc
// now filter to only events of interest
const futureEvents = sorted.filter((e) => e && e.timeOffset >= startDate)
const wantedFutureEvents = []
for (let index = 0; index < futureEvents.length; index++) {
const fe = futureEvents[index]
if (solarEventsArr.includes(fe.event)) {
wantedFutureEvents.push(fe)
}
}
const nextType = wantedFutureEvents[0].event
const nextTime = wantedFutureEvents[0].time
const nextTimeOffset = wantedFutureEvents[0].timeOffset
// performance.mark('End')
// performance.measure('SecondScanEnd to End', 'SecondScanEnd', 'End')
// performance.measure('Start to End', 'Start', 'End')
return {
solarState,
nextEvent: nextType,
nextEventTime: nextTime,
nextEventTimeOffset: nextTimeOffset,
eventTimes: wantedFutureEvents
// allTimes: sorted,
// eventTimesByType: resultCategories
}
function updateSolarState (stateObject, state, direction, day, night,
astrologicalTwilight, nauticalTwilight, civilTwilight,
morningGoldenHour, eveningGoldenHour) {
if (arguments.length > 1) {
if (state) stateObject.state = state
stateObject.direction = direction
if (arguments.length > 3) {
stateObject.day = day
stateObject.night = night
stateObject.astrologicalTwilight = astrologicalTwilight
stateObject.nauticalTwilight = nauticalTwilight
stateObject.civilTwilight = civilTwilight
stateObject.goldenHour = morningGoldenHour || eveningGoldenHour
stateObject.twilight = stateObject.astrologicalTwilight || stateObject.nauticalTwilight || stateObject.civilTwilight
}
return
}
stateObject.morningTwilight = stateObject.direction === 'rise' && stateObject.twilight
stateObject.eveningTwilight = stateObject.direction === 'fall' && stateObject.twilight
stateObject.dawn = stateObject.direction === 'rise' && stateObject.civilTwilight
stateObject.dusk = stateObject.direction === 'fall' && stateObject.civilTwilight
stateObject.morningGoldenHour = stateObject.direction === 'rise' && stateObject.goldenHour
stateObject.eveningGoldenHour = stateObject.direction === 'fall' && stateObject.goldenHour
}
}
function exportTask (task, includeStatus) {
const o = {
topic: task.node_topic || task.name,
name: task.name || task.node_topic,
index: task.node_index,
payloadType: task.node_payloadType,
payload: task.node_payload,
limit: task.node_limit || null,
expressionType: task.node_expressionType
}
if (o.expressionType === 'solar') {
o.solarType = task.node_solarType
o.solarEvents = task.node_solarEvents
o.location = task.node_location
o.offset = task.node_offset
} else {
o.expression = task.node_expression
}
if (includeStatus) {
o.isDynamic = task.isDynamic === true
o.modified = task.node_modified === true
o.isRunning = task.isRunning === true
o.count = task.node_count
}
return o
}
function isTaskFinished (_task) {
if (!_task) return true
return _task.node_limit ? _task.node_count >= _task.node_limit : false
}
function getTaskStatus (node, task, opts) {
opts = opts || {}
opts.locationType = node.defaultLocationType
opts.defaultLocation = node.defaultLocation
opts.defaultLocationType = node.defaultLocationType
const sol = task.node_expressionType === 'solar'
const exp = sol ? task.node_location : task.node_expression
const h = _describeExpression(exp, task.node_expressionType, node.timeZone, task.node_offset, task.node_solarType, task.node_solarEvents, null, opts)
let nextDescription = null
let nextDate = null
const running = !isTaskFinished(task)
if (running) {
// nextDescription = h.nextDescription;
nextDescription = h.prettyNext
nextDate = sol ? h.nextEventTimeOffset : h.nextDate
}
let tz = node.timeZone
let localTZ = ''
try {
localTZ = Intl.DateTimeFormat().resolvedOptions().timeZone
if (!tz) tz = localTZ
// eslint-disable-next-line no-empty
} catch (error) { }
const r = {
type: task.isDynamic ? 'dynamic' : 'static',
modified: !!task.modified,
isRunning: running && task.isRunning,
count: task.node_count,
limit: task.node_limit,
nextDescription,
nextDate: running ? nextDate : null,
nextDateTZ: running ? formatShortDateTimeWithTZ(nextDate, tz) : null,
timeZone: tz,
serverTime: new Date(),
serverTimeZone: localTZ,
description: h.description
}
if (sol) {
r.solarState = h.solarState
if (h.offset) r.solarStateOffset = h.solarStateOffset
r.solarTimes = running ? h.eventTimes : null
r.nextDescription = running ? nextDescription : null// r.solarTimes && (r.solarTimes[0].event + " " + r.nextDescription);
}
return r
}
let userDir = ''
let persistPath = ''
let FSAvailable = false
let contextAvailable = false
const cronplusDir = 'cronplusdata'
module.exports = function (RED) {
const STORE_NAMES = getStoreNames()
// when running tests, RED.settings.userDir & RED.settings.settingsFile (amongst others) are undefined
const testMode = typeof RED.settings.userDir === 'undefined' && typeof RED.settings.settingsFile === 'undefined'
if (testMode) {
FSAvailable = false
contextAvailable = false
} else {
userDir = RED.settings.userDir || ''
persistPath = path.join(userDir, cronplusDir)
try {
if (!fs.existsSync(persistPath)) {
fs.mkdirSync(persistPath)
}
FSAvailable = fs.existsSync(persistPath)
} catch (e) {
if (e.code !== 'EEXIST') {
RED.log.error(`cron-plus: Error creating persistence folder '${persistPath}'. ${e.message}`)
FSAvailable = false
}
}
contextAvailable = STORE_NAMES.length > 2 // 1st 2 are 'none' and 'file', any others are context stores
}
function CronPlus (config) {
RED.nodes.createNode(this, config)
const node = this
node.name = config.name
node.payloadType = config.payloadType || config.type || 'default'
delete config.type
node.payload = config.payload
node.crontab = config.crontab
node.outputField = config.outputField || 'payload'
node.timeZone = config.timeZone
node.options = config.options
node.commandResponseMsgOutput = config.commandResponseMsgOutput || 'output1'
node.defaultLocation = config.defaultLocation
node.defaultLocationType = config.defaultLocationType
node.outputs = 1
node.fanOut = false
node.queuedSerialisationRequest = null
node.serialisationRequestBusy = null
setInterval(async function () {
if (node.serialisationRequestBusy) return
if (node.queuedSerialisationRequest) {
node.serialisationRequestBusy = node.queuedSerialisationRequest
await serialise()
node.queuedSerialisationRequest = null
node.serialisationRequestBusy = null
}
}, 2500) // 2.5 seconds
// convert node.persistDynamic to a getter/setter
Object.defineProperty(node, 'persistDynamic', {
get: function () {
return !!node.storeName
}
})
// inherit/upgrade deprecated properties from config
const hasStoreNameProperty = Object.prototype.hasOwnProperty.call(config, 'storeName') && typeof config.storeName === 'string'
const hasDeprecatedPersistDynamic = Object.prototype.hasOwnProperty.call(config, 'persistDynamic') && typeof config.persistDynamic === 'boolean'
if (hasStoreNameProperty) {
// not an upgrade - let use this property
node.storeName = config.storeName
} else if (hasDeprecatedPersistDynamic) {
// upgrade from older version
node.storeName = config.persistDynamic ? 'file' : ''
} else {
// default
node.storeName = ''
}
if (node.storeName && node.storeName !== 'file' && STORE_NAMES.indexOf(node.storeName) < 0) {
node.warn(`Invalid store name specified '${node.storeName}' - state will not be persisted for this node`)
contextAvailable = false
}
if (config.commandResponseMsgOutput === 'output2') {
node.outputs = 2 // 1 output pins (all messages), 2 outputs (schedules out of pin1, command responses out of pin2)
} else if (config.commandResponseMsgOutput === 'fanOut') {
node.outputs = 2 + (node.options ? node.options.length : 0)
node.fanOut = true
} else {
config.commandResponseMsgOutput = 'output1'
}
node.statusUpdatePending = false
const MAX_CLOCK_DIFF = Number(RED.settings.CRONPLUS_MAX_CLOCK_DIFF || process.env.CRONPLUS_MAX_CLOCK_DIFF || 5000)
const clockMonitor = setInterval(async function timeChecker () {
const oldTime = timeChecker.oldTime || new Date()
const newTime = new Date()
const timeDiff = newTime - oldTime
timeChecker.oldTime = newTime
if (Math.abs(timeDiff) >= MAX_CLOCK_DIFF) {
node.log('System Time Change Detected - refreshing schedules! If the system time was not changed then this typically occurs due to blocking code elsewhere in your application')
await refreshTasks(node)
}
}, 1000)
const setProperty = function (msg, field, value) {
const set = (obj, path, val) => {
const keys = path.split('.')
const lastKey = keys.pop()
// eslint-disable-next-line no-return-assign
const lastObj = keys.reduce((obj, key) =>
obj[key] = obj[key] || {},
obj)
lastObj[lastKey] = val
}
set(msg, field, value)
}
const updateNodeNextInfo = (node, now) => {
const t = getNextTask(node.tasks)
if (t) {
const indicator = t.isDynamic ? 'ring' : 'dot'
const nx = (t._expression || t._sequence)
node.nextDate = nx.nextDate(now)
node.nextEvent = t.name
node.nextIndicator = indicator
if (t.node_solarEventTimes && t.node_solarEventTimes.nextEvent) {
node.nextEvent = t.node_solarEventTimes.nextEvent
}
} else {
node.nextDate = null
node.nextEvent = ''
node.nextIndicator = ''
}
}
const updateDoneStatus = (node, task) => {
let indicator = 'dot'
if (task) {
indicator = node.nextIndicator || 'dot'
}
node.status({ fill: 'green', shape: indicator, text: 'Done: ' + formatShortDateTimeWithTZ(Date.now(), node.timeZone) })
// node.nextDate = getNextTask(node.tasks);
const now = new Date()
updateNodeNextInfo(node, now)
const next = node.nextDate ? new Date(node.nextDate).valueOf() : (Date.now() + 5001)
const msTillNext = next - now
if (msTillNext > 5000) {
node.statusUpdatePending = true
setTimeout(function () {
node.statusUpdatePending = false
updateNextStatus(node, true)
}, 4000)
}
}
const sendMsg = async (node, task, cronTimestamp, manualTrigger) => {
const msg = { cronplus: {} }
msg.topic = task.node_topic
msg.cronplus.triggerTimestamp = cronTimestamp
const se = task.node_expressionType === 'solar' ? node.nextEvent : ''
msg.cronplus.status = getTaskStatus(node, task, { includeSolarStateOffset: true })
if (se) msg.cronplus.status.solarEvent = se
msg.cronplus.config = exportTask(task)
if (manualTrigger) msg.manualTrigger = true
msg.scheduledEvent = !msg.manualTrigger
const indicator = node.nextIndicator || 'dot'
const taskType = task.isDynamic ? 'dynamic' : 'static'
const index = task.node_index || 0
node.status({ fill: 'green', shape: indicator, text: 'Schedule Started' })
try {
if (task.node_payloadType !== 'flow' && task.node_payloadType !== 'global') {
let pl
if ((task.node_payloadType == null && task.node_payload === '') || task.node_payloadType === 'date') {
pl = Date.now()
} else if (task.node_payloadType == null) {
pl = task.node_payload
} else if (task.node_payloadType === 'none') {
pl = ''
} else if (task.node_payloadType === 'json' && isObject(task.node_payload)) {
pl = task.node_payload
} else if (task.node_payloadType === 'bin' && Array.isArray(task.node_payload)) {
pl = Buffer.from(task.node_payload)
} else if (task.node_payloadType === 'default') {
pl = msg.cronplus
delete msg.cronplus // To delete or not?
} else {
pl = await evaluateNodeProperty(task.node_payload, task.node_payloadType, node, msg)
}
setProperty(msg, node.outputField, pl)
node.send(generateSendMsg(node, msg, taskType, index))
updateDoneStatus(node, task)
} else {
const res = await evaluateNodeProperty(task.node_payload, task.node_payloadType, node, msg)
setProperty(msg, node.outputField, res)
node.send(generateSendMsg(node, msg, taskType, index))
updateDoneStatus(node, task)
}
} catch (err) {
node.error(err, msg)
}
}
(async function () {
try {
node.status({})
node.nextDate = null
if (!node.options) {
node.status({ fill: 'grey', shape: 'dot', text: 'Nothing set' })
return
}