This repository has been archived by the owner on Jul 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
198 lines (148 loc) · 5.21 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
"""
By Ultrasonic1209
I have no clue what I'm doing
"""
import gzip
from io import BytesIO
from typing import TypedDict
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy import select
from sqlalchemy.engine import Result
from sqlalchemy.orm import sessionmaker
import sanic, toml
from sanic.response import json
from models import Map, MapMeta, MapTile, Map
class ConfigSql(TypedDict):
database_url: str
class ConfigServer(TypedDict):
bind: str
port: int
access_log: bool
threads: int
forwarded_secret: str
class Config(TypedDict):
sql: ConfigSql
server: ConfigServer
app = sanic.Sanic("bluemap-server")
with open('config.toml', 'r') as f:
extconfig: Config = toml.load(f)
dburl = extconfig["sql"]["database_url"]
serverbind = extconfig["server"]["bind"]
serverport = extconfig["server"]["port"]
accesslog = extconfig["server"]["access_log"]
threads = extconfig["server"]["threads"]
secret = extconfig["server"]["forwarded_secret"]
app.config.ACCESS_LOG = accesslog
if secret != "":
app.config.FORWARDED_SECRET = secret
bind = create_async_engine(
dburl,
pool_pre_ping=True,
)
# https://stackoverflow.com/a/70390426/4784039
is_numeric = lambda x: x.replace('.', '', 1).replace('-', '', 1).isdigit()
_sessionmaker = sessionmaker(bind, AsyncSession, expire_on_commit=False)
@app.middleware("request")
async def inject_session(request):
request.ctx.session = _sessionmaker()
@app.middleware("response")
async def close_session(request, response):
if session := getattr(request.ctx, "session"):
await session.close()
@app.get("/maps/<world:str>/.rstate")
async def get_render_state(request: sanic.Request, world: str):
session: AsyncSession = request.ctx.session
async with session.begin():
getMapStmt = select(Map).where(Map.map_id == world)
getMapRes: Result = await session.execute(getMapStmt)
getMapRow = getMapRes.first()
map: Map = getMapRow["Map"]
if map is None:
return json({})
meta: MapMeta = await session.get(MapMeta, {
"map": map.id,
"key": "render_state"
})
if meta is None:
return json({})
response = sanic.HTTPResponse()
response.body = meta.value
response.headers["content-type"] = "application/octet-stream"
response.headers["content-encoding"] = "gzip"
response.headers["vary"] = "Accept-Encoding"
return response
@app.get("/maps/<world:str>/<reqmeta:ext=json>")
async def get_meta(request: sanic.Request, world: str, reqmeta: str, ext: str):
session: AsyncSession = request.ctx.session
async with session.begin():
getMapStmt = select(Map).where(Map.map_id == world)
getMapRes: Result = await session.execute(getMapStmt)
getMapRow = getMapRes.first()
map: Map = getMapRow["Map"]
if map is None:
return json({})
meta: MapMeta = await session.get(MapMeta, {
"map": map.id,
"key": reqmeta
})
if meta is None:
return json({})
response = sanic.HTTPResponse()
response.body = meta.value
response.headers["content-type"] = "application/json"
response.headers["content-encoding"] = "gzip"
response.headers["vary"] = "Accept-Encoding"
return response
@app.get("/maps/<world:str>/tiles/<lod:int>/<params:path>")
async def get_tile(request: sanic.Request, world: str, lod: int, params: str):
session: AsyncSession = request.ctx.session
parsedparams = params.split("/")
if len(parsedparams) == 0: return json({})
if not parsedparams[len(parsedparams) - 1].endswith(".json"): return json({})
parsedparams[len(parsedparams) - 1] = parsedparams[len(parsedparams) - 1][:-5]
isX = False
isZ = False
x = ""
z = ""
for param in parsedparams:
if param.startswith("x"):
isX = True
isZ = False
param = param[1:]
elif param.startswith("z"):
isX = False
isZ = True
param = param[1:]
if is_numeric(param):
if isX:
x += param
elif isZ:
z += param
else:
return json({"error": f"unknown coordinate fragment {param}"})
async with session.begin():
getMapStmt = select(Map).where(Map.map_id == world)
getMapRes: Result = await session.execute(getMapStmt)
getMapRow = getMapRes.first()
map: Map = getMapRow["Map"]
if map is None:
return json({})
maptile: MapTile = await session.get(MapTile, {
"map": map.id,
"lod": lod,
"x": int(x),
"z": int(z),
})
if maptile is None:
return json({})
response = sanic.HTTPResponse()
response.body = maptile.data
response.headers["content-type"] = "application/json"
response.headers["content-encoding"] = "gzip"
response.headers["vary"] = "Accept-Encoding"
return response
if __name__ == "__main__":
if threads <= 0:
app.run(host=serverbind, port=serverport, fast=True)
else:
app.run(host=serverbind, port=serverport, workers=threads)