This repository has been archived by the owner on Sep 21, 2018. It is now read-only.
forked from d-pollard/Pokemon-GO-node-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poke.io.js
429 lines (356 loc) · 13.6 KB
/
poke.io.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
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
'use strict';
const request = require('request');
const geocoder = require('geocoder');
const events = require('events');
const ProtoBuf = require('protobufjs');
const GoogleOAuth = require('gpsoauthnode');
const Long = require('long');
const ByteBuffer = require('bytebuffer');
const s2 = require('s2geometry-node');
const Logins = require('./logins');
const fs = require('fs');
const pokemonlist = JSON.parse(fs.readFileSync(__dirname + '/pokemons.json', 'utf8'));
let builder = ProtoBuf.loadProtoFile('pokemon.proto');
if (builder === null) {
builder = ProtoBuf.loadProtoFile(__dirname + '/pokemon.proto');
}
const pokemonProto = builder.build();
const {
RequestEnvelop,
ResponseEnvelop
} = pokemonProto;
const EventEmitter = events.EventEmitter;
const api_url = 'https://pgorelease.nianticlabs.com/plfe/rpc';
function GetCoords(self) {
let {
latitude,
longitude
} = self.playerInfo;
return [latitude, longitude];
};
function getNeighbors(lat, lng) {
var origin = new s2.S2CellId(new s2.S2LatLng(lat, lng)).parent(15);
var walk = [origin.id()];
// 10 before and 10 after
var next = origin.next();
var prev = origin.prev();
for (var i = 0; i < 10; i++) {
// in range(10):
walk.push(prev.id());
walk.push(next.id());
next = next.next();
prev = prev.prev();
}
return walk;
}
function Pokeio() {
var self = this;
self.events = new EventEmitter();
self.j = request.jar();
self.request = request.defaults({
jar: self.j
});
self.google = new GoogleOAuth();
self.playerInfo = {
accessToken: '',
tokenExpireTime: 0,
debug: true,
latitude: 0,
longitude: 0,
altitude: 0,
provider: {},
apiEndpoint: '',
};
self.DebugPrint = function(str) {
if (self.playerInfo.debug === true) {
//self.events.emit('debug',str)
console.log(str);
}
};
self.pokemonlist = pokemonlist.pokemon;
function api_req(api_endpoint, access_token, req, callback) {
// Auth
var auth = new RequestEnvelop.AuthInfo({
provider: self.playerInfo.provider,
token: new RequestEnvelop.AuthInfo.JWT(access_token, 59)
});
var f_req = new RequestEnvelop({
unknown1: 2,
rpc_id: 1469378659230941192,
requests: req,
latitude: self.playerInfo.latitude,
longitude: self.playerInfo.longitude,
altitude: self.playerInfo.altitude,
auth: auth,
unknown12: 989
});
var protobuf = f_req.encode().toBuffer();
var options = {
url: api_endpoint,
body: protobuf,
encoding: null,
headers: {
'User-Agent': 'Niantic App'
}
};
self.request.post(options, function(err, response, body) {
if (response === undefined || body === undefined) {
console.error('[!] RPC Server offline');
return callback(new Error('RPC Server offline'));
}
try {
var f_ret = ResponseEnvelop.decode(body);
} catch (e) {
if (e.decoded) { // Truncated
console.warn(e);
f_ret = e.decoded; // Decoded message with missing required fields
}
}
if (f_ret) {
return callback(null, f_ret);
} else {
api_req(api_endpoint, access_token, req, callback)
}
});
}
self.init = function(username, location, provider, callback) {
// Check if theres a provider token and expireTime
if (!provider.token || !provider.expireTime) {
return callback(new Error('Invalid Token'));
}
if (provider.name === 'ptc' && provider.token) {
self.DebugPrint('[i] Received PTC access token! {Expires: ' + provider.expireTime + '}');
} else if (provider.name === 'google' && provider.token) {
self.DebugPrint('[i] Received Google access token! {Expires: ' + provider.expireTime + '}');
}
// set provider
self.playerInfo.provider = provider.name;
self.playerInfo.accessToken = provider.token;
self.playerInfo.tokenExpireTime = provider.expireTime;
// Updating location
self.SetLocation(location, function(err, loc) {
if (err) {
return callback(err);
}
// Getting api endpoint
self.GetApiEndpoint(function(err, api_endpoint) {
if (err) {
return callback(err);
}
callback(null, self.playerInfo);
});
});
};
self.GetAccessToken = function(user, pass, callback) {
self.DebugPrint('[i] Logging with user: ' + user);
if (self.playerInfo.provider === 'ptc') {
Logins.PokemonClub(user, pass, self, function(err, session) {
if (err) {
return callback(err);
}
self.playerInfo.accessToken = session.token;
self.playerInfo.tokenExpireTime = session.expire_time;
self.DebugPrint('[i] Received PTC access token! {Expires: ' + session.expire_time + '}');
callback(null, session);
});
} else {
Logins.GoogleAccount(user, pass, self, function(err, session) {
if (err) {
return callback(err);
}
self.playerInfo.accessToken = session.token;
self.playerInfo.tokenExpireTime = session.expire_time;
self.DebugPrint('[i] Received Google access token! {Expires: ' + session.expire_time + '}');
callback(null, session);
});
}
};
self.GetApiEndpoint = function(callback) {
var req = [
new RequestEnvelop.Requests(2),
new RequestEnvelop.Requests(126),
new RequestEnvelop.Requests(4),
new RequestEnvelop.Requests(129),
new RequestEnvelop.Requests(5)
];
api_req(api_url, self.playerInfo.accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
}
var api_endpoint = `https://${f_ret.api_url}/rpc`;
self.playerInfo.apiEndpoint = api_endpoint;
self.DebugPrint('[i] Received API Endpoint: ' + api_endpoint);
return callback(null, api_endpoint);
});
};
self.GetInventory = function(callback) {
var req = new RequestEnvelop.Requests(4);
api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
}
var inventory = ResponseEnvelop.GetInventoryResponse.decode(f_ret.payload[0]);
return callback(null, inventory);
});
};
self.GetProfile = function(callback) {
var req = new RequestEnvelop.Requests(2);
api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
}
var profile = ResponseEnvelop.ProfilePayload.decode(f_ret.payload[0]).profile
if (profile.username) {
self.DebugPrint('[i] Logged in!');
}
callback(null, profile);
});
};
// IN DEVELPOMENT, YES WE KNOW IS NOT WORKING ATM
self.Heartbeat = function(callback) {
let {
apiEndpoint,
accessToken
} = self.playerInfo;
var nullbytes = new Array(21);
nullbytes.fill(0);
// Generating walk data using s2 geometry
var walk = getNeighbors(self.playerInfo.latitude, self.playerInfo.longitude).sort(function(a, b) {
return a > b;
});
// Creating MessageQuad for Requests type=106
var walkData = new RequestEnvelop.MessageQuad({
'f1': walk,
'f2': nullbytes,
'lat': self.playerInfo.latitude,
'long': self.playerInfo.longitude
});
var req = [new RequestEnvelop.Requests(106, walkData.encode().toBuffer()), new RequestEnvelop.Requests(126), new RequestEnvelop.Requests(4, new RequestEnvelop.Unknown3(Date.now().toString()).encode().toBuffer()), new RequestEnvelop.Requests(129), new RequestEnvelop.Requests(5, new RequestEnvelop.Unknown3('05daf51635c82611d1aac95c0b051d3ec088a930').encode().toBuffer())];
api_req(apiEndpoint, accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
} else if (!f_ret || !f_ret.payload || !f_ret.payload[0]) {
return callback('No result');
}
var heartbeat = ResponseEnvelop.HeartbeatPayload.decode(f_ret.payload[0]);
callback(null, heartbeat);
});
};
self.GetLocation = function(callback) {
geocoder.reverseGeocode(...GetCoords(self), function(err, data) {
if (data.status === 'ZERO_RESULTS') {
return callback(new Error('location not found'));
}
callback(null, data.results[0].formatted_address);
});
};
self.CatchPokemon = function(mapPokemon, pokeball, callback) {
console.log('Attempting to catch now...');
let {
apiEndpoint,
accessToken
} = self.playerInfo;
var catchPokemon = new RequestEnvelop.CatchPokemonMessage({
'encounter_id': mapPokemon.EncounterId,
'pokeball': pokeball,
'normalized_reticle_size': 1.950,
'spawnpoint_id': mapPokemon.SpawnPointId,
'hit_pokemon': true,
'spin_modifier': 1,
'normalized_hit_position': 1
});
var req = new RequestEnvelop.Requests(103, catchPokemon.encode().toBuffer());
api_req(apiEndpoint, accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
} else if (!f_ret || !f_ret.payload || !f_ret.payload[0]) {
return callback('No result');
}
var catchPokemonResponse = ResponseEnvelop.CatchPokemonResponse.decode(f_ret.payload[0]);
callback(null, catchPokemonResponse)
});
};
self.EncounterPokemon = function(catchablePokemon, callback) {
// console.log(catchablePokemon);
let {
apiEndpoint,
accessToken,
latitude,
longitude
} = self.playerInfo;
var encounterPokemon = new RequestEnvelop.EncounterMessage({
'encounter_id': catchablePokemon.EncounterId,
'spawnpoint_id': catchablePokemon.SpawnPointId,
'player_latitude': latitude,
'player_longitude': longitude
});
// console.log(encounterPokemon);
var req = new RequestEnvelop.Requests(102, encounterPokemon.encode().toBuffer());
api_req(apiEndpoint, accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
} else if (!f_ret || !f_ret.payload || !f_ret.payload[0]) {
return callback('No result');
}
var catchPokemonResponse = ResponseEnvelop.EncounterResponse.decode(f_ret.payload[0]);
callback(null, catchPokemonResponse);
});
};
self.GetLocationCoords = function() {
let {
latitude,
longitude,
altitude
} = self.playerInfo;
return {
latitude,
longitude,
altitude
};
};
self.SetLocation = function(location, callback) {
if (!location.latitude || !location.longitude) {
return callback(new Error('Invalid location type'));
}
self.playerInfo.latitude = location.latitude || self.playerInfo.latitude;
self.playerInfo.longitude = location.longitude || self.playerInfo.longitude;
self.playerInfo.altitude = location.altitude || self.playerInfo.altitude;
callback(null, self.GetLocationCoords());
};
self.changePosition = function() {
self.playerInfo.longitude = self.playerInfo.longitude + 0.000055;
self.playerInfo.latitude = self.playerInfo.latitude + 0.000055;
return true;
};
self.hatchEggs = function(cb) {
self.changePosition();
self.Heartbeat(cb);
};
self.GetFort = function(fortid, fortlat, fortlong, callback) {
var FortMessage = new RequestEnvelop.FortSearchMessage({
'fort_id': fortid,
'player_latitude': fortlat,
'player_longitude': fortlong,
'fort_latitude': fortlat,
'fort_longitude': fortlong
});
// console.log(FortMessage);
var req = new RequestEnvelop.Requests(101, FortMessage.encode().toBuffer());
api_req(self.playerInfo.apiEndpoint, self.playerInfo.accessToken, req, function(err, f_ret) {
if (err) {
return callback(err);
} else if (!f_ret || !f_ret.payload || !f_ret.payload[0]) {
return callback('No result');
}
var FortSearchResponse = ResponseEnvelop.FortSearchResponse.decode(f_ret.payload[0]);
callback(null, FortSearchResponse);
});
};
self.warpSpeed = function(lat, long) {
self.playerInfo.latitude = lat;
self.playerInfo.longitude = long;
return true;
};
}
module.exports = new Pokeio();
module.exports.Pokeio = Pokeio;