forked from simatec/ioBroker.schoolfree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
291 lines (258 loc) · 13.1 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
'use strict';
const utils = require('@iobroker/adapter-core');
const request = require('request');
const fs = require('fs');
/** @type {number | undefined} */
let timerRequest;
/** @type {number | undefined} */
let timerError;
/**
* The adapter instance
* @type {ioBroker.Adapter}
*/
let adapter;
const adapterName = require('./package.json').name.split('.').pop();
/**
* Starts the adapter instance
* @param {Partial<ioBroker.AdapterOptions>} [options]
*/
function startAdapter(options) {
options = options || {};
Object.assign(options, { name: adapterName });
adapter = new utils.Adapter(options);
// start here!
adapter.on('ready', main); // Main method defined below for readability
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', (callback) => {
try {
adapter.log.debug('cleaned everything up...');
clearTimeout(timerRequest);
clearTimeout(timerError);
callback();
} catch (e) {
callback();
}
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
if (state) {
// The state was changed
adapter.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
} else {
// The state was deleted
adapter.log.debug(`state ${id} deleted`);
}
});
}
function checkHolidayNames() {
request(
{
url: 'https://www.mehr-schulferien.de/api/v2.0/holiday_or_vacation_types',
json: true
},
function (error, response, content) {
try {
checkState(content.data);
} catch (e) {
adapter.log.warn('schoolfree request error');
adapter.log.error(e);
timerError = setTimeout(function () {
adapter.stop();
}, 5000);
}
});
}
function checkState(holidayNames) {
// calc current date
let date = new Date();
let monthIndex = (date.getMonth() + 1);
let year = date.getFullYear();
let day = date.getDate();
let today = (year + '-' + ('0' + monthIndex).slice(-2) + '-' + ('0' + day).slice(-2));
// calc Tomorrow date
let dateTomorrow = new Date(date.getTime() + (1000 * 60 * 60 * 24 * 1));
let monthIndexTomorrow = (dateTomorrow.getMonth() + 1);
let yearTomorrow = dateTomorrow.getFullYear();
let dayTomorrow = dateTomorrow.getDate();
let Tomorrow = (yearTomorrow + '-' + ('0' + monthIndexTomorrow).slice(-2) + '-' + ('0' + dayTomorrow).slice(-2));
// request API from www.mehr-schulferien.de
request(
{
url: 'https://www.mehr-schulferien.de/api/v2.0/periods',
json: true
},
function (error, response, content) {
try {
let federalStateStr = 0;
let searchLocation = content.data.filter(d => d.location_id == adapter.config.schools);
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.schools;
} else {
searchLocation = content.data.filter(d => d.location_id == adapter.config.places);
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.places;
} else {
searchLocation = content.data.filter(d => d.location_id == adapter.config.counties);
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.counties;
} else {
federalStateStr = adapter.config.federalState;
}
}
}
//federalStateStr = adapter.config.federalState;
// Filter current federal State
const arrFederalState = content.data.filter(d => d.location_id == federalStateStr);
// Filter old holidays
const arrNewHoliday = arrFederalState.filter(d => d.ends_on >= today);
let arrOnlyholiday;
let resData;
if (adapter.config.ignorePublicHoliday) {
adapter.log.debug('ignore public holiday');
// Filter Long weekends
arrOnlyholiday = arrNewHoliday.filter(d => d.starts_on != d.ends_on);
// Filter Data
resData = arrOnlyholiday.map(({ starts_on, ends_on, holiday_or_vacation_type_id }) => ({ starts_on, ends_on, holiday_or_vacation_type_id }));
} else {
resData = arrNewHoliday.map(({ starts_on, ends_on, holiday_or_vacation_type_id }) => ({ starts_on, ends_on, holiday_or_vacation_type_id }));
}
// sort for start holiday
const result = resData.sort((a, b) => (a.starts_on > b.starts_on) ? 1 : -1);
let currentName = holidayNames.filter(d => d.id == result[0].holiday_or_vacation_type_id);
let nextName = holidayNames.filter(d => d.id == result[1].holiday_or_vacation_type_id);
if (result[0] && result[0].starts_on !== 'undefined') {
// Set schoolfree today
let currentStart;
let currentEnd;
currentStart = result[0].starts_on.split('-');
currentStart = (currentStart[2] + '.' + currentStart[1] + '.' + currentStart[0]);
currentEnd = result[0].ends_on.split('-');
currentEnd = (currentEnd[2] + '.' + currentEnd[1] + '.' + currentEnd[0]);
if (result[0].starts_on <= today && result[0].ends_on >= today) {
adapter.log.debug(`school free name: ${currentName[0].colloquial ? currentName[0].colloquial : currentName[0].name}`);
adapter.log.debug('school free today');
adapter.setState('info.today', { val: true, ack: true });
adapter.setState('info.current.start', { val: currentStart, ack: true });
adapter.setState('info.current.end', { val: currentEnd, ack: true });
adapter.setState('info.current.name', { val: currentName[0].colloquial ? currentName[0].colloquial : currentName[0].name, ack: true });
adapter.log.debug('string: ' + JSON.stringify(result[0]));
} else {
adapter.setState('info.today', { val: false, ack: true });
}
// Set schoolfree tomorrow
if (result[0].starts_on <= Tomorrow && result[0].ends_on >= Tomorrow) {
adapter.log.debug(`school free name: ${currentName[0].colloquial ? currentName[0].colloquial : currentName[0].name}`);
adapter.log.debug('school free tomorrow');
adapter.setState('info.tomorrow', { val: true, ack: true });
adapter.setState('info.current.start', { val: currentStart, ack: true });
adapter.setState('info.current.end', { val: currentEnd, ack: true });
adapter.setState('info.current.name', { val: currentName[0].colloquial ? currentName[0].colloquial : currentName[0].name, ack: true });
adapter.log.debug('string: ' + JSON.stringify(result[0]));
} else {
adapter.setState('info.tomorrow', { val: false, ack: true });
}
// clear schoolfree after holiday
if (result[0].starts_on > today && result[0].starts_on > Tomorrow) {
adapter.setState('info.current.start', { val: 'none', ack: true });
adapter.setState('info.current.end', { val: 'none', ack: true });
adapter.setState('info.current.name', { val: 'none', ack: true });
}
// Set next holiday
let nextStart;
let nextEnd;
if (result[0].starts_on > today) {
nextStart = result[0].starts_on.split('-');
nextStart = (nextStart[2] + '.' + nextStart[1] + '.' + nextStart[0]);
nextEnd = result[0].ends_on.split('-');
nextEnd = (nextEnd[2] + '.' + nextEnd[1] + '.' + nextEnd[0]);
adapter.setState('info.next.start', { val: nextStart, ack: true });
adapter.setState('info.next.end', { val: nextEnd, ack: true });
adapter.setState('info.next.name', { val: currentName[0].colloquial ? currentName[0].colloquial : currentName[0].name, ack: true });
} else if (result[0].starts_on <= today && result[0].ends_on >= today) {
if (result[1] && result[1].starts_on !== 'undefined') {
nextStart = result[1].starts_on.split('-');
nextStart = (nextStart[2] + '.' + nextStart[1] + '.' + nextStart[0]);
nextEnd = result[1].ends_on.split('-');
nextEnd = (nextEnd[2] + '.' + nextEnd[1] + '.' + nextEnd[0]);
adapter.setState('info.next.start', { val: nextStart, ack: true });
adapter.setState('info.next.end', { val: nextEnd, ack: true });
adapter.setState('info.next.name', { val: nextName[0].colloquial ? nextName[0].colloquial : nextName[0].name, ack: true });
} else {
adapter.setState('info.next.start', { val: 'No data available', ack: true });
adapter.setState('info.next.end', { val: 'No data available', ack: true });
adapter.setState('info.next.name', { val: 'No data available', ack: true });
}
}
adapter.log.info('schoolfree request done');
timerRequest = setTimeout(function () {
adapter.stop();
}, 20000);
}
} catch (e) {
adapter.log.warn('schoolfree request error');
adapter.log.error(e);
timerError = setTimeout(function () {
adapter.stop();
}, 20000);
}
});
}
function fillLocation() {
adapter.getState('data.locations', (err, state) => {
if (state) {
try {
const locations = JSON.parse(state.val);
const arrCounties = locations.filter(d => d.id == adapter.config.counties);
adapter.log.debug('counties number: ' + adapter.config.counties);
if (adapter.config.counties !== 'allCounties') {
adapter.setState('location.countieName', { val: arrCounties[0].name ? arrCounties[0].name : 'no selection', ack: true });
} else {
adapter.setState('location.countieName', { val: 'no selection', ack: true });
}
const arrPlaces = locations.filter(d => d.id == adapter.config.places);
adapter.log.debug('places number: ' + adapter.config.places);
if (adapter.config.places !== 'allPlaces') {
adapter.setState('location.placeName', { val: arrPlaces[0].name ? arrPlaces[0].name : 'no selection', ack: true });
} else {
adapter.setState('location.placeName', { val: 'no selection', ack: true });
}
const arrSchools = locations.filter(d => d.id == adapter.config.schools);
adapter.log.debug('schools number: ' + adapter.config.schools);
if (adapter.config.schools !== 'allschools') {
adapter.setState('location.schoolName', { val: arrSchools[0].name ? arrSchools[0].name : 'no selection', ack: true });
} else {
adapter.setState('location.schoolName', { val: 'no selection', ack: true });
}
} catch (e) {
adapter.log.warn('schoolfree set state error');
adapter.log.error(e);
}
}
});
}
function loadLocationsData() {
adapter.getState('data.locations', (err, state) => {
if (!state || !state.val) {
try {
const locations = require('./locations.json');
adapter.setState('data.locations', { val: JSON.stringify(locations), ack: true });
} catch (err) {
err && adapter.log.error(err);
adapter.log.error('Cannot parse data');
}
}
});
}
function main() {
// function for request
loadLocationsData();
fillLocation();
checkHolidayNames();
}
// If started as allInOne/compact mode => return function to create instance
if (module && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}