-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
278 lines (208 loc) · 7.21 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
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
var fs = require('fs');
var request = require('request');
var twilio = require('twilio');
var express = require('express');
var async = require('async');
var app = express();
try {
fs.accessSync('GOOGLE_MAPS_API_KEY');
} catch (e) {
console.log('Please create GOOGLE_MAPS_API_KEY file in current directory');
process.exit();
}
var GOOGLE_MAPS_API_KEY = fs.readFileSync('GOOGLE_MAPS_API_KEY', 'utf-8').slice(0, -1);
var GOOGLE_DIRECTIONS_ENDPOINT = "https://maps.googleapis.com/maps/api/directions/json";
var GOOGLE_PLACES_ENDPOINT = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
var GOOGLE_GEOCODE_ENDPOINT = "https://maps.googleapis.com/maps/api/geocode/json";
var NORTH_AMERICA = {
'lat': 42.7632012,
'lng': -78.4410568
}
app.set('json spaces', 4);
app.get('/geocode/:address', function (req, res) {
var address = req.params.address;
geocode(address, NORTH_AMERICA, 500, function (err, geo) {
if (err) return res.sendStatus(500);
res.json(geo);
});
});
app.get('/route/:from_loc/:to_loc', function (req, res) {
route_loc(req.params.from_loc, req.params.to_loc, function (err, polyline) {
if (err) return res.sendStatus(500);
return res.json(polyline);
});
});
app.get('/food/:from_loc', function (req, res) {
nearby_food(req.params.from_loc, function (err, resp) {
if (err) return res.sendStatus(500);
return res.json(resp);
});
});
app.get('/macdonalds/:from_loc', function (req, res) {
nearby_wifi_generator('macdonalds')(req.params.from_loc, function (err, resp) {
if (err) return res.sendStatus(500);
return res.json(resp);
});
});
app.get('/wifi/:from_loc', function (req, res) {
nearby_wifi(req.params.from_loc, function (err, resp) {
console.log('yo!');
if (err) return res.sendStatus(500);
return res.json(resp);
});
});
app.get('/health', function (req, res) {
request.get(GOOGLE_DIRECTIONS_ENDPOINT + '?origin=Toronto&destination=Montreal&key=' + GOOGLE_MAPS_API_KEY, function (err, resp) {
resp = JSON.parse(resp.body);
res.json(resp);
});
});
var is_latlng = function (str) {
for (var i=0; i<str.length; str++) {
if ("-.0123456789".indexOf(str[i]) === -1) return false;
}
return true;
}
var geocode = function (address, near_ll, radius, cb) {
if (is_latlng(address)) return cb(null, {
'lat': +address.split(',')[0],
'lng': +address.split(',')[1]
});
var url = GOOGLE_GEOCODE_ENDPOINT;
url += '?address=';
url += address;
url += '&key=';
url += GOOGLE_MAPS_API_KEY;
console.log('sending geocode request to gmaps...');
request.get(url, function (err, resp) {
if (err) return console.log('error', err);
resp = JSON.parse(resp.body);
if (resp.results.length === 0) return cb("geocode failed");
var scores = resp.results.map(function (result) {
return Math.pow(result.geometry.location.lat - near_ll.lat, 2) +
Math.pow(result.geometry.location.lng - near_ll.lng, 2);
});
var idx_of_best = 0;
for (var i=0; i<scores.length; i++) {
if (scores[i] < radius) return cb(null, resp.results[i].geometry.location);
if (scores[i] < scores[idx_of_best]) idx_of_best = i;
}
return cb(null, resp.results[idx_of_best].geometry.location);
});
}
var nearby_wifi = function (from_loc, cb) {
async.map(['macdonalds', 'starbucks', 'timhortons'], function (chain, cb) {
nearby_wifi_generator(chain)(from_loc, cb);
}, function (err, res) {
if (err) return cb(err);
console.log(res);
return cb(null, [].concat.apply([], res));
});
}
var nearby_wifi_generator = function (chain) {
return function (from_loc, cb) {
geocode(from_loc, NORTH_AMERICA, 500, function (err, ll) {
if (err) return cb(err);
var url = GOOGLE_PLACES_ENDPOINT;
url += '?location=';
url += [ll.lat, ll.lng].join(',');
url += '&radius=1000';
url += '&keyword=';
url += chain;
url += '&key=';
url += GOOGLE_MAPS_API_KEY;
request.get(url, function (err, resp) {
if (err) return console.log('error', err);
resp = JSON.parse(resp.body);
return cb(null, resp.results.map(function (result) {
var ret = result.geometry.location;
ret.name = result.name;
return ret;
}));
});
});
}
}
var nearby_food = function (from_loc, cb) {
console.log('nearby_food', from_loc);
geocode(from_loc, NORTH_AMERICA, 500, function (err, ll) {
if (err) return cb(err);
var url = GOOGLE_PLACES_ENDPOINT;
url += '?location=';
url += [ll.lat, ll.lng].join(',');
url += '&radius=500';
// url += '&opennow=true';
url += '&types=food';
url += '&key=';
url += GOOGLE_MAPS_API_KEY;
request.get(url, function (err, resp) {
if (err) return console.log('error', err);
resp = JSON.parse(resp.body);
return cb(null, resp.results.map(function (result) {
var ret = result.geometry.location;
ret.name = result.name;
return ret;
}));
});
});
}
var route_loc = function (from_loc, to_loc, cb) {
console.log('route_loc', from_loc, to_loc);
var url = GOOGLE_DIRECTIONS_ENDPOINT;
url += '?origin=';
url += from_loc;
url += '&destination=';
url += to_loc;
url += '&key=';
url += GOOGLE_MAPS_API_KEY;
console.log('sending route request to gmaps...');
request.get(url, function (err, resp) {
if (err) return console.log(err);
resp = JSON.parse(resp.body);
if (resp.routes.length === 0) return cb("no routes found");
var polyline = resp.routes[0].overview_polyline.points;
console.log('gmaps returned', polyline);
cb(null, polyline);
});
}
app.get('/twilio', function (req, res) {
var message_body = req.query.Body.split('\n');
console.log('received: ', message_body);
var command = message_body[0].split(' ')[0];
if (command === 'r') {
route_loc(message_body[1], message_body[2], function (err, polyline) {
var resp = new twilio.TwimlResponse();
resp.message(message_body[0] + '\n' + polyline);
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(resp.toString());
});
} else if (command === 'f') {
nearby_food(message_body[1], function (err, wifi_arr) {
console.log('sending nearby_food sms');
var resp = new twilio.TwimlResponse();
resp.message(message_body[0] + '\n' + wifi_arr.map(function (food) {
return [food.lat, food.lng, food.name].join(' ')
}).join('\n'));
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(resp.toString());
});
} else if (command === 'w') {
nearby_wifi(message_body[1], function (err, wifi_arr) {
console.log('sending nearby_wifi sms', wifi_arr);
var resp = new twilio.TwimlResponse();
resp.message(message_body[0] + '\n' + wifi_arr.map(function (food) {
return [food.lat, food.lng, food.name].join(' ')
}).join('\n'));
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(resp.toString());
});
} else {
console.log('unrecognized command', command);
}
});
var port = +process.argv[2] || 4000;
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});