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
/
app.py
executable file
·277 lines (221 loc) · 9.25 KB
/
app.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
from flask import Flask, jsonify
from geopy.geocoders import Nominatim
from pgoapi.pgoapi import PGoApi
from pgoapi.exceptions import AuthException
from backend.pokemon import Pokemon
from backend.pokehelper import Pokehelper
from flask import make_response, request
from flask_cors import CORS
import time
import random
app = Flask(__name__)
CORS(app)
pokeapi = PGoApi()
pokehelper = Pokehelper()
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():
login_name = request.json['email']
service = request.json['service']
password = request.json['password']
location = request.json['location']
geolocator = Nominatim()
location = geolocator.geocode(location)
if not location:
location = geolocator.geocode("Düsseldorf, Germany")
latitude = location.latitude
longitude = location.longitude
try:
logged_in = pokeapi.login(service, login_name, password,
lat=latitude, lng=longitude, app_simulation=True)
except AuthException as e:
return jsonify({'status': 'error',
'message': e.__str__()})
time.sleep(1)
if not logged_in:
return jsonify({'status': 'error',
'message': 'Failed to login. If the Pokemon GO Servers are online, your credentials may be wrong.'})
else:
return jsonify({'status': 'ok'})
@app.route('/api/pokemon', methods=['GET'])
def get_pokemon():
time.sleep(1)
req = pokeapi.create_request()
req.get_inventory()
# Make the Niantic API call
response_dict = req.call()
if not response_dict:
return jsonify({'status': 'error',
'message': 'Failed to retrieve Pokemon. The servers are probably down right now.'})
if 'GET_INVENTORY' in response_dict['responses']:
items = response_dict['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']
# add candies to answerdict
for poke in answer:
family = pokehelper.get_pokefamily(poke['pokemon_id'])
poke['candy'] = candies.get(family, 0)
return jsonify(answer)
else:
return jsonify({'status': 'error',
'message': 'Login successful, but your inventory could not be loaded...'})
@app.route('/api/pokemon/delete', methods=['POST'])
def delete_pokemon():
deletion_candidates = request.json['ids']
global pokemon_deletion_amount
global deleted_pokemon
if 'safe' not in request.json:
for id in deletion_candidates:
req = pokeapi.create_request()
req.release_pokemon(pokemon_id=int(id))
req.call()
else:
pokemon_deletion_amount = len(deletion_candidates)
deleted_pokemon = 0
for id in deletion_candidates:
req = pokeapi.create_request()
req.release_pokemon(pokemon_id=int(id))
req.call()
# Sleep some random time between two and three seconds
time.sleep(random.randint(200, 350)/100)
deleted_pokemon += 1
print('Deleted Pokemon %d out of %d' % (deleted_pokemon, pokemon_deletion_amount))
pokemon_deletion_amount = 0
deleted_pokemon = 0
return jsonify({'status': 'ok'})
@app.route('/api/status/delete', methods=['GET'])
def deletion_status():
return jsonify({'status': 'ok',
'to_delete': pokemon_deletion_amount,
'deleted': deleted_pokemon})
@app.route('/api/pokemon/favorite', methods=['POST'])
def favorite_pokemon():
pokemon_id = int(request.json['id'])
set_favorite = request.json['set_favorite']
req = pokeapi.create_request()
req.set_favorite_pokemon(pokemon_id=pokemon_id, is_favorite=set_favorite)
req.call()
return jsonify({'status': 'ok',
'id': str(pokemon_id),
'set_favorite': set_favorite})
@app.route('/api/pokemon/rename', methods=['POST'])
def rename_pokemon():
global pokemon_deletion_amount
global deleted_pokemon
rename_list = request.json
pokemon_deletion_amount = len(request.json)
deleted_pokemon = 0
for pokemon in rename_list:
req = pokeapi.create_request()
req.nickname_pokemon(pokemon_id=int(pokemon['id']), nickname=pokemon['name'])
req.call()
deleted_pokemon += 1
time.sleep(random.randint(200, 350)/100)
return jsonify({'status': 'ok'})
@app.route('/api/pokemon/upgrade', methods=['POST'])
def upgrade_pokemon():
pokemon_id = int(request.json['id'])
req = pokeapi.create_request()
req.upgrade_pokemon(pokemon_id=pokemon_id)
req.call()
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():
req = pokeapi.create_request()
req.echo()
response_dict = req.call()
if 'ECHO' in response_dict['responses']:
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`.
"""
req = pokeapi.create_request()
req.get_player()
response_dict = req.call()
if 'GET_PLAYER' in response_dict['responses']:
player_data = response_dict['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)
return jsonify({
'status': 'error',
'message': 'There was an error retrieving player data. If the error persists, try to log in anew.'
})
@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 = request.json['id']
req = pokeapi.create_request()
req.evolve_pokemon(pokemon_id=int(evolution_candidate))
req.call()
return jsonify({'status': 'ok'})
if __name__ == '__main__':
app.run(threaded=True)
# For windows installer to hook in
def main():
import os
os.startfile(os.path.dirname(os.path.abspath(__file__)) + '\..\interface\index.html')
app.run(threaded=True)