-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
365 lines (321 loc) · 15.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
'use strict';
const utils = require('@iobroker/adapter-core');
const axios = require('axios');
const fs = require('fs');
const tools = require('./lib/tools');
const schoolfreeURL = 'https://www.mehr-schulferien.de/api/v2.0/';
/** @type {number | undefined} */
let timerRequest;
/**
* 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);
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`);
}
});
}
async function checkHolidayNames() {
try {
const _holidayNames = await axios({
method: 'get',
url: schoolfreeURL + 'holiday_or_vacation_types/',
responseType: 'json'
});
if (_holidayNames && _holidayNames.data) {
const holidayNames = _holidayNames.data
adapter.log.debug(`schoolfree request holiday_or_vacation_types done`);
//adapter.log.debug(`schoolfree request holiday_or_vacation_types: ${JSON.stringify(holidayNames.data)}`);
try {
checkState(holidayNames.data);
} catch (e) {
adapter.log.warn(`schoolfree request holiday_or_vacation_types error: ${e}`);
stopSchoolfree();
}
} else {
adapter.log.warn('schoolfree request holiday_or_vacation_types error... API not reachable!!');
stopSchoolfree();
}
} catch (e) {
adapter.log.warn(`schoolfree request holiday_or_vacation_types error: ${e}`);
stopSchoolfree();
}
}
function stopSchoolfree() {
timerRequest = setTimeout(function () {
adapter.log.debug('schoolfree stopped ...')
adapter.stop();
}, 30000);
}
// only for update locations.json
async function locationsUpdate() {
try {
const _locationsUpdate = await axios({
method: 'get',
url: schoolfreeURL + 'locations/',
responseType: 'json'
});
adapter.log.debug(`schoolfree request locations done`);
if (_locationsUpdate && _locationsUpdate.data) {
try {
// @ts-ignore
const result = Object.values(_locationsUpdate.data).map(({ name, id, parent_location_id }) => ({ name, id, parent_location_id }));
adapter.log.debug(`schoolfree request locations: ${JSON.stringify(result)}`);
// @ts-ignore
if (fs.existsSync(__dirname + '/admin/locations.json')) {
fs.unlinkSync(__dirname + '/admin/locations.json');
}
fs.writeFileSync(__dirname + '/admin/locations.json', JSON.stringify(result));
} catch (e) {
adapter.log.warn(`schoolfree request locations error: ${e}`);
stopSchoolfree();
}
} else {
adapter.log.warn('schoolfree request locations error... API not reachable!!');
stopSchoolfree();
}
} catch (e) {
adapter.log.warn(`schoolfree request locations error: ${e}`);
stopSchoolfree();
}
}
async 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
try {
const _content = await axios({
method: 'get',
url: schoolfreeURL + 'periods/',
responseType: 'json'
});
const content = _content.data;
adapter.log.debug(`schoolfree request periods done`);
//adapter.log.debug(`schoolfree request periods: ${JSON.stringify(content.data)}`);
let federalStateStr = 0;
let searchLocation = [];
if (content && content.data !== undefined) {
if (adapter.config.schools !== 'allschools') {
// @ts-ignore
searchLocation = Object.values(content.data).filter(d => d.location_id == adapter.config.schools);
}
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.schools;
} else {
if (adapter.config.places !== 'allPlaces') {
// @ts-ignore
searchLocation = Object.values(content.data).filter(d => d.location_id == adapter.config.places);
}
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.places;
} else {
if (adapter.config.counties !== 'allCounties') {
// @ts-ignore
searchLocation = Object.values(content.data).filter(d => d.location_id == adapter.config.counties);
}
if (JSON.stringify(searchLocation) !== '[]') {
federalStateStr = adapter.config.counties;
} else {
federalStateStr = adapter.config.federalState;
}
}
}
} else {
adapter.log.warn('schoolfree request periods error... API not reachable!!');
stopSchoolfree();
}
// Filter current federal State
if (content && content.data !== undefined) {
// @ts-ignore
const arrFederalState = content.data.filter(d => d.location_id == federalStateStr);
// Filter old holidays
// @ts-ignore
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
// @ts-ignore
resData = arrOnlyholiday.map(({ starts_on, ends_on, holiday_or_vacation_type_id }) => ({ starts_on, ends_on, holiday_or_vacation_type_id }));
} else {
// @ts-ignore
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 = Object.values(holidayNames).filter(d => d.id == result[0].holiday_or_vacation_type_id);
let nextName = Object.values(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 if (result[1].starts_on == Tomorrow) {
adapter.setState('info.tomorrow', { val: true, ack: true });
} 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');
stopSchoolfree();
} else {
adapter.log.warn('schoolfree cannot request... API not reachable!!');
stopSchoolfree();
}
} else {
adapter.log.warn(`schoolfree request error... API not reachable!!`);
stopSchoolfree();
}
} catch (e) {
adapter.log.warn(`schoolfree request error... API not reachable: ${e}`);
stopSchoolfree();
}
}
function fillLocation() {
try {
const locations = require('./admin/locations.json');
if (adapter.config.counties !== 'allCounties' || adapter.config.counties !== '') {
const arrCounties = locations.filter(d => d.id == adapter.config.counties);
adapter.log.debug(`counties number: ${adapter.config.counties}`);
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 });
}
if (adapter.config.places !== 'allPlaces' || adapter.config.places !== '') {
const arrPlaces = locations.filter(d => d.id == adapter.config.places);
adapter.log.debug(`places number: ${adapter.config.places}`);
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 });
}
if (adapter.config.schools !== 'allschools' || adapter.config.schools !== '') {
const arrSchools = locations.filter(d => d.id == adapter.config.schools);
adapter.log.debug(`schools number: ${adapter.config.schools}`);
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: ${e}`);
}
}
function delOldObjects() {
adapter.getState('data.locations', (err, state) => {
if (state) {
adapter.delObject('data.locations');
adapter.delObject('data');
}
});
}
function main() {
//locationsUpdate(); only for update locations.json
delOldObjects();
if (adapter.config.federalState !== 'none') {
fillLocation();
checkHolidayNames();
} else {
stopSchoolfree();
}
}
// 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();
}