-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
245 lines (215 loc) · 7.51 KB
/
index.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
/* eslint-disable func-names */
/* eslint-disable no-console */
const Alexa = require('ask-sdk');
const http = require('http');
const https = require("https");
const DEBUG = 0;
function d(msg) {
if (DEBUG) console.log(msg);
}
function SpeechCard(handlerInput, speechOutput) {
return handlerInput.responseBuilder
.speak(speechOutput)
.withSimpleCard(SKILL_NAME, speechOutput)
.getResponse();
}
const httpGet = url => {
return new Promise((resolve, reject) => {
var client = http;
if (url.match(/^https/g)) client = https;
client.get(url, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => resolve(body));
}).on('error', reject);
});
};
async function getVolcano() {
return 'http://api.geonet.org.nz/volcano/1';
}
async function GetQuakeData(mmi=3) {
const responseStr = await httpGet(`http://api.geonet.org.nz/quake?MMI=${mmi}`);
d(`Received response:\n${responseStr}`);
const response = JSON.parse(responseStr);
return response["features"];
}
async function GetRecentQuakeData(mmi=3, location) {
const quakes = await GetQuakeData(mmi);
//TODO: pick-up device location ["locality"]
return quakes[0]["properties"];
}
function CalculateTimeDifference(timeUTC) {
var currentMiliseconds = Date.now();
var oneDate = new Date(timeUTC);
var oneDateMiliseconds = oneDate.getTime();
var difference = currentMiliseconds-oneDateMiliseconds;
return diff = new Date(difference);
}
function ConvertTimeToSpeech(time) {
if (CalculateTimeDifference(time).getHours() < 2) {
return `${CalculateTimeDifference(time).getMinutes()} minutes ago`;
};
return `${CalculateTimeDifference(time).getHours()} hours ago`;
}
function ConvertQuakeToSpeech(quake) {
var ago = ConvertTimeToSpeech(quake["time"]);
return `${ago} at ${quake["locality"]} with a magnitude of ${Math.round(quake["magnitude"]*100)/100} and intensity of ${quake["mmi"]}`;
}
async function GetLatestNews() {
const responseStr = await httpGet(`https://api.geonet.org.nz/news/geonet`);
const response = JSON.parse(responseStr);
var news = await httpGet(response.feed[0].link);
//TODO: apply a proper innerHTML parser
news = news.replace(/(\w|-)+=(\\)*("|')[^"^']*("|')/gm,'');
news = news.replace(/(&nbps;|\n)/gm,' ');
//Cut to header and footer
news = news.replace(/<!.*<h3>/gm,'');
news = news.replace(/Data Policy.*/gm,'');
// Clean other tags
news = news.replace(/<(!|\/)*(\w+\s*\w*\/*)>/gm,' ');
return news;
}
// ----- TELL THE LATEST ONE ----
const LatestQuakeIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest' || (request.type === 'IntentRequest'
&& request.intent.name === 'LatestQuakeIntent');
},
async handle(handlerInput) {
var speechOutput='There weren`t any recent earthquakes.';
var quake;
if (handlerInput.slots != null) {
var size = handlerInput.intent.slots.size.value;
quake = await GetRecentQuakeData(size);
} else
{
quake = await GetRecentQuakeData();
};
// if (quake != null) {
// if (handlerInput.intent.slots.size.value != null) {
// speechOutput=`The last intensity 'handlerInput.intent.slots.size.value+' relevant earthquake was ${ConvertQuakeToSpeech(quake)}`;
// }
// else {
speechOutput=`The last relevant earthquake was ${ConvertQuakeToSpeech(quake)}`;
// }
return SpeechCard(handlerInput,speechOutput);
}
};
// ----- WAS THAT ONE ----
const WasThatAQuakeIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest' || (request.type === 'IntentRequest'
&& request.intent.name === 'WasThatAQuakeIntent');
},
async handle(handlerInput) {
var speechOutput='No, I don\'t think so. There weren\`t any recent quakes.';
const quake = await GetRecentQuakeData(3); //Look for lower magintude quakes for local quake check
const timeDifference = CalculateTimeDifference(quake.time);
d('Time difference=',timeDifference);
if (timeDifference > 10*60*1000)
{
speechOutput = 'Couln\'t find a recent quake. Maybe just a gust of wind (you are in Wellington, after all!)'; }
else {
speechOutput = 'This quake could be what you felt: There was a quake ' + ConvertQuakeToSpeech(quake);
}
//TODO: no, don't worry
//TODO: check time less that 0h, 10mins?
//TODO: YES, there was one few hours ago
return SpeechCard(handlerInput,speechOutput);
}
};
// ----- READ NEWS ----
const ReadNewsIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest' || (request.type === 'IntentRequest'
&& request.intent.name === 'ReadNewsIntent');
},
async handle(handlerInput) {
var speechOutput=await GetLatestNews();
return SpeechCard(handlerInput,speechOutput);
}
};
// ----- REPORT ONE ----
const FeltIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'LaunchRequest' || (request.type === 'IntentRequest'
&& request.intent.name === 'FeltIntent');
},
async handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
var size = request.intent.slots.size.value;
var city = "Wellington"; //TODO: detect nearest city
var speechOutput=`Ok, I am reporting a ${size} earthquake for ${city}.`;
return SpeechCard(handlerInput,speechOutput);
}
};
const HelpHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(HELP_MESSAGE)
.reprompt(HELP_REPROMPT)
.getResponse();
},
};
const ExitHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& (request.intent.name === 'AMAZON.CancelIntent'
|| request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak(STOP_MESSAGE)
.getResponse();
},
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
return handlerInput.responseBuilder
.speak('Sorry, an error occurred.')
.reprompt('Sorry, an error occurred.')
.getResponse();
},
};
const SKILL_NAME = 'GeoNet assistant';
const HELP_MESSAGE = 'You can say - if that was an earthquake or when was the last earthquake';
const HELP_REPROMPT = 'What do you want to know from GeoNet?';
const STOP_MESSAGE = 'Goodbye!';
const skillBuilder = Alexa.SkillBuilders.standard();
exports.handler = skillBuilder
.addRequestHandlers(
LatestQuakeIntentHandler,
WasThatAQuakeIntentHandler,
FeltIntentHandler,
ReadNewsIntentHandler,
HelpHandler,
ExitHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();