66 lines
2.0 KiB
Python
66 lines
2.0 KiB
Python
import sqlite3
|
|
import os
|
|
from flask import Flask, render_template, request, jsonify
|
|
|
|
app = Flask(__name__)
|
|
|
|
DB_PATH = '/opt/flaskapp/scores.db'
|
|
|
|
def get_db():
|
|
conn = sqlite3.connect(DB_PATH)
|
|
conn.row_factory = sqlite3.Row
|
|
return conn
|
|
|
|
def init_db():
|
|
with get_db() as conn:
|
|
conn.execute('''
|
|
CREATE TABLE IF NOT EXISTS scores (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL,
|
|
score INTEGER NOT NULL,
|
|
level INTEGER NOT NULL,
|
|
lines INTEGER NOT NULL,
|
|
domain TEXT,
|
|
ts DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
''')
|
|
conn.commit()
|
|
|
|
init_db()
|
|
|
|
@app.route("/", defaults={"path": ""})
|
|
@app.route("/<path:path>")
|
|
def blocked(path):
|
|
if path == "leaderboard":
|
|
return leaderboard()
|
|
domain = request.host or request.args.get("domain", "that site")
|
|
domain = domain.split(":")[0]
|
|
return render_template("blocked.html", domain=domain, reason="blocked by network policy")
|
|
|
|
@app.route("/score", methods=["POST"])
|
|
def submit_score():
|
|
data = request.get_json()
|
|
name = (data.get("name") or "ANONYMOUS")[:16].upper().strip()
|
|
score = int(data.get("score", 0))
|
|
level = int(data.get("level", 1))
|
|
lines = int(data.get("lines", 0))
|
|
domain = (data.get("domain") or "unknown")[:64]
|
|
with get_db() as conn:
|
|
conn.execute(
|
|
"INSERT INTO scores (name, score, level, lines, domain) VALUES (?,?,?,?,?)",
|
|
(name, score, level, lines, domain)
|
|
)
|
|
conn.commit()
|
|
return jsonify({"ok": True})
|
|
|
|
@app.route("/leaderboard")
|
|
def leaderboard():
|
|
with get_db() as conn:
|
|
rows = conn.execute(
|
|
"SELECT name, score, level, lines, domain, ts FROM scores ORDER BY score DESC LIMIT 20"
|
|
).fetchall()
|
|
return render_template("leaderboard.html", scores=rows)
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=80, debug=True)
|