This repository has been archived by the owner on Feb 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
testserver.py
335 lines (267 loc) · 13.2 KB
/
testserver.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
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
"""
This server is a test version of the production app.py. It will send dummy replies for every API Call.
The replies and test functions are described inside the docstrings.
"""
from flask import Flask, jsonify
from geopy.geocoders import GoogleV3
from backend.pokemon import Pokemon
from backend.pokehelper import Pokehelper
from flask import make_response, request
from flask_cors import CORS
from geopy.exc import GeocoderServiceError
import json
import time
import random
app = Flask(__name__)
CORS(app)
TESTFILE = "example-dump.json"
with open(TESTFILE) as pokemon_data:
data = json.load(pokemon_data)
pokehelper = Pokehelper()
status = {'logged_in': False}
deleted_pokemon = 0
pokemon_deletion_amount = 0
player_level = None
@app.route('/', methods=['GET'])
def index():
return jsonify({'status': 'ok',
'message': 'Welcome to the pogo-cruncher API! Seems like everything is working fine.'})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.route('/api/login', methods=['POST'])
def login():
"""
It does not matter what data you send as long as there is a `password`, `email` and `service`.
If you want to simulate a failing login, send an additonal `'fail': <some message>`. The API will answer
with an error and return the message inside the `message` field.
:return: Always returns an `ok` status if `resolve` is not sent. Otherwise return `ok` when the location could be
found and an `error` including a message if not.
"""
global data
with open(TESTFILE) as pokemon_data:
data = json.load(pokemon_data)
if request.json.get('fail', False):
return jsonify({'status': 'error',
'message': request.json['fail']})
global status
status['logged_in'] = True
return jsonify({'status': 'ok'})
@app.route('/api/pokemon', methods=['GET'])
def get_pokemon():
"""
The API endpoint allways returns the same test data. If you want to reset the pokemon list, logout and back in.
:return: Returns a list of Pokemon inside a dict.
"""
items = data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']
# Build answer Pokemon list
answer = list()
candies = dict()
for item in items:
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
pokemon = Pokemon(item['inventory_item_data']['pokemon_data'])
answer.append({
'id': str(pokemon.id),
'pokemon_id': pokemon.pokemon_number,
'individual_attack': pokemon.iv_att,
'individual_stamina': pokemon.iv_sta,
'individual_defense': pokemon.iv_def,
'individual_percentage': float(pokemon.iv_percentage()),
'health': pokemon.stamina_max,
'cp': pokemon.cp,
'nickname': pokemon.nickname,
'favorite': pokemon.is_favorite(),
'move_1': pokemon.move_1,
'move_2': pokemon.move_2,
'level': pokemon.level(),
'powerup_cost_stardust': pokemon.powerup_stardust_cost(),
'powerup_cost_candy': pokemon.powerup_candy_cost(),
'attack': pokemon.attack,
'defense': pokemon.defense,
})
elif 'candy' in item['inventory_item_data']:
candy_data = item['inventory_item_data']['candy']
candies[candy_data['family_id']] = candy_data.get("candy", 0)
elif 'player_stats' in item['inventory_item_data']:
global player_level
player_level = item['inventory_item_data']['player_stats']['level']
for poke in answer:
family = pokehelper.get_pokefamily(poke['pokemon_id'])
poke['candy'] = candies.get(family, 0)
return jsonify(answer)
@app.route('/api/pokemon/delete', methods=['POST'])
def delete_pokemon():
"""
Deletes the sent pokemon inside the local storage. If you want to reset the db, send a new login call.
Simulates the sleeping calls from the main app as well.
:return: Returns `'status': 'ok'`, as soon as the db is done.
"""
deletion_candidates = request.json['ids']
global pokemon_deletion_amount
global deleted_pokemon
global data
print('In Deletion process')
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
if 'safe' not in request.json:
while(len(deletion_candidates) != 0):
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if str(item['inventory_item_data']['pokemon_data']['id']) in deletion_candidates:
data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'].pop(count)
deletion_candidates.remove(str(item['inventory_item_data']['pokemon_data']['id']))
break
print("Done deleting")
else:
pokemon_deletion_amount = len(deletion_candidates)
deleted_pokemon = 0
while(len(deletion_candidates) != 0):
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if str(item['inventory_item_data']['pokemon_data']['id']) in deletion_candidates:
data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'].pop(count)
deletion_candidates.remove(str(item['inventory_item_data']['pokemon_data']['id']))
deleted_pokemon += 1
print('Deleted Pokemon %d out of %d' % (deleted_pokemon, pokemon_deletion_amount))
time.sleep(random.randint(200, 350)/100)
break
print("Done deleting")
pokemon_deletion_amount = 0
deleted_pokemon = 0
return jsonify({'status': 'ok'})
@app.route('/api/status/delete', methods=['GET'])
def deletion_status():
"""
Request how much pokemon have been deelted in the current sitting.
:return: Returns the amount of pokemon to be deleted in total and the count of pokemon currently deleted.
"""
return jsonify({'status': 'ok',
'to_delete': pokemon_deletion_amount,
'deleted': deleted_pokemon})
@app.route('/api/pokemon/favorite', methods=['POST'])
def favorite_pokemon():
"""
Set or unset a favorite pokemon. Expects the values `id` and `set_favorite` (boolean).
:return: Returns status ok if there were no errors.
"""
pokemon_id = int(request.json['id'])
set_favorite = request.json['set_favorite']
global data
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if item['inventory_item_data']['pokemon_data']['id'] == pokemon_id:
data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']['favorite'] = set_favorite
print("Pokemon favorite status has been set to " +
str(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']['favorite']))
break
return jsonify({'status': 'ok',
'id': str(pokemon_id),
'set_favorite': set_favorite})
@app.route('/api/pokemon/rename', methods=['POST'])
def rename_pokemon():
"""
Rename a pokemon. Expects the values `id` and `name` (string).
:return: Returns status ok if there were no errors.
"""
rename_list = request.json
print(request.json)
global data
global pokemon_deletion_amount
global deleted_pokemon
pokemon_deletion_amount = len(request.json)
deleted_pokemon = 0
for pokemon in rename_list:
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if item['inventory_item_data']['pokemon_data']['id'] == int(pokemon['id']):
data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']['nickname'] = pokemon['name']
print("Pokemon renamed to " +
str(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']['nickname']))
deleted_pokemon += 1
time.sleep(random.randint(200, 350)/100)
break
return jsonify({'status': 'ok'})
@app.route('/api/status', methods=['GET'])
def api_status():
return jsonify({'status': 'ok'})
@app.route('/api/status/niantic', methods=['GET'])
def niantic_status():
if status['logged_in']:
return jsonify({'status': 'ok'})
return jsonify({'status': 'error',
'message': 'The connection to the Pokemon Go Servers could not be established. Please Logout and back in.'})
@app.route('/api/player', methods=['GET'])
def get_player():
"""
Request Information about the player.
:return: Return a json dictionary including `name`, `stardust`, `pokecoins`.
"""
player_data = data['responses']['GET_PLAYER']['player_data']
pokecoins = 0
stardust = 0
for currency in player_data['currencies']:
if currency['name'] == 'STARDUST':
stardust = currency.get('amount', 0)
elif currency['name'] == 'POKECOIN':
pokecoins = currency.get('amount', 0)
answer = {
'name': player_data.get('username'),
'stardust': stardust,
'pokecoins': pokecoins,
}
if player_level:
answer['level'] = player_level
return jsonify(answer)
@app.route('/api/pokemon/evolve', methods=['POST'])
def evolve_pokemon():
"""
Evolves Pokemon. The post request has to have an `id` field which contains the id of the pokemon to be evolved.
:return: Return a status: ok if everything is finished.
"""
evolution_candidate = int(request.json['id'])
global data
answer = {'status': 'ok'}
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if item['inventory_item_data']['pokemon_data']['id'] == evolution_candidate:
pokemon = data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']
pokemon['cp'] *= 2
pokemon['name'] = pokehelper.get_evolution_name(pokemon['pokemon_id'])
pokemon['pokemon_id'] += 1
print("Pokemon has been evolved to " +
str(pokemon['name']))
break
return jsonify(answer)
@app.route('/api/pokemon/upgrade', methods=['POST'])
def upgrade_pokemon():
pokemon_id = int(request.json['id'])
global data
print('upgrading')
invlist = list(data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'])
for count, item in enumerate(invlist):
if 'pokemon_data' in item['inventory_item_data']:
# Eggs are treated as pokemon by Niantic.
if 'is_egg' not in item['inventory_item_data']['pokemon_data']:
if item['inventory_item_data']['pokemon_data']['id'] == pokemon_id:
pokemon = data['responses']['GET_INVENTORY']['inventory_delta']['inventory_items'][count]['inventory_item_data']['pokemon_data']
pokemon['cp'] += 30
break
return jsonify({'status': 'ok'})
if __name__ == '__main__':
app.run(threaded=True)