This repository has been archived by the owner on Oct 19, 2021. It is now read-only.
forked from AHAAAAAAA/PokemonGo-Map
-
Notifications
You must be signed in to change notification settings - Fork 43
/
server.py
309 lines (256 loc) · 10.5 KB
/
server.py
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
"""
The server is started with the command:
server.py interface-ip/port (e.g.: 127.0.0.1/12345)
Warning: this script is only usable for test purposes with trusted clients since
it does not address authentication aspects and does not prevent DoS attacks.
Queues are kept in memory and are lost when the server is shutdown.
The exposed RESTful calls are the following (for each call we specify the list
of supported fields sent using the urlencoding scheme in the body of the
request); results are returned using a JSON dictionary and successful requests
return the status code 200:
- GET /
- Required fields:
- id: identity of the request
- lat: latitude
- lng: longitude
- rad: radius of research
- Example:
http://127.0.0.1:12345/?id=5&lat=45.2156&lng=2.4586&rad=4
- Result of the request:
{
"id": idOfTheRequest,
"pokemons": "[{
"id": idOfThePokemon,
"lat": latitude,
"lng": longitude
}, ... ]",
"gyms": "[{
"team": numberOfTheTeam,
"lat": latitude,
"lng": longitude,
"score": score
}, ... ]",
"pokestop": "[{
"lat": latitude,
"lng": longitude,
"lured": lured,
"expire_time": expireTime
}, ...]"
}
"""
import logging
import os
import main
import cgi
import sys
import json
from threading import Lock
from http.server import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPException
from socketserver import ThreadingMixIn
def find_pokemons(location, steplimit, x, y):
pokemons = []
gyms = []
pokestops = []
args = main.get_args()
main.retrying_set_location(location)
api_endpoint, access_token, profile_response = main.login(args)
main.clear_stale_pokemons()
# Scan location math
if -steplimit / 2 < x <= steplimit / 2 \
and -steplimit / 2 < y <= steplimit / 2:
main.set_location_coords(x * 0.0025 + main.origin_lat,
y * 0.0025 + main.origin_lon, 0)
origin = main.LatLng.from_degrees(main.FLOAT_LAT, main.FLOAT_LONG)
step_lat = main.FLOAT_LAT
step_long = main.FLOAT_LONG
parent = main.CellId.from_lat_lng(origin).parent(15)
h = main.get_heartbeat(args.auth_service,
api_endpoint,
access_token,
profile_response)
hs = [h]
seen = set([])
for child in parent.children():
latlng = main.LatLng.from_point(main.Cell(child).get_center())
main.set_location_coords(latlng.lat().degrees, latlng.lng().degrees, 0)
hs.append(main.get_heartbeat(
args.auth_service,
api_endpoint,
access_token,
profile_response))
main.set_location_coords(step_lat, step_long, 0)
visible = []
for hh in hs:
try:
for cell in hh.cells:
for wild in cell.WildPokemon:
_hash = wild.SpawnPointId + ':' \
+ str(wild.pokemon.PokemonId)
if _hash not in seen:
visible.append(wild)
seen.add(_hash)
if cell.Fort:
for Fort in cell.Fort:
if Fort.Enabled:
if Fort.GymPoints:
gyms.append(Gym(Fort.Team,
Fort.Latitude,
Fort.Longitude,
Fort.GymPoints))
elif Fort.FortType:
expire_time = 0
if Fort.LureInfo.LureExpiresTimestampMs:
expire_time = \
main.datetime.fromtimestamp(
Fort.LureInfo
.LureExpiresTimestampMs / 1000.0
).strftime("%H:%M:%S")
pokestops.append(PokeStop(Fort.Latitude,
Fort.Longitude,
expire_time > 0,
expire_time))
except AttributeError:
break
for poke in visible:
disappear_timestamp = main.time.time() + poke.TimeTillHiddenMs / 1000
pokemons.append(Pokemon(poke.pokemon.PokemonId,
poke.Latitude,
poke.Longitude,
main.datetime.fromtimestamp(disappear_timestamp)
.strftime("%H:%M:%S"),
long(disappear_timestamp),
poke.SpawnPointId))
return pokemons, gyms, pokestops
class PokeStop(object):
def __init__(self, lat, lng, lured, expire_time):
self.lat = lat
self.lng = lng
self.lured = lured
self.expire_time = expire_time
def to_json(self):
return {
"lat": self.lat,
"lng": self.lng,
"lured": self.lured,
"expire_time": self.expire_time}
class Gym(object):
def __init__(self, team, lat, lng, score):
self.team = team
self.lat = lat
self.lng = lng
self.score = score
def to_json(self):
return {
"team": self.team,
"lat": self.lat,
"lng": self.lng,
"score": self.score}
class Pokemon(object):
def __init__(self, number, lat, lng, expire_time, disappear_time, spawn_id):
self.number = number
self.lng = lng
self.lat = lat
self.expire_time = expire_time
self.disappear_time = disappear_time
self.spawn_id = spawn_id
self._hash = hash(str(spawn_id) + ':' + str(number))
def to_json(self):
return {
"id": self.number,
"lat": self.lat,
"lng": self.lng,
"expire_time": self.expire_time,
"disappear_time": self.disappear_time,
"hash": self._hash}
def __hash__(self):
return self._hash
def __eq__(self, other):
return self.number == other.number\
and self.spawn_id == other.spawn_id
class PokemonHandlerFactory(object):
def __init__(self):
self.lock = Lock()
def treat_request(self, request):
from urlparse import urlparse
result = None
url = urlparse(request.path)
env = {"REQUEST_METHOD": request.command, "QUERY_STRING": url.query,
"CONTENT_LENGTH": request.headers.get('Content-Length', -1),
"CONTENT_TYPE": request.headers.get('Content-Type', None)}
parsed = cgi.parse(request.rfile, env)
def get_field(name, integer=False, double=False):
r = parsed.get(name)
if not r:
return None
if integer:
return int(r[0])
if double:
return float(r[0])
return r[0]
try:
if request.command == "GET":
idy = get_field("id", integer=True)
lat = get_field("lat", double=True)
lng = get_field("lng", double=True)
rad = get_field("rad", integer=True)
x = get_field("x", integer=True)
y = get_field("y", integer=True)
if not idy or not lat or not lng or not rad:
raise HTTPException(417, "All the fields were not supplied")
pokemons, gyms, pokestops =\
find_pokemons(str(lat) + ", " + str(lng), rad, x, y)
if len(pokemons) == 0:
main.login_session = None
pokemons, gyms, pokestops = \
find_pokemons(str(lat) + ", " + str(lng), rad)
result = {"id": idy,
"pokemons": [p.to_json() for p in pokemons],
"gyms": [g.to_json() for g in gyms],
"pokestops": [s.to_json() for s in pokestops]}
elif request.command == "POST":
r2 = json.dumps({"dump": "ok"}).encode("UTF-8")
request.send_response(200, 'OK')
request.send_header('Content-Type', 'application/json')
request.send_header('Content-Length', str(len(r2)))
request.end_headers()
request.wfile.write(r2)
restart()
except HTTPException as e:
request.send_response(417, e.message)
request.end_headers()
except Exception as e:
request.send_response(
500,
"An exception was encountered with the message {}".format(e)
)
request.end_headers()
else:
r2 = json.dumps(result).encode("UTF-8")
request.send_response(200, 'OK')
request.send_header('Content-Type', 'application/json')
request.send_header('Content-Length', str(len(r2)))
request.end_headers()
request.wfile.write(r2)
def get_handler(self):
p = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self): return p.treat_request(self)
def do_POST(self): return p.treat_request(self)
return Handler
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
def restart():
prog = sys.executable
os.execl(prog, prog, *sys.argv)
if __name__ == '__main__':
logger = logging.getLogger("PokemonGo-Finder")
logger.setLevel(logging.INFO)
if len(sys.argv) < 2:
print(__doc__)
sys.exit(-1)
else:
(iface, port) = sys.argv[1].split('/', 1)
httpServer = ThreadingHTTPServer((iface, int(port)),
PokemonHandlerFactory().get_handler())
httpServer.serve_forever()