84 lines
4.7 KiB
Python
84 lines
4.7 KiB
Python
|
|
"""Same-origin public basemap gateway. Never receives member tokens or coordinates.
|
||
|
|
|
||
|
|
Only immutable geography is cached; family locations stay on the existing auth APIs.
|
||
|
|
The bundled PMTiles daemon listens on loopback and reads prebuilt archives.
|
||
|
|
"""
|
||
|
|
from pathlib import Path
|
||
|
|
import http.client
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import re
|
||
|
|
import threading
|
||
|
|
import urllib.parse
|
||
|
|
import map_archive
|
||
|
|
|
||
|
|
SLOTS = threading.BoundedSemaphore(6)
|
||
|
|
MAX_TILE = 2 * 1024 * 1024
|
||
|
|
|
||
|
|
|
||
|
|
class Maps:
|
||
|
|
def __init__(self, app):
|
||
|
|
self.app = app
|
||
|
|
self.root = Path(os.environ.get('VISION_MAP_DATA', app.DATA / 'maps')).resolve()
|
||
|
|
self.port = int(os.environ.get('VISION_MAP_PORT', '8841'))
|
||
|
|
self.archive = map_archive.Archive(self)
|
||
|
|
|
||
|
|
def catalog(self):
|
||
|
|
# Readiness comes from atomic, verified archive installation, never a partial.
|
||
|
|
regions=[]
|
||
|
|
for key,spec in self.archive.specs().items():
|
||
|
|
file=self.root/(key+'.pmtiles')
|
||
|
|
if file.is_file():regions.append(dict(spec,revision=str(file.stat().st_mtime_ns)))
|
||
|
|
return dict(revision='|'.join(r['id']+r['revision'] for r in regions),regions=regions,
|
||
|
|
attribution='© OpenStreetMap contributors · Protomaps')
|
||
|
|
|
||
|
|
def respond(self, handler, raw, mime, *, status=200, encoding=None, cache=True):
|
||
|
|
handler.send_response(status)
|
||
|
|
handler.send_header('Content-Type', mime)
|
||
|
|
handler.send_header('Content-Length', str(len(raw)))
|
||
|
|
handler.send_header('X-Content-Type-Options', 'nosniff')
|
||
|
|
handler.send_header('Cache-Control', 'public, max-age=3600' if status==200 and cache else 'no-store')
|
||
|
|
if encoding: handler.send_header('Content-Encoding', encoding)
|
||
|
|
handler.end_headers()
|
||
|
|
if handler.command != 'HEAD': handler.wfile.write(raw)
|
||
|
|
|
||
|
|
def serve(self, handler, path):
|
||
|
|
if path == '/maps/catalog.json':
|
||
|
|
self.respond(handler, json.dumps(self.catalog(), ensure_ascii=False).encode(), 'application/json; charset=utf-8',cache=False)
|
||
|
|
return
|
||
|
|
match = re.fullmatch(r'/maps/tiles/(world|china|cn-\d{2})/(\d{1,2})/(\d{1,5})/(\d{1,5})\.mvt', path)
|
||
|
|
if match:
|
||
|
|
name,z,x,y=match.groups(); z,x,y=map(int,(z,x,y))
|
||
|
|
spec=self.archive.specs().get(name)
|
||
|
|
if not spec or z > spec['maxZoom'] or not 0<=x<2**z or not 0<=y<2**z:
|
||
|
|
raise self.app.Problem('地图层级不存在', 404)
|
||
|
|
if not (self.root/(name+'.pmtiles')).is_file():
|
||
|
|
self.respond(handler,b'','application/vnd.mapbox-vector-tile',status=204);return
|
||
|
|
if not SLOTS.acquire(blocking=False): raise self.app.Problem('地图正在加载,请稍后重试', 503)
|
||
|
|
connection = http.client.HTTPConnection('127.0.0.1', self.port, timeout=4)
|
||
|
|
try:
|
||
|
|
# No browser headers, cookies, bearer tokens, queries or user URLs forwarded.
|
||
|
|
connection.request('GET', f'/{name}/{z}/{x}/{y}.mvt', headers={'Accept-Encoding':'gzip'})
|
||
|
|
response=connection.getresponse()
|
||
|
|
if response.status in (204,404):
|
||
|
|
self.respond(handler,b'', 'application/vnd.mapbox-vector-tile',status=204);return
|
||
|
|
if response.status!=200: raise self.app.Problem('内置地图暂时不可用',503)
|
||
|
|
raw=response.read(MAX_TILE+1)
|
||
|
|
if len(raw)>MAX_TILE: raise self.app.Problem('地图数据超出限制',502)
|
||
|
|
encoding=response.getheader('Content-Encoding')
|
||
|
|
if encoding not in (None,'gzip'): raise self.app.Problem('地图编码不支持',502)
|
||
|
|
self.respond(handler,raw,'application/vnd.mapbox-vector-tile',encoding=encoding)
|
||
|
|
except (OSError,http.client.HTTPException):
|
||
|
|
raise self.app.Problem('内置地图暂时不可用',503)
|
||
|
|
finally:
|
||
|
|
connection.close();SLOTS.release()
|
||
|
|
return
|
||
|
|
asset=urllib.parse.unquote(path.removeprefix('/maps/assets/'))
|
||
|
|
if path.startswith('/maps/assets/') and (re.fullmatch(r'fonts/(?:Noto Sans (?:Regular|Medium|Italic)|Noto Sans Devanagari Regular)/(?:\d{1,5}-\d{1,5}\.pbf)',asset) or re.fullmatch(r'sprites/v4/(?:light|dark)(?:@2x)?\.(?:json|png)',asset)):
|
||
|
|
file=(self.root/'assets'/asset).resolve()
|
||
|
|
if not file.is_relative_to(self.root/'assets') or not file.is_file(): raise self.app.Problem('地图资源不存在',404)
|
||
|
|
if file.stat().st_size>MAX_TILE: raise self.app.Problem('地图资源超出限制',502)
|
||
|
|
mime='image/png' if file.suffix=='.png' else 'application/json' if file.suffix=='.json' else 'application/x-protobuf'
|
||
|
|
self.respond(handler,file.read_bytes(),mime);return
|
||
|
|
raise self.app.Problem('地图资源不存在',404)
|