-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
289 lines (259 loc) · 8.03 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
var http = require('https');
var Twitter = require('twitter');
var moment = require('moment');
require('moment-timezone');
// setup libraries
// secrets from environment
var client = new Twitter({
consumer_key: process.env.TW_CONSUMER_KEY,
consumer_secret: process.env.TW_CONSUMER_SECRET,
access_token_key: process.env.TW_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TW_ACCESS_TOKEN_SECRET
});
var apiUrls = [
// downtown
'https://pokevision.com/map/data/49.29154563906309/-123.13287734985352',
'https://pokevision.com/map/data/49.28829871209136/-123.12429428100586',
'https://pokevision.com/map/data/49.28359588700294/-123.11150550842287',
'https://pokevision.com/map/data/49.28214015975995/-123.10077667236327',
'https://pokevision.com/map/data/49.27659680498306/-123.11562538146973',
'https://pokevision.com/map/data/49.278388664575886/-123.12764167785645',
'https://pokevision.com/map/data/49.28337193176269/-123.13708305358885',
'https://pokevision.com/map/data/49.29137769980898/-123.14240455627443',
'https://pokevision.com/map/data/49.281692235039465/-123.12026023864746',
// mt pleasant (near the office)
'https://pokevision.com/map/data/49.26648837773104/-123.10094833374025',
'https://pokevision.com/map/data/49.26657238981664/-123.11240673065186',
'https://pokevision.com/map/data/49.261223334999976/-123.11262130737303',
'https://pokevision.com/map/data/49.26052315401983/-123.10116291046143'
];
var pokeMap = {
1 : 'Bulbasaur',
2 : 'Ivysaur',
3 : 'Venusaur',
4 : 'Charmander',
5 : 'Charmeleon',
6 : 'Charizard',
7 : 'Squirtle',
8 : 'Wartortle',
9 : 'Blastoise',
25 : 'Pikachu',
26 : 'Raichu',
31 : 'Nidoqueen',
34 : 'Nidoking',
36 : 'Clefable',
38 : 'Ninetales',
40 : 'Wigglytuff',
45 : 'Vileplume',
51 : 'Dugtrio',
53 : 'Persian',
55 : 'Golduck',
57 : 'Primeape',
58 : 'Growlithe',
59 : 'Arcanine',
62 : 'Poliwrath',
64 : 'Kadabra',
65 : 'Alakazam',
68 : 'Machamp',
71 : 'Victreebel',
73 : 'Tentacruel',
75 : 'Graveler',
76 : 'Golem',
77 : 'Ponyta',
78 : 'Rapidash',
80 : 'Slowbro',
82 : 'Magneton',
91 : 'Cloyster',
95 : 'Onix',
101 : 'Electrode',
102 : 'Exeggcute',
103 : 'Exeggutor',
106 : 'Hitmonlee',
107 : 'Hitmonchan',
108 : 'Lickitung',
110 : 'Weezing',
112 : 'Rhydon',
113 : 'Chansey',
115 : 'Kangaskhan',
112 : 'Mr. Mime',
117 : 'Seadra',
121 : 'Starmie',
123 : 'Scyther',
125 : 'Electabuzz',
126 : 'Magmar',
127 : 'Pinsir',
128 : 'Tauros',
130 : 'Gyarados',
131 : 'Lapras',
132 : 'Ditto',
134 : 'Vaporeon',
135 : 'Jolteon',
136 : 'Flareon',
137 : 'Porygon',
138 : 'Omanyte',
139 : 'Omastar',
140 : 'Kabuto',
141 : 'Kabutops',
142 : 'Aerodactyl',
143 : 'Snorlax',
144 : '!Articuno',
145 : '!Zapdos',
146 : '!Moltres',
147 : 'Dratini',
148 : 'Dragonair',
149 : '!Dragonite',
150 : '!Mewtwo',
151 : '!Mew'
};
var cache = {};
function sendTweet (p, name) {
var nameStr = name + ' found';
var expStr = createExpiryMessage (p);
var mapUrl = createMapUrl(p.latitude, p.longitude);
getAddress(p.latitude, p.longitude, (addressStr) => {
if (addressStr) {
addressStr = ' ' + addressStr;
}
var msg = nameStr + addressStr + '. ' + expStr + ' ' + mapUrl;
console.log(msg);
client.post('statuses/update', {status: msg}, function(error, tweet, response) {});
});
}
function createExpiryMessage (monData) {
var secondsExp = monData.expiration_time;
var exp = moment(secondsExp * 1000).tz('America/Vancouver');
var expirationStr = exp.clone().format('h:mmA'); // 9:28PM
var expFromNow = exp.clone().toNow(true); // in X mins
return 'It will be there for ' + expFromNow + ', until ' + expirationStr;
}
function createMapUrl (lat, longi) {
return 'https://maps.google.com/maps?q=' + lat + ',' + longi;
}
function getAddress (lat, longi, callback) {
var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + longi + '&key=' + process.env.GOOGLE_KEY;
getContent(url).then((body) => {
var json,
output = '';
if (body && body.length && body.charAt(0) === '{') {
json = JSON.parse(body);
if (json.results && json.results[0] && json.results[0].address_components && json.results[0].formatted_address) {
output = json.results[0].formatted_address;
// turn "1050 Quebec St, Vancouver, BC V6A, Canada" into "1050 Quebec St"
output = output.split(',')[0];
output = 'near ' + output;
}
}
callback(output);
});
}
function getCacheKey (p) {
// can't trust p.uid for some reason
return p.pokemonId + '|' + p.latitude + '|' + p.longitude;
}
function putCache (key, p) {
if (getCache(key)) {
return;
}
cache[key] = p;
}
function getCache (key) {
return cache[key];
}
function removeCache (key) {
delete cache[key];
}
function cleanCache () {
var curr = (new Date())*1;
var toDelete = [];
for (var key in cache) {
var p = cache[key];
// give 1 second buffer
if (curr >= (p.expiration_time + 1)*1000) {
toDelete.push(key);
}
}
console.log(Object.keys(cache), toDelete);
toDelete.forEach(function (key) {
removeCache(key);
});
}
function isCached (p) {
var result = false;
var cached = getCache(getCacheKey(p));
if (cached) {
result = true;
}
return result;
}
function processMons (res, callback) {
if (res && res.pokemon && res.pokemon.length) {
res.pokemon.forEach((p) => {
var pId = parseInt(p.pokemonId, 10);
if (pokeMap[pId]) {
if (!isCached(p)) {
var name = pokeMap[pId];
sendTweet(p, name);
putCache(getCacheKey(p), p);
}
}
});
}
}
function getByUrls (urls) {
var promises = urls.map((url) => {
return getContent(url);
});
Promise.all(promises).then(bodies => {
var outputs = [];
bodies.forEach((body) => {
if (body && body.length && body.charAt(0) === '{') {
try {
var parsed = JSON.parse(body);
outputs.push(parsed);
} catch (e) {}
}
});
outputs.forEach((data) => {
processMons(data);
});
});
}
// https://www.tomas-dvorak.cz/posts/nodejs-request-without-dependencies/
function getContent (url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
//const lib = url.startsWith('https') ? require('https') : require('http');
const lib = http;
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
//reject(new Error('Failed to load page, status code: ' + response.statusCode));
console.log('Failed to get: ' + url);
resolve('');
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
//request.on('error', (err) => reject(err));
request.on('error', () => {
console.log('Failed to get: ' + url);
resolve('');
});
});
};
// main loop
function main () {
cleanCache();
getByUrls(apiUrls);
}
main(); // run immediately
// run every 45 seconds
setInterval(() => {
main();
}, 45 * 1000);