-
Notifications
You must be signed in to change notification settings - Fork 1
/
doodle.js
84 lines (67 loc) · 1.96 KB
/
doodle.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
var request = require('request');
const MIN_YEAR = 2000;
const MIN_MONTH = 0;
const MAX_MONTH = 11;
const LANGUAGE = "en";
const DOODLE_API = "http://www.google.com/doodles/json/";
module.exports = function (ctx, req, res) {
var doodleUri = DOODLE_API + randomPathForDoodle();
console.log('Url generated: ' + doodleUri);
request({ url: doodleUri, json: true}, function(err, doodleRes, body) {
try {
var randomIndexDay = randomNumber(0, body.length - 1);
console.log('Day index: ' + randomIndexDay);
var doodle = body[randomIndexDay];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(buildSlackResponse(buildTitle(doodle), builImagedUrl(doodle))));
} catch(e) {
console.error(e);
res.end('Douh! Something bad happened :( try again');
}
});
};
function randomPathForDoodle() {
var year = randomYear();
var month = randomMonth();
if (isDateInFuture(year, month)) {
month = getCurrentMonth();
}
return year + "/" + (month + 1) + "?hl=" + LANGUAGE;
}
function randomYear() {
return randomNumber(MIN_YEAR, getCurrentYear());
}
function randomMonth() {
return randomNumber(MIN_MONTH, MAX_MONTH);
}
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function isDateInFuture(year, month) {
return year == getCurrentYear() && month > getCurrentMonth();
}
function getCurrentMonth() {
return new Date().getMonth();
}
function getCurrentYear() {
return new Date().getFullYear();
}
function buildTitle(doodle) {
return doodle.title + ' (' + formatDate(doodle.run_date_array) + ')';
}
function formatDate(date_array) {
return date_array[2] + '-' + date_array[1] + '-' + date_array[0];
}
function builImagedUrl(doodle) {
return 'https:' + doodle.url;
}
function buildSlackResponse(title, url) {
return {
response_type: "in_channel",
text: title,
attachments: [{
fallback: title,
image_url: url
}]
}
}