-
Notifications
You must be signed in to change notification settings - Fork 50
/
pokesite.py
157 lines (132 loc) · 6.13 KB
/
pokesite.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
from flask import Flask, render_template, g, request, jsonify
from flask_compress import Compress
import os, sys
import socket
# import SocketServer
# import BaseHTTPServer
import signal
import time
import json
import sqlite3
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import tornado.options
tornado.options.parse_command_line()
workdir = os.path.dirname(os.path.realpath(__file__))
data_file = '{}/webres/data.db'.format(workdir)
settings_file = '{}/res/usersettings.json'.format(workdir)
exclude_ids = None
def signal_handler(signal, frame):
sys.exit()
signal.signal(signal.SIGINT, signal_handler)
def isnotExcluded(id):
return not (id in exclude_ids)
def server_start():
global exclude_ids
try:
f = open(settings_file, 'r')
try:
allsettings = json.load(f)
except ValueError as e:
print('[-] Error: The settings file is not in a valid format, {}'.format(e))
f.close()
sys.exit()
f.close()
finally:
if 'f' in vars() and not f.closed:
f.close()
exclude_ids = allsettings['exclude_ids']
port = allsettings['port']
if allsettings['icon_set'] == 'standard':
icon_set = 'icons_gen1_standard.png'
elif allsettings['icon_set'] == 'shuffle':
icon_set = 'icons_gen1_shuffle.png'
elif allsettings['icon_set'] == 'alt':
icon_set = 'icons_gen1_alt.png'
elif allsettings['icon_set'] == 'toon':
icon_set = 'icons_gen1_toon.png'
else:
print('[-] Error: Icon set in settings file is invalid, possible sets are: "standard", "shuffle", "toon", "alt".')
list_profiles = []
list_lats = []
list_lngs = []
for i in range(0, len(allsettings['profiles'])):
if allsettings['profiles'][i]['id'] not in list_profiles:
list_profiles.append(allsettings['profiles'][i]['id'])
list_lats.append(allsettings['profiles'][i]['coordinates']['lat'])
list_lngs.append(allsettings['profiles'][i]['coordinates']['lng'])
if len(list_profiles) == 0:
print('[-] Error: No profiles in settings file.')
sys.exit()
else:
main_ind = 0
db_data = sqlite3.connect(data_file, check_same_thread=False)
db_data.create_function("isnotExcluded", 1, isnotExcluded)
# def patched_finish(self):
# print('still')
# try:
# if not self.wfile.closed:
# self.wfile.close()
# except socket.error as e:
# sys.stdout.write('socket error: {}\n'.format(e))
# self.rfile.close()
# SocketServer.StreamRequestHandler.finish = patched_finish
# BaseHTTPServer.HTTPServer.allow_reuse_address = False
compress = Compress()
app = Flask(__name__,template_folder=workdir+'/'+'webres',static_url_path='/static',static_folder=workdir+'/webres/static')
app.config['COMPRESS_MIN_SIZE'] = 0
app.config['COMPRESS_LEVEL'] = 6
app.config['COMPRESS_MIMETYPES'] = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript', 'application/octet-stream', 'image/svg+xml']
compress.init_app(app)
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
if db is not None:
db.close()
@app.after_request
def add_header(response):
if response.headers['Content-Type'] == "image/png":
response.headers['Cache-Control'] = 'must-revalidate, public, max-age=86400'
else:
response.headers['Cache-Control'] = 'must-revalidate, public, max-age=-1'
return response
@app.route('/_getdata')
def add_numbers():
datatill = request.args.get('data_till', 0, type=int)
profile = request.args.get('profile', -1, type=int)
timenow = int(round(time.time(),0))
cursor_data = db_data.cursor()
while True:
try:
if profile == -1:
results = cursor_data.execute('SELECT spawnid, latitude, longitude, spawntype, pokeid, expiretime FROM spawns WHERE isnotExcluded(pokeid) AND (expiretime > ?) AND (fromtime >= ?)',(timenow,datatill))
else:
results = cursor_data.execute('SELECT spawnid, latitude, longitude, spawntype, pokeid, expiretime FROM spawns WHERE isnotExcluded(pokeid) AND (profile == ?) AND (expiretime > ?) AND (fromtime >= ?)', (profile,timenow, datatill))
return jsonify([timenow, results.fetchall()])
except sqlite3.OperationalError as e:
print('[-] Sqlite operational error: {} Retrying...'.format(e))
@app.route("/")
def mainapp():
return render_template('index.html',api_key=allsettings['api_key'],icon_scalefactor=allsettings['icon_scalefactor'],mobile_scale=allsettings['mobile_scalefactor'],lat=list_lats[main_ind],lng=list_lngs[main_ind],language=allsettings['language'],icon_set = icon_set, profile=-1)
@app.route("/id<int:profile>")
def subapp(profile):
if profile in list_profiles:
sub_ind = list_profiles.index(profile)
return render_template('index.html', api_key=allsettings['api_key'], icon_scalefactor=allsettings['icon_scalefactor'], mobile_scale=allsettings['mobile_scalefactor'],lat=list_lats[sub_ind],lng=list_lngs[sub_ind], language=allsettings['language'], icon_set = icon_set, profile=profile)
http_server = HTTPServer(WSGIContainer(app))
try:
http_server.listen(port=port,address='0.0.0.0')
IOLoop.instance().start()
except socket.error as e:
if e.errno == 10048:
print('[-] Error: The specified port {} is already in use.'.format(port))
# while True:
# try:
# app.run(host='0.0.0.0', port=port, threaded=True)
# except socket.error as e:
# if e.errno == 10048:
# print('[-] Error: The specified port {} is already in use.'.format(port))
# break
if __name__ == "__main__":
server_start()