Merge #5 websocket -> main
'websocket' Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
+9
-3
@@ -1,5 +1,5 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, session, flash
|
||||
from flask_login import login_user
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash
|
||||
from flask_login import login_user, current_user
|
||||
from app.db import get_db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
@@ -9,6 +9,9 @@ auth_bp = Blueprint("auth", __name__)
|
||||
|
||||
@auth_bp.route("/login", methods=["GET", "POST"])
|
||||
def login():
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("main.home"))
|
||||
|
||||
if request.method == "POST":
|
||||
username = request.form["username"]
|
||||
password = request.form["password"]
|
||||
@@ -32,6 +35,9 @@ def login():
|
||||
|
||||
@auth_bp.route("/register", methods=["GET", "POST"])
|
||||
def register():
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("main.home"))
|
||||
|
||||
if request.method == "POST":
|
||||
username = request.form.get("username")
|
||||
password = request.form.get("password")
|
||||
@@ -62,4 +68,4 @@ def register():
|
||||
flash("Account created! Please log in.")
|
||||
return redirect(url_for("auth.login"))
|
||||
|
||||
return render_template("register.html")
|
||||
return render_template("register.html")
|
||||
|
||||
+10
-2
@@ -1,4 +1,4 @@
|
||||
from flask import Blueprint, render_template
|
||||
from flask import Blueprint, render_template, redirect, url_for
|
||||
from flask_login import login_required, current_user
|
||||
|
||||
main_bp = Blueprint("main", __name__)
|
||||
@@ -14,6 +14,8 @@ main_bp = Blueprint("main", __name__)
|
||||
|
||||
@main_bp.route("/", methods=["GET", "POST"])
|
||||
def index():
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("main.home"))
|
||||
return render_template("index.html")
|
||||
|
||||
@main_bp.route("/home", methods=["GET", "POST"])
|
||||
@@ -26,4 +28,10 @@ def home():
|
||||
@main_bp.route("/play", methods=["GET"])
|
||||
@login_required
|
||||
def play():
|
||||
return render_template("play.html")
|
||||
return render_template("play.html")
|
||||
|
||||
|
||||
@main_bp.route("/friends", methods=["GET"])
|
||||
@login_required
|
||||
def friends():
|
||||
return render_template("friends.html")
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
from app import sIO
|
||||
|
||||
@sIO.on('auth')
|
||||
def handle_auth(msg):
|
||||
print(msg)
|
||||
@@ -0,0 +1,137 @@
|
||||
from typing import Any, Literal, NotRequired, Optional, TypedDict, get_args, get_origin
|
||||
|
||||
class CreateCodeGame(TypedDict): # Client
|
||||
play_as: Literal["b", "w", "r"]
|
||||
time_mode: str
|
||||
|
||||
class JoinCodeGame(TypedDict): # Client
|
||||
code: str
|
||||
|
||||
class CodeGameCreated(TypedDict): # Server
|
||||
code: str
|
||||
|
||||
class JoinCodeGameSuccess(TypedDict): # Server
|
||||
p1_name: str
|
||||
play_as: NotRequired[Literal["b", "w", "r"]]
|
||||
|
||||
class JoinCodeGameFailure(TypedDict): # Server
|
||||
reason: str
|
||||
|
||||
class P2Connected(TypedDict): # Server
|
||||
p2_name: str
|
||||
ready: bool
|
||||
|
||||
class UserReady(TypedDict): # Client or Server
|
||||
ready: bool
|
||||
|
||||
class GameStart(TypedDict): # Server
|
||||
play_as: Literal["b", "w", "r"]
|
||||
time_left_ms: int
|
||||
|
||||
class Move_Request(TypedDict): # Client
|
||||
from_square: str
|
||||
to_square: str
|
||||
promotion: NotRequired[str]
|
||||
|
||||
class Move_Accepted(TypedDict): # Server
|
||||
from_square: str
|
||||
to_square: str
|
||||
promotion: NotRequired[str]
|
||||
time_left_ms: int
|
||||
|
||||
class Move_Refused(TypedDict): # Server
|
||||
reason: str
|
||||
|
||||
class RequestResign(TypedDict): # Client
|
||||
accepted: NotRequired[bool] # missing = offer, true = accept, false = refuse
|
||||
|
||||
class RequestDraw(TypedDict): # Client
|
||||
accepted: NotRequired[bool] # missing = offer, true = accept, false = refuse
|
||||
|
||||
class GameEnd(TypedDict): # Server
|
||||
result: Literal["win", "loss", "draw"]
|
||||
reason: str
|
||||
|
||||
|
||||
#todo: implement later
|
||||
class _RematchRequest(TypedDict): # Client
|
||||
accepted: NotRequired[bool] # missing = offer, true = accept, false = refuse
|
||||
|
||||
|
||||
ClientEventSchema = {
|
||||
"create_code_game": CreateCodeGame,
|
||||
"join_code_game": JoinCodeGame,
|
||||
"user_ready": UserReady,
|
||||
"move_request": Move_Request,
|
||||
"request_resign": RequestResign,
|
||||
"request_draw": RequestDraw,
|
||||
}
|
||||
|
||||
|
||||
def _matches_annotation(value: Any, annotation: Any) -> bool:
|
||||
"""Minimal runtime checker for the annotations used in WS payloads."""
|
||||
origin = get_origin(annotation)
|
||||
args = get_args(annotation)
|
||||
|
||||
if annotation is Any:
|
||||
return True
|
||||
if origin is None:
|
||||
return isinstance(value, annotation)
|
||||
if origin is Literal:
|
||||
return value in args
|
||||
if origin is Optional:
|
||||
inner_type = args[0]
|
||||
return value is None or _matches_annotation(value, inner_type)
|
||||
if origin is list:
|
||||
return isinstance(value, list) and all(_matches_annotation(v, args[0]) for v in value)
|
||||
if origin is dict:
|
||||
key_type, val_type = args
|
||||
return isinstance(value, dict) and all(
|
||||
_matches_annotation(k, key_type) and _matches_annotation(v, val_type)
|
||||
for k, v in value.items()
|
||||
)
|
||||
if origin is tuple:
|
||||
if not isinstance(value, tuple):
|
||||
return False
|
||||
if len(args) == 2 and args[1] is Ellipsis:
|
||||
return all(_matches_annotation(v, args[0]) for v in value)
|
||||
return len(value) == len(args) and all(_matches_annotation(v, t) for v, t in zip(value, args))
|
||||
if origin is set:
|
||||
return isinstance(value, set) and all(_matches_annotation(v, args[0]) for v in value)
|
||||
|
||||
# covers Union and "|" types
|
||||
if args:
|
||||
return any(_matches_annotation(value, arg) for arg in args)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def validate_typed_dict_payload(payload: Any, schema: type[Any]) -> tuple[bool, str | None]:
|
||||
if not isinstance(payload, dict):
|
||||
return False, "payload must be an object"
|
||||
|
||||
required_keys = getattr(schema, "__required_keys__", set())
|
||||
optional_keys = getattr(schema, "__optional_keys__", set())
|
||||
allowed_keys = required_keys | optional_keys
|
||||
|
||||
missing = required_keys - payload.keys()
|
||||
if missing:
|
||||
return False, f"missing required keys: {', '.join(sorted(missing))}"
|
||||
|
||||
unexpected = payload.keys() - allowed_keys
|
||||
if unexpected:
|
||||
return False, f"unexpected keys: {', '.join(sorted(unexpected))}"
|
||||
|
||||
annotations = schema.__annotations__
|
||||
for key, expected_type in annotations.items():
|
||||
if key in payload and not _matches_annotation(payload[key], expected_type):
|
||||
return False, f"invalid type for '{key}'"
|
||||
|
||||
return True, None
|
||||
|
||||
|
||||
def validate_client_event(event: str, payload: Any) -> tuple[bool, str | None]:
|
||||
schema = ClientEventSchema.get(event)
|
||||
if schema is None:
|
||||
return False, f"unknown event '{event}'"
|
||||
return validate_typed_dict_payload(payload, schema)
|
||||
@@ -0,0 +1,219 @@
|
||||
:root {
|
||||
--bg: #f4f6f8;
|
||||
--surface: #ffffff;
|
||||
--surface-soft: #f8fafc;
|
||||
--border: #dde2e8;
|
||||
--text: #111827;
|
||||
--muted: #5f6b7a;
|
||||
--primary: #1f2937;
|
||||
--primary-strong: #0f172a;
|
||||
--success: #16a34a;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: "Manrope", "Segoe UI", sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.site-shell {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
height: 64px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 20px;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.brand {
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.topnav {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.topnav a {
|
||||
text-decoration: none;
|
||||
color: var(--muted);
|
||||
padding: 8px 12px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.topnav a:hover {
|
||||
color: var(--text);
|
||||
background: var(--surface-soft);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.topnav a.active {
|
||||
color: var(--text);
|
||||
background: var(--surface-soft);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.profile-pill {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-soft);
|
||||
padding: 7px 10px;
|
||||
font-size: 0.9rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.page-wrap {
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 20px 30px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 8px 0 10px;
|
||||
font-size: clamp(1.6rem, 3vw, 2.25rem);
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.cta-row {
|
||||
margin-top: 18px;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.btn {
|
||||
font: inherit;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 9px 14px;
|
||||
border-radius: 4px;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
border-color: var(--primary);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--primary-strong);
|
||||
border-color: var(--primary-strong);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.queue-layout {
|
||||
margin-top: 14px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.chip-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.chip {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-soft);
|
||||
color: var(--text);
|
||||
border-radius: 4px;
|
||||
padding: 7px 11px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chip.active,
|
||||
.chip:hover {
|
||||
border-color: #b7c0cb;
|
||||
background: #eef2f6;
|
||||
}
|
||||
|
||||
.friend-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.friend-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 0;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.friend-list li:first-child {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.panel-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.queue-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.topbar {
|
||||
height: auto;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
}
|
||||
|
||||
.topnav {
|
||||
width: 100%;
|
||||
order: 3;
|
||||
}
|
||||
|
||||
.topnav a {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.page-wrap {
|
||||
padding: 16px 14px 24px;
|
||||
}
|
||||
|
||||
.hero,
|
||||
.stack-head,
|
||||
.panel {
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createWSClient } from "./ws.js";
|
||||
import {
|
||||
handleP2Connected,
|
||||
handleGameStarted,
|
||||
handleCodeGameCreated,
|
||||
} from "./ws_handlers.js";
|
||||
|
||||
function main() {
|
||||
createWSClient({
|
||||
onGameStarted: handleGameStarted,
|
||||
onP2Connected: handleP2Connected,
|
||||
onGameCreated: handleCodeGameCreated,
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,35 @@
|
||||
// using socketio for websocket communication
|
||||
export function createWSClient(handlers = {}) {
|
||||
const socket = io();
|
||||
|
||||
socket.on("connect", () => {
|
||||
console.log("Connected to server");
|
||||
handlers.onConnect?.();
|
||||
});
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
console.log("Disconnected from server");
|
||||
handlers.onDisconnect?.();
|
||||
});
|
||||
|
||||
const serverEvents = {
|
||||
code_game_created: handlers.onGameCreated,
|
||||
code_game_joined: handlers.onGameJoined,
|
||||
game_started: handlers.onGameStarted,
|
||||
p2_connected: handlers.onP2Connected,
|
||||
user_move: handlers.onUserMove,
|
||||
move_accept: handlers.onMoveAccept,
|
||||
move_reject: handlers.onMoveReject,
|
||||
game_over: handlers.onGameOver,
|
||||
//todo: draw, resign, rematch
|
||||
};
|
||||
|
||||
let i = 0;
|
||||
for (const [event, handler] of Object.entries(serverEvents)) {
|
||||
if (handler) {
|
||||
socket.on(event, handler);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
console.log("registered " + i + " server event handlers");
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function handleGameStarted(data) {
|
||||
throw new Error("todo");
|
||||
}
|
||||
|
||||
export function handleCodeGameCreated(data) {
|
||||
throw new Error("todo");
|
||||
}
|
||||
|
||||
export function handleP2Connected(data) {
|
||||
throw new Error("todo");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Friends</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="site-shell">
|
||||
<header class="topbar">
|
||||
<a href="{{ url_for('main.home') }}" class="brand">Chess</a>
|
||||
<nav class="topnav">
|
||||
<a href="{{ url_for('main.home') }}">Home</a>
|
||||
<a href="{{ url_for('main.play') }}">Play</a>
|
||||
<a href="{{ url_for('main.friends') }}" class="active">Friends</a>
|
||||
</nav>
|
||||
<div class="profile-pill">{{ current_user.username }}</div>
|
||||
</header>
|
||||
|
||||
<h1>Friends</h1>
|
||||
|
||||
<section class="panel-grid">
|
||||
<article class="panel">
|
||||
<h2>Online now</h2>
|
||||
<ul class="friend-list">
|
||||
<li><span class="dot"></span>name1</li>
|
||||
<li><span class="dot"></span>friend2</li>
|
||||
<li><span class="dot"></span>bro has a lot of friends</li>
|
||||
</ul>
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<h2>Incoming invites</h2>
|
||||
<p>No pending invitations
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+29
-4
@@ -3,13 +3,38 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Home Page</title>
|
||||
<title>Home</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
href="{{ url_for('static', filename='style.css') }}"
|
||||
/>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>logged in</h1>
|
||||
<p>hi, {{ current_user.username }}!</p>
|
||||
<div class="site-shell">
|
||||
<header class="topbar">
|
||||
<a href="{{ url_for('main.home') }}" class="brand">Chess</a>
|
||||
<nav class="topnav">
|
||||
<a href="{{ url_for('main.home') }}" class="active">Home</a>
|
||||
<a href="{{ url_for('main.play') }}">Play</a>
|
||||
<a href="{{ url_for('main.friends') }}">Friends</a>
|
||||
</nav>
|
||||
<div class="profile-pill">{{ current_user.username }}</div>
|
||||
</header>
|
||||
|
||||
<main class="page-wrap">
|
||||
<h1>Welcome back, {{current_user.username}}</h1>
|
||||
<div class="cta-row">
|
||||
<a href="{{ url_for('main.play') }}" class="btn btn-primary"
|
||||
>Start a game</a
|
||||
>
|
||||
<a href="{{ url_for('main.friends') }}" class="btn btn-secondary"
|
||||
>Open friends</a
|
||||
>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Play</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='app.css') }}" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="site-shell">
|
||||
<header class="topbar">
|
||||
<a href="{{ url_for('main.home') }}" class="brand">Chess</a>
|
||||
<nav class="topnav">
|
||||
<a href="{{ url_for('main.home') }}">Home</a>
|
||||
<a href="{{ url_for('main.play') }}" class="active">Play</a>
|
||||
<a href="{{ url_for('main.friends') }}">Friends</a>
|
||||
</nav>
|
||||
<div class="profile-pill">{{ current_user.username }}</div>
|
||||
</header>
|
||||
|
||||
<!-- todo: make all of this via js and implement logic -->
|
||||
<main class="page-wrap">
|
||||
<section class="queue-layout">
|
||||
<article class="panel">
|
||||
<h2>Game settings</h2>
|
||||
<h4>Choose a time setup</h4>
|
||||
<div class="chip-row">
|
||||
<button class="chip">1 + 0</button>
|
||||
<button class="chip">3 + 2</button>
|
||||
<button class="chip active">10 + 0</button>
|
||||
<button class="chip">15 + 10</button>
|
||||
</div>
|
||||
<h4>You play as</h4>
|
||||
<div class="chip-row">
|
||||
<button class="chip">white</button>
|
||||
<button class="chip">black</button>
|
||||
<button class="chip active">random</button>
|
||||
</div>
|
||||
<div class="cta-row">
|
||||
<!-- <button class="btn btn-primary" type="button">Start game</button> -->
|
||||
<button class="btn btn-secondary" type="button">
|
||||
Create game code
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user