Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
62 lignes
3.3 KiB
Python
62 lignes
3.3 KiB
Python
"""Serveur LAN du site Romma : fichiers statiques + sauvegarde de la selection (GET/POST /api/selection).
|
|
Usage : python server.py [port] [dossier-du-site] (la selection est stockee dans selection.json a cote de ce script)"""
|
|
import http.server, json, os, re, sys, threading, time
|
|
|
|
ICI = os.path.dirname(os.path.abspath(__file__))
|
|
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8780
|
|
SITE = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else ICI
|
|
FICHIER = os.path.join(ICI, 'selection.json')
|
|
VERROU = threading.Lock()
|
|
ID = re.compile(r'^[0-9A-Za-z_-]{1,12}$')
|
|
|
|
def lire():
|
|
try:
|
|
with open(FICHIER, encoding='utf-8') as f: return json.load(f)
|
|
except Exception: return {'supprimees': None, 'maj': 0}
|
|
|
|
class H(http.server.SimpleHTTPRequestHandler):
|
|
def __init__(self, *a, **k): super().__init__(*a, directory=SITE, **k)
|
|
def _json(self, code, obj):
|
|
b = json.dumps(obj).encode()
|
|
self.send_response(code); self.send_header('Content-Type', 'application/json')
|
|
self.send_header('Content-Length', str(len(b))); self.send_header('Cache-Control', 'no-store'); self.end_headers(); self.wfile.write(b)
|
|
def _autorise(self, chemin):
|
|
c = chemin.split('?')[0].split('#')[0]
|
|
if c in ('/', '/index.html', '/style.css', '/app.js', '/favicon.ico'): return True
|
|
if c.startswith('/vendor/leaflet/'):
|
|
if '%' in c or chr(92) in c or '..' in c: return False
|
|
reel = os.path.realpath(self.translate_path(c))
|
|
return reel.startswith(os.path.realpath(os.path.join(SITE, 'vendor', 'leaflet')) + os.sep)
|
|
return c in ('/data/stations-romma.js', '/data/stations-romma.csv', '/data/stations-romma.json', '/data/refs.js')
|
|
def list_directory(self, path):
|
|
self.send_error(404); return None
|
|
def do_GET(self):
|
|
if self.path.split('?')[0] == '/api/selection':
|
|
with VERROU: return self._json(200, lire())
|
|
if not self._autorise(self.path): return self.send_error(404)
|
|
super().do_GET()
|
|
def do_HEAD(self):
|
|
if not self._autorise(self.path): return self.send_error(404)
|
|
super().do_HEAD()
|
|
def do_POST(self):
|
|
if self.path.split('?')[0] != '/api/selection': return self._json(404, {'erreur': 'inconnu'})
|
|
if (self.headers.get('Content-Type') or '').split(';')[0].strip() != 'application/json': return self._json(415, {'erreur': 'type'})
|
|
org = self.headers.get('Origin')
|
|
if org and org.split('://', 1)[-1] != self.headers.get('Host'): return self._json(403, {'erreur': 'origine'})
|
|
n = int(self.headers.get('Content-Length') or 0)
|
|
if n <= 0 or n > 200000: return self._json(413, {'erreur': 'taille'})
|
|
try:
|
|
d = json.loads(self.rfile.read(n)); s = d['supprimees']
|
|
if not isinstance(s, list) or len(s) > 5000 or not all(isinstance(x, str) and ID.match(x) for x in s): raise ValueError
|
|
except Exception: return self._json(400, {'erreur': 'format'})
|
|
obj = {'supprimees': sorted(set(s)), 'maj': int(time.time())}
|
|
with VERROU:
|
|
tmp = FICHIER + '.tmp'
|
|
with open(tmp, 'w', encoding='utf-8') as f: json.dump(obj, f)
|
|
os.replace(tmp, FICHIER)
|
|
self._json(200, obj)
|
|
def log_message(self, *a): pass
|
|
|
|
if __name__ == '__main__':
|
|
http.server.ThreadingHTTPServer(('0.0.0.0', PORT), H).serve_forever()
|