-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
462 lines (407 loc) · 13.1 KB
/
main.js
File metadata and controls
462 lines (407 loc) · 13.1 KB
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
//PublicHolidayAPI
//main handles post-requests
//author: Marius Riehl
//date: 2017-03-08
//change: 2017-03-10
//server objects (nice libraries :p)
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//general
var supported = ["DE", "US", "CH", "AT", "BE", "BG","IN", "NL", "MX", "IL", "SK", "UK", "MY", "DU"]; //list of countries
var icsConverter = require('./icsConverter.js');
var xmlConverter = require('./xmlConverter.js');
var enablelogging = false;
function dataFromCountryString(countryCode, year){
var next;
var cc = undefined;
cc = require('./countries/' + countryCode.toLowerCase() + '.js');
return next = JSON.parse(JSON.stringify(cc.getHolidays(year)));
}
//returns JSON object with all holidays of all countries (array)
function getData(countries, year){
var data = undefined;
var next = undefined;
for(var k = 0; k < countries.length; k++){
next = undefined;
next = dataFromCountryString(countries[k], year);
if(k < 1){
data = JSON.parse(JSON.stringify(next)); //thanks Dominik :D "js pros standard copy function"
}else{
data.num += next.num;
data.holidays = data.holidays.concat(next.holidays);
}
}
//now sort data, key is timestamp of date
data.holidays.sort(function(a, b){
var x = a['date']; var y = b['date'];
var x1 = (new Date(x)).getTime(); var y1 = (new Date(y)).getTime();
return ((x1 < y1) ? -1 : ((x1 > y1) ? 1 : 0));
});
return data;
}
//gets the next holiday (from now on)
function getNextHoliday(countries, year){
if(year > 9999){
return false; //leave recursive calculation
}
var time = Date.now();
var data = getData(countries, year);
for(var i = 0; i < data.num; i++){
var date = new Date(data.holidays[i].date);
if(date.getTime() > time){
//is this date used in other countries too?
var j = i + 1;
while(data.holidays[j].date == data.holidays[i].date){
data.holidays[i].name += ", " + data.holidays[j].name;
data.holidays[i].region += ", " + data.holidays[j].region;
j++;
}
data.holidays[i].countryCount = j - i;
return data.holidays[i];
}
}
let yearp1 = (parseInt(year) + 1).toString();
return getNextHoliday(countries, yearp1); //no next holiday for this year, try in next year (recursive)
}
//miscallaneous functions
function getCountryArray(countrystring){
//delete all spaces from countries string
countrystring = countrystring.replace(/\s+/g, '');
//support lower case chars
countrystring = countrystring.toUpperCase();
//convert countries string to array
let countries = countrystring.split(",");
//check last char and empty
for(var i = 0; i < countries.length; i++){
if(countries[i] == ''){
countries.splice(i, 1);
}
}
return countries;
}
//post request handling function
function checkCountry(req, res){
//check countries
let countries = getCountryArray(req);
//check if each country is supported and format is correct
for(var j = 0; j < countries.length; j++){
if(countries[j].length != 2){
res.status(400).send("Bad Request. Wrong country request format. Use: AA,BB,CC");
return false;
}
if(supported.indexOf(countries[j]) == -1){
res.status(400).send("Bad Request. Country " + countries[j] + " not supported.");
return false;
}
}
return countries; //return array, if everything is fine
}
function checkYear(req, res){
//check year
let p = req.replace(/\D/g, ''); //remove non numeric chars
if(p != req){
res.status(400).send("Bad Request. Only non numeric characters in [year] parameter are allowed.");
return false;
}
if(req.length != 4){
res.status(400).send("Bad Request. Wrong format for year parameter.");
return false;
}
if(parseInt(req) < 1970){
res.status(400).send("Bad Request. Year must be >= 1970.");
return false;
}
return p; //return formatted string, if everything is fine
}
function checkDate(req, res){
//check dates for area type request
if(req.length != 10){ //wrong length
res.status(400).send("Bad Request. Invalid date format. Use ISO-8601 YYYY-MM-DD");
return false;
}
let p = req.replace(/\D/g, ''); //remove non numeric chars
p = req.replace(/[0-9]/g, 'X'); //replace numeric with X for format check
if(p != "XXXX-XX-XX"){
res.status(400).send("Bad Request. Invalid date format. Use ISO-8601 YYYY-MM-DD");
return false;
}
if(parseInt(req.substring(0,4)) < 1970){
res.status(400).send("Bad Request. Year must be >= 1970.");
return false;
}
let q = Date.parse(req);
if(isNaN(q)){
res.status(400).send("Bad Request. Invalid date object. Use ISO-8601 YYYY-MM-DD");
return false;
}
return true; //everything fine, return true
}
function checkResponseType(req, res){
//check if response type is supported
req = req.toUpperCase();
if(req == "XML" || req == "JSON" || req == "ICS"){
return true;
}else{
res.status(400).send("Bad Request. Response type not supported. Use: XML, JSON, ICS");
return false;
}
}
//list type, process here
//required params: countries, year
function typeList(req, res){
//check required params
if(typeof typeof req.body.year == "undefined" || req.body.year == ""){
res.status(400).send("Bad Request. 'Year' was not defined.");
return;
}
if(typeof req.body.countries == "undefined" || req.body.countries == ""){
res.status(400).send("Bad Request. No countries selected. Atleast one country is required.");
return;
}
//check year
let year = checkYear(req.body.year, res);
if(typeof year != "string"){ //returns false, when something is wrong, and correct string if its fine
return;
}
//check countries
let countries = checkCountry(req.body.countries, res);
if(!Array.isArray(countries)){ //returns array if everything is fine, returns false if not
return;
}
//check responsetype
if(typeof req.body.responsetype == "undefined" || req.body.responsetype == ""){req.body.responsetype = "JSON";}
if(!checkResponseType(req.body.responsetype, res)){
return; //returnd false, stop
}req.body.responsetype = req.body.responsetype.toUpperCase();
//everything fine, get the data and send response
try{
var data = clearList(getData(countries, year));
if(data.num > 0){
switch(req.body.responsetype){
case "JSON":
res.json(data);
return;
case "ICS":
res.send(icsConverter.getICS(data));
return;
case "XML":
res.send(xmlConverter.getXML(data));
return;
}
}else{
res.status(400).send("No Holidays found in the date range you specified."); //no content
}
}catch(err){
console.log(err); //internal error, prevent server from crashing and log error
res.status(500).send("Internal Server Error. Something went wrong. Please try again.");
}
return;
}
//next type, required params: countries (only)
function typeNext(req, res){
//check required params
if(typeof req.body.countries == "undefined" || req.body.countries == ""){
res.status(400).send("Bad Request. No countries selected. Atleast one country is required.");
return;
}
//check countries
let countries = checkCountry(req.body.countries, res);
if(!Array.isArray(countries)){ //returns array if everything is fine, returns false if not
return;
}
//check responsetype
if(typeof req.body.responsetype == "undefined" || req.body.responseType == ""){req.body.responsetype = "JSON";}
if(!checkResponseType(req.body.responsetype, res)){
return; //returnd false, stop
}req.body.responsetype = req.body.responsetype.toUpperCase();
//get data and respond
try{
let p = new Date();
let nextholiday = getNextHoliday(countries, p.toISOString().substring(0, 4));
if(nextholiday == false){
res.status(400).send("No Holidays found in the date range you specified.");
return;
}
nextholiday = clearParams(nextholiday);
switch(req.body.responsetype){
case "JSON":
res.json(nextholiday);
return;
case "ICS":
res.send(icsConverter.getICS(nextholiday));
return;
case "XML":
res.send(xmlConverter.getXML(nextholiday));
}
}catch(err){
console.log(err);
res.status(500).send("Internal Server Error. We messed up. Please try again.");
}
return;
}
//area type, required params: countries, start, end in ISO 8601 format
function typeArea(req, res){
//check required params
if(typeof typeof req.body.start == "undefined" || typeof req.body.end == "undefined" ||
req.body.start == "" || req.body.end == ""){
res.status(400).send("Bad Request. Check API documentation for required params.");
return;
}
if(typeof req.body.countries == "undefined" || req.body.countries == ""){
res.status(400).send("Bad Request. No countries selected. Atleast one country is required.");
return;
}
//check countries
let countries = checkCountry(req.body.countries, res);
if(!Array.isArray(countries)){ //returns array if everything is fine, returns false if not
return;
}
//check responsetype
if(typeof req.body.responsetype == "undefined" || req.body.responsetype == ""){req.body.responsetype = "JSON";}
if(!checkResponseType(req.body.responsetype, res)){
return; //returned false, stop, else ok
}req.body.responsetype = req.body.responsetype.toUpperCase();
//check start and end date
if(!checkDate(req.body.start, res) || !checkDate(req.body.end, res)){
return; //date check invalid
}//else:
//new date objects
let x = new Date(req.body.start);
let y = new Date(req.body.end);
//calculate number of years
var dt = parseInt(y.toISOString().substring(0, 4)) - parseInt(x.toISOString().substring(0, 4)) + 1;
if(dt < 1){
res.status(400).send("Bad request. Start date must be before end date.");
return;
}else if(dt > 4){
res.status(400).send("Bad request. Not more than 3 years area allowed. This is to prevent timeouts from long requests.");
return;
}
//date format is valid, got dt (number of years inbetween
var data = undefined;
var next = undefined;
try{
for(var i = 0; i < dt; i++){ //itterate through the years and put the data together
next = undefined;
let z = (parseInt(x.toISOString().substring(0, 4)) + i).toString();
next = clearList(getData(countries, z));
if(i < 1){
data = JSON.parse(JSON.stringify(next)); //copy data into object
}else{
data.num += next.num;
data.holidays = data.holidays.concat(next.holidays);
}
}
//ok, got the object, now itterate through the first year, delete all that are smaller than x
let j = 0;let v = data.num -1;
while(parseInt(data.holidays[j].date.substring(0, 4)) == x.getFullYear() && v > 0){
let p = (new Date(data.holidays[j].date)).getTime();
if(p < x.getTime()){
data.holidays.splice(0, 1); //remove out of array
data.num--;
j--; //nachrücken problem -> solved by v
}
j++;v--;
}//not itterate through the last year backwards, delete all that are bigger than x
let k = data.num - 1;
while(k >= 0){
if(parseInt(data.holidays[k].date.substring(0, 4)) == y.getFullYear()){
let p = (new Date(data.holidays[k].date)).getTime();
if(p > y.getTime()){
data.holidays.splice(data.holidays.length - 1, 1); //remove out of array
data.num--;
}
}
k--;
}
//check if no holidays were found
if(data.num > 0){
switch(req.body.responsetype){
case "JSON":
res.json(data);
return;
case "ICS":
res.send(icsConverter.getICS(data));
return;
case "XML":
res.send(xmlConverter.getXML(data));
}
}else{
res.status(400).send("No Holidays found in the date range you specified."); //204 = no content
}
return;
}catch(err){
console.log(err);
res.status(500).send("Internal Server Error. We messed up. Please try again.");
return;
}
}
//process and respond for incomming post requests
//check for correct body & parameters, crunch the numbers and return JSON Object
app.post('/data/', function(req, res){
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'POST');
try{
if(typeof req.body.requesttype != 'undefined'){
req.body.requesttype = req.body.requesttype.toUpperCase();
switch(req.body.requesttype){
case "LIST":
typeList(req, res);
return;
case "NEXT":
typeNext(req, res);
break;
case "AREA":
typeArea(req, res);
break;
default:
res.status(501).send("Not implemented. Request-Type is not supported.");
return;
}
}else{
res.status(400).send("Bad Request. Refer to API documentation for required params & headers.");
return;
}
}catch(err){
res.status(500).send("Internal Server Error. We messed up. Please try again.");
}
});
//removes unwanted variables from object before sending it to client
function clearParams(obj){
switch(obj.type){
case 0:
delete obj.day;
break;
case 1:
case 6:
case 7:
case 8:
delete obj.offset;
break;
case 2:
delete obj.day;
delete obj.month;
delete obj.offset;
break;
case 3:
delete obj.day;
delete obj.month;
break;
}
delete obj.type;
return obj;
}
//removes unwanted variables of list
function clearList(obj){
for(var i = 0; i < obj.num; i++){
obj.holidays[i] = clearParams(obj.holidays[i]);
}
return obj;
}
//app listens for post (or get) requests
app.listen(121); //change this port to whatever port is available on UberSpace Avior