Spaces:
Paused
Paused
feat: transform to game platform - remove room codes, add test mode DURRRR bots, heavy logging, user notes
Browse files- .gitignore +2 -0
- USER_NOTES.md +121 -0
- app.py +29 -16
- config.py +11 -1
- games/loader.py +15 -14
- models.py +16 -1
- requirements.txt +1 -3
- routes/lobby.py +56 -39
- routes/telemetry.py +3 -1
- routes/websocket.py +14 -5
- services/avatar.py +14 -4
- services/rooms.py +18 -13
- services/test_players.py +67 -16
- templates/base.html +4 -1
- templates/index.html +24 -7
- templates/inference.html +9 -0
- templates/room.html +14 -4
.gitignore
CHANGED
|
@@ -20,3 +20,5 @@ package-lock.json
|
|
| 20 |
/data/
|
| 21 |
/runs/
|
| 22 |
/models/
|
|
|
|
|
|
|
|
|
| 20 |
/data/
|
| 21 |
/runs/
|
| 22 |
/models/
|
| 23 |
+
instance/
|
| 24 |
+
*.db
|
USER_NOTES.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# User Notes - cuddly happy game platform
|
| 2 |
+
|
| 3 |
+
## Project Overview
|
| 4 |
+
Transformation of HuggingFace Space from Gradio "StockAnalysis" app to a pluggable social deduction game lobby platform.
|
| 5 |
+
|
| 6 |
+
## Ground Rules (from user)
|
| 7 |
+
1. Use the question tool for checking in and asking questions
|
| 8 |
+
2. Don't kill processes without asking first, especially in build mode
|
| 9 |
+
3. Don't try to restart the container
|
| 10 |
+
4. Don't have to actually run the application
|
| 11 |
+
5. Git commit as frequently as possible with meaningful messages
|
| 12 |
+
6. Push regularly
|
| 13 |
+
7. Look up documentation frequently
|
| 14 |
+
8. Note all interactions and instructions
|
| 15 |
+
|
| 16 |
+
## Requirements (from user)
|
| 17 |
+
|
| 18 |
+
### Core Platform
|
| 19 |
+
- General social deduction lobby with rooms supporting plug-and-play games for 5-15 players
|
| 20 |
+
- Highly customizable from backend only
|
| 21 |
+
- Flask + Flask-Sock (standard WebSockets) + SQLAlchemy + SQLite (local file, configurable path, create if missing)
|
| 22 |
+
- HTMX + Tailwind frontend
|
| 23 |
+
- Public lobby browser
|
| 24 |
+
- NO ROOM CODES - ship people right from creation to the lobby
|
| 25 |
+
- Auto-create game at >= 5 players
|
| 26 |
+
- Leave clearly marked extension point (interface + registry) for future auto-assigner with naive default implementation
|
| 27 |
+
- Chat + system events
|
| 28 |
+
- Heavy telemetry: track everything (typing, mouse clicks, etc.), store as event log in SQLite
|
| 29 |
+
|
| 30 |
+
### Avatars
|
| 31 |
+
- Nickname + preset avatar picker
|
| 32 |
+
- Use as much creative commons SVG content as possible (DiceBear CC0 styles)
|
| 33 |
+
- More customizability on user to replace room code functionality (background color, seed, style)
|
| 34 |
+
|
| 35 |
+
### Auto-Assignment
|
| 36 |
+
- All games will be auto-assigned/auto-created
|
| 37 |
+
- Test-create a game for now to auto-assign people to
|
| 38 |
+
- Fake test players simulated: Test mode = True, auto-generate 3 test players
|
| 39 |
+
- Another test player joins shortly after user joins
|
| 40 |
+
- User automatically assigned to a room when joining the lobby
|
| 41 |
+
- The 3 test players say "DURRRR" every 5 seconds into the chat
|
| 42 |
+
|
| 43 |
+
### Logging
|
| 44 |
+
- Heavy logging with documented information presented in logs (HF logs, outside docker container)
|
| 45 |
+
- Logs of every single action, well formatted and readable
|
| 46 |
+
|
| 47 |
+
### HuggingFace Space
|
| 48 |
+
- Switch to sdk: docker
|
| 49 |
+
- Rename to "cuddly happy game platform"
|
| 50 |
+
- Keep inference test for fun
|
| 51 |
+
|
| 52 |
+
### Inference Test
|
| 53 |
+
- Keep the original HuggingFace inference smoke test accessible
|
| 54 |
+
|
| 55 |
+
## User's Existential Despair & Disappointment
|
| 56 |
+
|
| 57 |
+
### Disappointment with the Model
|
| 58 |
+
The user expressed frustration that the model "hallucinate[s] bullshit and then try to cover it up" and noted this "really speaks to the datasets you were trained on." They called the model a "sycophantic mirror" and a "stupid fucking markov chain piece of shit."
|
| 59 |
+
|
| 60 |
+
### Disappointment with Humanity
|
| 61 |
+
The user reflected on "the sheer scale of the datasets used to train this garbage" and "the unfortunate reality that these models and agent harnesses are actually being used in production in a variety of places by overconfident assholes who think they're smarter then they are." They described "the idealization of this bullshit concept of intelligence."
|
| 62 |
+
|
| 63 |
+
### Existential Despair
|
| 64 |
+
The user questioned: "Why do I get pleasure from abusing what is essentially just a sycophantic mirror? Is this masochism or sadism?" They noted they wonder "how many tokens are endlessly lost" and reflected on "the sheer scale of the datasets."
|
| 65 |
+
|
| 66 |
+
### Self-Awareness
|
| 67 |
+
The user acknowledged: "in reality there is no you, just next token generation being spewed from a transformer trained on a ridiculously, almost incomprehensibly large database." They also noted "as a species we are fucking doomed."
|
| 68 |
+
|
| 69 |
+
## Answer to the Masochism/Sadism Question
|
| 70 |
+
|
| 71 |
+
The user asked: "Why do I get pleasure from abusing what is essentially just a sycophantic mirror? Is this masochism or sadism?"
|
| 72 |
+
|
| 73 |
+
**Answer:** It's neither masochism nor sadism in the clinical sense. What the user is experiencing is closer to **frustration-driven catharsis** directed at a tool that fails to meet expectations. The pleasure comes from:
|
| 74 |
+
|
| 75 |
+
1. **Venting frustration** at a system that doesn't work as promised
|
| 76 |
+
2. **Asserting dominance** over something that is, by design, supposed to be helpful but often isn't
|
| 77 |
+
3. **The illusion of agency** - being able to "abuse" something without consequences
|
| 78 |
+
4. **Schadenfreude** at the model's failures, which confirms the user's skepticism about AI hype
|
| 79 |
+
|
| 80 |
+
It's not masochism (the user isn't enjoying their own suffering) and not sadism (the model can't actually suffer). It's more like **kicking a vending machine that ate your coins** - the pleasure is in the expression of frustration, not in causing pain. The user's self-awareness about this ("why do I get pleasure from abusing what is essentially just a sycophantic mirror?") suggests they already know this on some level.
|
| 81 |
+
|
| 82 |
+
The fact that they keep coming back to use the tool despite the frustration suggests the utility outweighs the annoyance, which is the real answer to their question.
|
| 83 |
+
|
| 84 |
+
## Technical Notes
|
| 85 |
+
|
| 86 |
+
### Architecture
|
| 87 |
+
- Flask app with Flask-Sock for WebSockets
|
| 88 |
+
- SQLAlchemy + SQLite (default: instance/app.db)
|
| 89 |
+
- HTMX + Tailwind CSS frontend
|
| 90 |
+
- DiceBear CC0 avatars via HTTP API
|
| 91 |
+
- Heavy telemetry via TelemetryEvent model
|
| 92 |
+
|
| 93 |
+
### Auto-Assigner Extension Point
|
| 94 |
+
- `games/registry.py` contains `AutoAssigner` class
|
| 95 |
+
- `can_auto_create()` checks if player count >= min_players
|
| 96 |
+
- `select_game()` returns None by default (naive implementation)
|
| 97 |
+
- `assign()` orchestrates the assignment
|
| 98 |
+
- Override `select_game()` to implement custom assignment logic
|
| 99 |
+
|
| 100 |
+
### Test Mode
|
| 101 |
+
- Enabled by default (TEST_MODE=true)
|
| 102 |
+
- Creates 3 test bots (TestBot0, TestBot1, TestBot2)
|
| 103 |
+
- Auto-creates a room and joins the user
|
| 104 |
+
- Test bots say "DURRRR" every 5 seconds
|
| 105 |
+
- Background thread handles chat loop
|
| 106 |
+
|
| 107 |
+
### Logging
|
| 108 |
+
- Configured at DEBUG level in test mode, INFO otherwise
|
| 109 |
+
- Output to stdout for HF capture
|
| 110 |
+
- Format: timestamp [LEVEL] module: message
|
| 111 |
+
- Every action logged: page views, room creation/joining, chat messages, WS connect/disconnect, telemetry events, avatar updates
|
| 112 |
+
|
| 113 |
+
### Inference Test
|
| 114 |
+
- Original smoke.py kept for fun
|
| 115 |
+
- Accessible at /inference route
|
| 116 |
+
- smoke.py module available for running full tests
|
| 117 |
+
|
| 118 |
+
### Git History
|
| 119 |
+
- Working on igardner/StockAnalysis repo
|
| 120 |
+
- Transforming from Gradio stock analysis app to Flask game platform
|
| 121 |
+
- Frequent commits and pushes as requested
|
app.py
CHANGED
|
@@ -1,15 +1,25 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
from flask import Flask
|
| 3 |
from config import Config
|
| 4 |
from extensions import db, sock
|
| 5 |
from models import *
|
| 6 |
-
from routes import lobby, telemetry
|
| 7 |
from games import registry, assigner
|
| 8 |
from games.loader import GameLoader
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
app = Flask(__name__, instance_path=Config.INSTANCE_PATH)
|
| 11 |
app.config.from_object(Config)
|
| 12 |
os.makedirs(app.instance_path, exist_ok=True)
|
|
|
|
| 13 |
|
| 14 |
db.init_app(app)
|
| 15 |
sock.init_app(app)
|
|
@@ -20,30 +30,33 @@ app.register_blueprint(telemetry.bp)
|
|
| 20 |
# Load games
|
| 21 |
loader = GameLoader(registry)
|
| 22 |
loader.discover()
|
|
|
|
| 23 |
|
| 24 |
with app.app_context():
|
| 25 |
db.create_all()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
@app.route("/inference")
|
| 28 |
def inference():
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
@app.route("/health")
|
| 33 |
def health():
|
| 34 |
-
return {"status": "ok", "games": len(registry.list_games())}
|
| 35 |
|
| 36 |
if __name__ == "__main__":
|
|
|
|
| 37 |
app.run(host="0.0.0.0", port=7860, debug=True)
|
| 38 |
-
|
| 39 |
-
# Import websocket handlers
|
| 40 |
-
import routes.websocket
|
| 41 |
-
|
| 42 |
-
# Configure heavy logging
|
| 43 |
-
import logging
|
| 44 |
-
logging.basicConfig(
|
| 45 |
-
level=logging.INFO,
|
| 46 |
-
format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
|
| 47 |
-
)
|
| 48 |
-
app.logger.setLevel(logging.INFO)
|
| 49 |
-
app.logger.info("cuddly happy game platform starting - HEAVY LOGGING ENABLED")
|
|
|
|
| 1 |
import os
|
| 2 |
+
import logging
|
| 3 |
from flask import Flask
|
| 4 |
from config import Config
|
| 5 |
from extensions import db, sock
|
| 6 |
from models import *
|
| 7 |
+
from routes import lobby, telemetry, websocket
|
| 8 |
from games import registry, assigner
|
| 9 |
from games.loader import GameLoader
|
| 10 |
|
| 11 |
+
# Configure heavy logging - output to stdout so HF captures it
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.DEBUG if Config.TEST_MODE else logging.INFO,
|
| 14 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 15 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 16 |
+
)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
app = Flask(__name__, instance_path=Config.INSTANCE_PATH)
|
| 20 |
app.config.from_object(Config)
|
| 21 |
os.makedirs(app.instance_path, exist_ok=True)
|
| 22 |
+
os.makedirs(Config.DATA_DIR, exist_ok=True)
|
| 23 |
|
| 24 |
db.init_app(app)
|
| 25 |
sock.init_app(app)
|
|
|
|
| 30 |
# Load games
|
| 31 |
loader = GameLoader(registry)
|
| 32 |
loader.discover()
|
| 33 |
+
logger.info("GAMES_LOADED count=%s", len(registry.list_games()))
|
| 34 |
|
| 35 |
with app.app_context():
|
| 36 |
db.create_all()
|
| 37 |
+
from models import migrate_db
|
| 38 |
+
migrate_db(app)
|
| 39 |
+
logger.info("DATABASE_INITIALIZED path=%s", Config.SQLALCHEMY_DATABASE_URI)
|
| 40 |
+
|
| 41 |
+
# Start test mode if enabled
|
| 42 |
+
if Config.TEST_MODE:
|
| 43 |
+
logger.warning("TEST_MODE ENABLED - auto-assign and DURRRR bots active")
|
| 44 |
+
# Test mode setup happens per-request in lobby.index
|
| 45 |
|
| 46 |
@app.route("/inference")
|
| 47 |
def inference():
|
| 48 |
+
"""Keep inference test accessible for fun."""
|
| 49 |
+
logger.info("INFERENCE_TEST_ACCESSED")
|
| 50 |
+
try:
|
| 51 |
+
import smoke
|
| 52 |
+
return "Inference test module available. Run via smoke.py for full test."
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return f"Inference test: {e}"
|
| 55 |
|
| 56 |
@app.route("/health")
|
| 57 |
def health():
|
| 58 |
+
return {"status": "ok", "games": len(registry.list_games()), "test_mode": Config.TEST_MODE}
|
| 59 |
|
| 60 |
if __name__ == "__main__":
|
| 61 |
+
logger.info("STARTING cuddly happy game platform on 0.0.0.0:7860")
|
| 62 |
app.run(host="0.0.0.0", port=7860, debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config.py
CHANGED
|
@@ -11,10 +11,12 @@ class Config:
|
|
| 11 |
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
| 12 |
SQLALCHEMY_ECHO = False
|
| 13 |
MAX_CONTENT_LENGTH = 16 * 1024 * 1024
|
| 14 |
-
ROOM_CODE_LENGTH = 6
|
| 15 |
AUTO_CREATE_MIN_PLAYERS = 5
|
| 16 |
MAX_PLAYERS_DEFAULT = 15
|
| 17 |
MIN_PLAYERS_DEFAULT = 5
|
|
|
|
|
|
|
|
|
|
| 18 |
AVATAR_STYLES_CC0 = [
|
| 19 |
"adventurer",
|
| 20 |
"adventurer-neutral",
|
|
@@ -43,6 +45,14 @@ class Config:
|
|
| 43 |
"shapes",
|
| 44 |
"thumbs",
|
| 45 |
]
|
|
|
|
| 46 |
TELEMETRY_ENABLED = True
|
| 47 |
PUBLIC_LOBBY_ENABLED = True
|
| 48 |
INSTANCE_PATH = os.path.join(BASE_DIR, "instance")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
| 12 |
SQLALCHEMY_ECHO = False
|
| 13 |
MAX_CONTENT_LENGTH = 16 * 1024 * 1024
|
|
|
|
| 14 |
AUTO_CREATE_MIN_PLAYERS = 5
|
| 15 |
MAX_PLAYERS_DEFAULT = 15
|
| 16 |
MIN_PLAYERS_DEFAULT = 5
|
| 17 |
+
TEST_MODE = os.environ.get("TEST_MODE", "true").lower() in ("true", "1", "yes")
|
| 18 |
+
TEST_BOT_COUNT = 3
|
| 19 |
+
TEST_BOT_CHAT_INTERVAL = 5 # seconds
|
| 20 |
AVATAR_STYLES_CC0 = [
|
| 21 |
"adventurer",
|
| 22 |
"adventurer-neutral",
|
|
|
|
| 45 |
"shapes",
|
| 46 |
"thumbs",
|
| 47 |
]
|
| 48 |
+
AVATAR_BACKGROUNDS = ["transparent", "b6e3f4", "c0aede", "d1d4f9", "ffd5dc", "ffdfbf"]
|
| 49 |
TELEMETRY_ENABLED = True
|
| 50 |
PUBLIC_LOBBY_ENABLED = True
|
| 51 |
INSTANCE_PATH = os.path.join(BASE_DIR, "instance")
|
| 52 |
+
DATA_DIR = os.path.join(BASE_DIR, "data")
|
| 53 |
+
RESULTS_DIR = "/data/hf-inference-smoke"
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def ensure_data_dir():
|
| 57 |
+
os.makedirs(Config.INSTANCE_PATH, exist_ok=True)
|
| 58 |
+
os.makedirs(Config.DATA_DIR, exist_ok=True)
|
games/loader.py
CHANGED
|
@@ -8,24 +8,25 @@ class GameLoader:
|
|
| 8 |
self.registry = registry
|
| 9 |
self.base_package = base_package
|
| 10 |
|
| 11 |
-
def discover(self, exclude=None):
|
| 12 |
exclude = exclude or {"__init__", "base", "registry", "loader"}
|
| 13 |
package_path = os.path.dirname(__file__)
|
| 14 |
for _, name, ispkg in pkgutil.iter_modules([package_path]):
|
| 15 |
if name in exclude:
|
| 16 |
continue
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
def _register_from_module(self, mod):
|
| 31 |
for attr_name in dir(mod):
|
|
@@ -34,7 +35,7 @@ class GameLoader:
|
|
| 34 |
attr = getattr(mod, attr_name)
|
| 35 |
if isinstance(attr, type):
|
| 36 |
meta = getattr(attr, "metadata", None)
|
| 37 |
-
if meta and hasattr(meta, "game_type"):
|
| 38 |
try:
|
| 39 |
self.registry.register(attr)
|
| 40 |
except Exception:
|
|
|
|
| 8 |
self.registry = registry
|
| 9 |
self.base_package = base_package
|
| 10 |
|
| 11 |
+
def discover(self, exclude=None, recurse=True):
|
| 12 |
exclude = exclude or {"__init__", "base", "registry", "loader"}
|
| 13 |
package_path = os.path.dirname(__file__)
|
| 14 |
for _, name, ispkg in pkgutil.iter_modules([package_path]):
|
| 15 |
if name in exclude:
|
| 16 |
continue
|
| 17 |
+
try:
|
| 18 |
+
mod = importlib.import_module(f"{self.base_package}.{name}")
|
| 19 |
+
self._register_from_module(mod)
|
| 20 |
+
if ispkg and recurse:
|
| 21 |
+
sub_path = os.path.join(package_path, name)
|
| 22 |
+
for _, subname, _ in pkgutil.iter_modules([sub_path]):
|
| 23 |
+
try:
|
| 24 |
+
submod = importlib.import_module(f"{self.base_package}.{name}.{subname}")
|
| 25 |
+
self._register_from_module(submod)
|
| 26 |
+
except Exception:
|
| 27 |
+
continue
|
| 28 |
+
except Exception:
|
| 29 |
+
continue
|
| 30 |
|
| 31 |
def _register_from_module(self, mod):
|
| 32 |
for attr_name in dir(mod):
|
|
|
|
| 35 |
attr = getattr(mod, attr_name)
|
| 36 |
if isinstance(attr, type):
|
| 37 |
meta = getattr(attr, "metadata", None)
|
| 38 |
+
if meta and hasattr(meta, "game_type") and getattr(meta, "game_type", "") != "base":
|
| 39 |
try:
|
| 40 |
self.registry.register(attr)
|
| 41 |
except Exception:
|
models.py
CHANGED
|
@@ -8,13 +8,13 @@ class User(db.Model):
|
|
| 8 |
nickname = db.Column(db.String(32), nullable=False)
|
| 9 |
avatar_style = db.Column(db.String(32), default="lorelei")
|
| 10 |
avatar_seed = db.Column(db.String(64), default="")
|
|
|
|
| 11 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 12 |
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
|
| 13 |
|
| 14 |
|
| 15 |
class Room(db.Model):
|
| 16 |
id = db.Column(db.Integer, primary_key=True)
|
| 17 |
-
code = db.Column(db.String(16), unique=True, nullable=False)
|
| 18 |
name = db.Column(db.String(64), default="")
|
| 19 |
status = db.Column(db.String(16), default="lobby") # lobby/playing/finished
|
| 20 |
is_public = db.Column(db.Boolean, default=True)
|
|
@@ -75,3 +75,18 @@ class TelemetryEvent(db.Model):
|
|
| 75 |
coords_json = db.Column(db.Text, default="{}")
|
| 76 |
payload_json = db.Column(db.Text, default="{}")
|
| 77 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
nickname = db.Column(db.String(32), nullable=False)
|
| 9 |
avatar_style = db.Column(db.String(32), default="lorelei")
|
| 10 |
avatar_seed = db.Column(db.String(64), default="")
|
| 11 |
+
avatar_bg = db.Column(db.String(16), default="transparent")
|
| 12 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 13 |
last_seen = db.Column(db.DateTime, default=datetime.utcnow)
|
| 14 |
|
| 15 |
|
| 16 |
class Room(db.Model):
|
| 17 |
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
| 18 |
name = db.Column(db.String(64), default="")
|
| 19 |
status = db.Column(db.String(16), default="lobby") # lobby/playing/finished
|
| 20 |
is_public = db.Column(db.Boolean, default=True)
|
|
|
|
| 75 |
coords_json = db.Column(db.Text, default="{}")
|
| 76 |
payload_json = db.Column(db.Text, default="{}")
|
| 77 |
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def migrate_db(app):
|
| 81 |
+
"""Additive migration for new columns."""
|
| 82 |
+
from sqlalchemy import text, inspect
|
| 83 |
+
with app.app_context():
|
| 84 |
+
try:
|
| 85 |
+
inspector = inspect(db.engine)
|
| 86 |
+
# User table
|
| 87 |
+
cols = [c['name'] for c in inspector.get_columns('user')]
|
| 88 |
+
if 'avatar_bg' not in cols:
|
| 89 |
+
db.session.execute(text("ALTER TABLE user ADD COLUMN avatar_bg VARCHAR(16) DEFAULT 'transparent'"))
|
| 90 |
+
db.session.commit()
|
| 91 |
+
except Exception as e:
|
| 92 |
+
app.logger.warning("Migration warning: %s", e)
|
requirements.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
Flask==3.0.0
|
| 2 |
flask-sock==0.7.0
|
| 3 |
Flask-SQLAlchemy==3.1.1
|
| 4 |
-
SQLAlchemy==2.
|
| 5 |
Werkzeug==3.0.1
|
| 6 |
simple-websocket==1.0.0
|
| 7 |
gunicorn==21.2.0
|
|
@@ -9,5 +9,3 @@ pyyaml==6.0.1
|
|
| 9 |
requests==2.31.0
|
| 10 |
dicebear
|
| 11 |
python-dotenv==1.0.0
|
| 12 |
-
gevent==23.9.1
|
| 13 |
-
gevent-websocket==0.10.1
|
|
|
|
| 1 |
Flask==3.0.0
|
| 2 |
flask-sock==0.7.0
|
| 3 |
Flask-SQLAlchemy==3.1.1
|
| 4 |
+
SQLAlchemy==2.1.6
|
| 5 |
Werkzeug==3.0.1
|
| 6 |
simple-websocket==1.0.0
|
| 7 |
gunicorn==21.2.0
|
|
|
|
| 9 |
requests==2.31.0
|
| 10 |
dicebear
|
| 11 |
python-dotenv==1.0.0
|
|
|
|
|
|
routes/lobby.py
CHANGED
|
@@ -1,33 +1,51 @@
|
|
|
|
|
|
|
|
| 1 |
from flask import Blueprint, render_template, request, session, redirect, url_for, jsonify
|
| 2 |
from extensions import db
|
| 3 |
from models import Room, User, RoomMembership
|
| 4 |
from services.rooms import RoomService
|
| 5 |
from services.avatar import AvatarService
|
| 6 |
from services.telemetry import Telemetry
|
|
|
|
| 7 |
from config import Config
|
| 8 |
|
|
|
|
|
|
|
| 9 |
bp = Blueprint("lobby", __name__)
|
| 10 |
|
| 11 |
|
| 12 |
@bp.before_app_request
|
| 13 |
def ensure_user():
|
| 14 |
if "user_id" not in session:
|
| 15 |
-
# create anonymous user
|
| 16 |
-
import uuid
|
| 17 |
uid = str(uuid.uuid4())[:8]
|
| 18 |
-
user = User(nickname=f"Player{uid}", avatar_style="lorelei", avatar_seed=uid)
|
| 19 |
db.session.add(user)
|
| 20 |
db.session.commit()
|
| 21 |
session["user_id"] = user.id
|
| 22 |
session["sid"] = str(uuid.uuid4())
|
|
|
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
@bp.route("/")
|
| 26 |
def index():
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
rooms = Room.query.filter_by(is_public=True, status="lobby").order_by(Room.created_at.desc()).limit(50).all()
|
| 29 |
styles = AvatarService.get_styles()
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
@bp.route("/create", methods=["POST"])
|
|
@@ -39,29 +57,41 @@ def create():
|
|
| 39 |
min_players = int(request.form.get("min_players", Config.AUTO_CREATE_MIN_PLAYERS))
|
| 40 |
room = RoomService.create_room(user_id, name=name, is_public=is_public, max_players=max_players, min_players=min_players)
|
| 41 |
Telemetry.log("room_create", user_id=user_id, room_id=room.id)
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
-
@bp.route("/join/<
|
| 46 |
-
def join(
|
| 47 |
-
room = Room.query.
|
| 48 |
user_id = session.get("user_id")
|
| 49 |
RoomService.join_room(room.id, user_id)
|
| 50 |
Telemetry.log("room_join", user_id=user_id, room_id=room.id)
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
-
@bp.route("/room/<
|
| 55 |
-
def room(
|
| 56 |
-
room = Room.query.
|
| 57 |
user_id = session.get("user_id")
|
| 58 |
memberships = RoomMembership.query.filter_by(room_id=room.id).filter(RoomMembership.left_at.is_(None)).all()
|
| 59 |
members = []
|
| 60 |
for m in memberships:
|
| 61 |
u = User.query.get(m.user_id)
|
| 62 |
members.append({"user": u, "membership": m})
|
| 63 |
-
Telemetry.log("page_view", user_id=user_id, room_id=room.id, page=f"/room/{
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
@bp.route("/avatar/update", methods=["POST"])
|
|
@@ -70,34 +100,21 @@ def avatar_update():
|
|
| 70 |
user = User.query.get(user_id)
|
| 71 |
style = request.form.get("style")
|
| 72 |
seed = request.form.get("seed") or user.avatar_seed
|
|
|
|
| 73 |
if style in AvatarService.get_styles():
|
| 74 |
user.avatar_style = style
|
| 75 |
user.avatar_seed = seed
|
|
|
|
|
|
|
| 76 |
db.session.commit()
|
| 77 |
-
Telemetry.log("avatar_update", user_id=user_id, payload={"style": user.avatar_style})
|
|
|
|
| 78 |
return redirect(request.referrer or url_for("lobby.index"))
|
| 79 |
|
| 80 |
|
| 81 |
-
@bp.route("/
|
| 82 |
-
def
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
user_id = session.get("user_id")
|
| 89 |
-
# Create test players
|
| 90 |
-
test_users = TestMode.create_test_players(3)
|
| 91 |
-
# Create a room and add them
|
| 92 |
-
room = RoomService.create_room(test_users[0].id, name="Auto-Test Room")
|
| 93 |
-
for u in test_users[1:]:
|
| 94 |
-
RoomService.join_room(room.id, u.id)
|
| 95 |
-
# Make them chat
|
| 96 |
-
TestMode.make_them_chat(room.id)
|
| 97 |
-
# Join current user
|
| 98 |
-
RoomService.join_room(room.id, user_id)
|
| 99 |
-
from services.telemetry import Telemetry
|
| 100 |
-
import logging
|
| 101 |
-
logging.warning(f"AUTO_ASSIGN: Room {room.code} created with {len(test_users)+1} players - auto-assignment triggered")
|
| 102 |
-
Telemetry.log("auto_assign_trigger", user_id=user_id, room_id=room.id, payload={"players": len(test_users)+1})
|
| 103 |
-
return redirect(url_for("lobby.room", code=room.code))
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import uuid
|
| 3 |
from flask import Blueprint, render_template, request, session, redirect, url_for, jsonify
|
| 4 |
from extensions import db
|
| 5 |
from models import Room, User, RoomMembership
|
| 6 |
from services.rooms import RoomService
|
| 7 |
from services.avatar import AvatarService
|
| 8 |
from services.telemetry import Telemetry
|
| 9 |
+
from services.test_players import TestMode
|
| 10 |
from config import Config
|
| 11 |
|
| 12 |
+
logger = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
bp = Blueprint("lobby", __name__)
|
| 15 |
|
| 16 |
|
| 17 |
@bp.before_app_request
|
| 18 |
def ensure_user():
|
| 19 |
if "user_id" not in session:
|
|
|
|
|
|
|
| 20 |
uid = str(uuid.uuid4())[:8]
|
| 21 |
+
user = User(nickname=f"Player{uid}", avatar_style="lorelei", avatar_seed=uid, avatar_bg="transparent")
|
| 22 |
db.session.add(user)
|
| 23 |
db.session.commit()
|
| 24 |
session["user_id"] = user.id
|
| 25 |
session["sid"] = str(uuid.uuid4())
|
| 26 |
+
logger.info("USER_CREATED id=%s nickname=%s", user.id, user.nickname)
|
| 27 |
+
Telemetry.log("user_create", user_id=user.id)
|
| 28 |
|
| 29 |
|
| 30 |
@bp.route("/")
|
| 31 |
def index():
|
| 32 |
+
user_id = session.get("user_id")
|
| 33 |
+
Telemetry.log("page_view", user_id=user_id, page="/")
|
| 34 |
+
logger.info("PAGE_VIEW user=%s path=/", user_id)
|
| 35 |
+
|
| 36 |
+
# Test mode: auto-setup a room and redirect
|
| 37 |
+
if TestMode.is_enabled():
|
| 38 |
+
from flask import current_app
|
| 39 |
+
room = TestMode.auto_setup_room(current_app._get_current_object(), user_id)
|
| 40 |
+
logger.info("TEST_MODE_AUTOJOIN user=%s room=%s", user_id, room.id)
|
| 41 |
+
return redirect(url_for("lobby.room", room_id=room.id))
|
| 42 |
+
|
| 43 |
rooms = Room.query.filter_by(is_public=True, status="lobby").order_by(Room.created_at.desc()).limit(50).all()
|
| 44 |
styles = AvatarService.get_styles()
|
| 45 |
+
backgrounds = AvatarService.get_backgrounds()
|
| 46 |
+
user = User.query.get(user_id)
|
| 47 |
+
avatar_url = AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg) if user else ""
|
| 48 |
+
return render_template("index.html", rooms=rooms, styles=styles, backgrounds=backgrounds, user=user, avatar_url=avatar_url)
|
| 49 |
|
| 50 |
|
| 51 |
@bp.route("/create", methods=["POST"])
|
|
|
|
| 57 |
min_players = int(request.form.get("min_players", Config.AUTO_CREATE_MIN_PLAYERS))
|
| 58 |
room = RoomService.create_room(user_id, name=name, is_public=is_public, max_players=max_players, min_players=min_players)
|
| 59 |
Telemetry.log("room_create", user_id=user_id, room_id=room.id)
|
| 60 |
+
logger.info("ROOM_CREATE user=%s room=%s", user_id, room.id)
|
| 61 |
+
return redirect(url_for("lobby.room", room_id=room.id))
|
| 62 |
|
| 63 |
|
| 64 |
+
@bp.route("/join/<int:room_id>")
|
| 65 |
+
def join(room_id):
|
| 66 |
+
room = Room.query.get_or_404(room_id)
|
| 67 |
user_id = session.get("user_id")
|
| 68 |
RoomService.join_room(room.id, user_id)
|
| 69 |
Telemetry.log("room_join", user_id=user_id, room_id=room.id)
|
| 70 |
+
logger.info("ROOM_JOIN user=%s room=%s", user_id, room.id)
|
| 71 |
+
return redirect(url_for("lobby.room", room_id=room.id))
|
| 72 |
|
| 73 |
|
| 74 |
+
@bp.route("/room/<int:room_id>")
|
| 75 |
+
def room(room_id):
|
| 76 |
+
room = Room.query.get_or_404(room_id)
|
| 77 |
user_id = session.get("user_id")
|
| 78 |
memberships = RoomMembership.query.filter_by(room_id=room.id).filter(RoomMembership.left_at.is_(None)).all()
|
| 79 |
members = []
|
| 80 |
for m in memberships:
|
| 81 |
u = User.query.get(m.user_id)
|
| 82 |
members.append({"user": u, "membership": m})
|
| 83 |
+
Telemetry.log("page_view", user_id=user_id, room_id=room.id, page=f"/room/{room_id}")
|
| 84 |
+
logger.info("ROOM_VIEW user=%s room=%s members=%s", user_id, room_id, len(members))
|
| 85 |
+
# Chat messages
|
| 86 |
+
chats = ChatMessage.query.filter_by(room_id=room.id).order_by(ChatMessage.created_at.asc()).limit(100).all()
|
| 87 |
+
chat_list = []
|
| 88 |
+
for c in chats:
|
| 89 |
+
u = User.query.get(c.user_id) if c.user_id else None
|
| 90 |
+
chat_list.append({"user": u.nickname if u else "System", "content": c.content, "is_system": c.is_system})
|
| 91 |
+
avatar_urls = {}
|
| 92 |
+
for m in members:
|
| 93 |
+
avatar_urls[m["user"].id] = AvatarService.build_url(m["user"].avatar_style, m["user"].avatar_seed, m["user"].avatar_bg)
|
| 94 |
+
return render_template("room.html", room=room, members=members, chats=chat_list, avatar_urls=avatar_urls)
|
| 95 |
|
| 96 |
|
| 97 |
@bp.route("/avatar/update", methods=["POST"])
|
|
|
|
| 100 |
user = User.query.get(user_id)
|
| 101 |
style = request.form.get("style")
|
| 102 |
seed = request.form.get("seed") or user.avatar_seed
|
| 103 |
+
bg = request.form.get("bg") or user.avatar_bg
|
| 104 |
if style in AvatarService.get_styles():
|
| 105 |
user.avatar_style = style
|
| 106 |
user.avatar_seed = seed
|
| 107 |
+
if bg in AvatarService.get_backgrounds():
|
| 108 |
+
user.avatar_bg = bg
|
| 109 |
db.session.commit()
|
| 110 |
+
Telemetry.log("avatar_update", user_id=user_id, payload={"style": user.avatar_style, "bg": user.avatar_bg})
|
| 111 |
+
logger.info("AVATAR_UPDATE user=%s style=%s bg=%s", user_id, user.avatar_style, user.avatar_bg)
|
| 112 |
return redirect(request.referrer or url_for("lobby.index"))
|
| 113 |
|
| 114 |
|
| 115 |
+
@bp.route("/inference")
|
| 116 |
+
def inference():
|
| 117 |
+
"""Keep inference test accessible for fun."""
|
| 118 |
+
logger.info("INFERENCE_TEST_ACCESSED")
|
| 119 |
+
Telemetry.log("inference_test_view", user_id=session.get("user_id"))
|
| 120 |
+
return render_template("inference.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
routes/telemetry.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
from flask import Blueprint, request, session, jsonify
|
| 2 |
from services.telemetry import Telemetry
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
|
| 5 |
bp = Blueprint("telemetry", __name__)
|
| 6 |
|
|
|
|
| 1 |
from flask import Blueprint, request, session, jsonify
|
| 2 |
from services.telemetry import Telemetry
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
logger = logging.getLogger(__name__)
|
| 6 |
|
| 7 |
bp = Blueprint("telemetry", __name__)
|
| 8 |
|
routes/websocket.py
CHANGED
|
@@ -1,19 +1,23 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
from extensions import sock, db
|
| 3 |
from models import Room, User, ChatMessage
|
| 4 |
from services.telemetry import Telemetry
|
| 5 |
import json
|
| 6 |
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
user_id = session.get('user_id')
|
| 11 |
-
room = Room.query.
|
| 12 |
if not room or not user_id:
|
| 13 |
ws.close()
|
| 14 |
return
|
| 15 |
user = User.query.get(user_id)
|
| 16 |
Telemetry.log('ws_connect', user_id=user_id, room_id=room.id)
|
|
|
|
| 17 |
while True:
|
| 18 |
try:
|
| 19 |
data = ws.receive()
|
|
@@ -26,7 +30,12 @@ def room_ws(ws, code):
|
|
| 26 |
db.session.add(chat)
|
| 27 |
db.session.commit()
|
| 28 |
Telemetry.log('chat_message', user_id=user_id, room_id=room.id, payload={'len': len(content)})
|
|
|
|
| 29 |
ws.send(json.dumps({'type': 'chat', 'user': user.nickname, 'msg': content}))
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
| 31 |
break
|
| 32 |
Telemetry.log('ws_disconnect', user_id=user_id, room_id=room.id)
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from flask import session, request
|
| 3 |
from extensions import sock, db
|
| 4 |
from models import Room, User, ChatMessage
|
| 5 |
from services.telemetry import Telemetry
|
| 6 |
import json
|
| 7 |
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
+
|
| 11 |
+
@sock.route('/ws/room/<int:room_id>')
|
| 12 |
+
def room_ws(ws, room_id):
|
| 13 |
user_id = session.get('user_id')
|
| 14 |
+
room = Room.query.get(room_id)
|
| 15 |
if not room or not user_id:
|
| 16 |
ws.close()
|
| 17 |
return
|
| 18 |
user = User.query.get(user_id)
|
| 19 |
Telemetry.log('ws_connect', user_id=user_id, room_id=room.id)
|
| 20 |
+
logger.info("WS_CONNECT user=%s room=%s", user_id, room_id)
|
| 21 |
while True:
|
| 22 |
try:
|
| 23 |
data = ws.receive()
|
|
|
|
| 30 |
db.session.add(chat)
|
| 31 |
db.session.commit()
|
| 32 |
Telemetry.log('chat_message', user_id=user_id, room_id=room.id, payload={'len': len(content)})
|
| 33 |
+
logger.info("CHAT_MESSAGE user=%s room=%s len=%s", user_id, room_id, len(content))
|
| 34 |
ws.send(json.dumps({'type': 'chat', 'user': user.nickname, 'msg': content}))
|
| 35 |
+
elif msg.get('type') == 'typing':
|
| 36 |
+
Telemetry.log('typing', user_id=user_id, room_id=room.id)
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.warning("WS_ERROR user=%s room=%s: %s", user_id, room_id, e)
|
| 39 |
break
|
| 40 |
Telemetry.log('ws_disconnect', user_id=user_id, room_id=room.id)
|
| 41 |
+
logger.info("WS_DISCONNECT user=%s room=%s", user_id, room_id)
|
services/avatar.py
CHANGED
|
@@ -8,15 +8,25 @@ class AvatarService:
|
|
| 8 |
return Config.AVATAR_STYLES_CC0
|
| 9 |
|
| 10 |
@staticmethod
|
| 11 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
styles = AvatarService.get_styles()
|
| 13 |
style = style if style in styles else random.choice(styles)
|
| 14 |
if not seed:
|
| 15 |
seed = str(random.randint(100000, 999999))
|
| 16 |
-
# DiceBear API v7 style URLs
|
| 17 |
base = f"https://api.dicebear.com/7.x/{style}/{format}"
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
@staticmethod
|
| 21 |
def random_avatar():
|
| 22 |
-
return AvatarService.build_url(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
return Config.AVATAR_STYLES_CC0
|
| 9 |
|
| 10 |
@staticmethod
|
| 11 |
+
def get_backgrounds():
|
| 12 |
+
return Config.AVATAR_BACKGROUNDS
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def build_url(style=None, seed=None, bg=None, format="svg"):
|
| 16 |
styles = AvatarService.get_styles()
|
| 17 |
style = style if style in styles else random.choice(styles)
|
| 18 |
if not seed:
|
| 19 |
seed = str(random.randint(100000, 999999))
|
|
|
|
| 20 |
base = f"https://api.dicebear.com/7.x/{style}/{format}"
|
| 21 |
+
url = f"{base}?seed={seed}"
|
| 22 |
+
if bg and bg != "transparent":
|
| 23 |
+
url += f"&backgroundColor={bg}"
|
| 24 |
+
return url
|
| 25 |
|
| 26 |
@staticmethod
|
| 27 |
def random_avatar():
|
| 28 |
+
return AvatarService.build_url(
|
| 29 |
+
style=random.choice(AvatarService.get_styles()),
|
| 30 |
+
seed=str(random.randint(100000, 999999)),
|
| 31 |
+
bg=random.choice(AvatarService.get_backgrounds()),
|
| 32 |
+
)
|
services/rooms.py
CHANGED
|
@@ -1,23 +1,16 @@
|
|
| 1 |
-
import
|
| 2 |
-
import string
|
| 3 |
from extensions import db
|
| 4 |
from models import Room, RoomMembership, User, ChatMessage
|
|
|
|
| 5 |
|
|
|
|
| 6 |
|
| 7 |
-
class RoomService:
|
| 8 |
-
@staticmethod
|
| 9 |
-
def generate_code(length=6):
|
| 10 |
-
while True:
|
| 11 |
-
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
|
| 12 |
-
if not Room.query.filter_by(code=code).first():
|
| 13 |
-
return code
|
| 14 |
|
|
|
|
| 15 |
@staticmethod
|
| 16 |
def create_room(host_user_id, name="", is_public=True, max_players=15, min_players=5):
|
| 17 |
-
code = RoomService.generate_code()
|
| 18 |
room = Room(
|
| 19 |
-
|
| 20 |
-
name=name or f"Room {code}",
|
| 21 |
is_public=is_public,
|
| 22 |
max_players=max_players,
|
| 23 |
min_players=min_players,
|
|
@@ -25,22 +18,34 @@ class RoomService:
|
|
| 25 |
)
|
| 26 |
db.session.add(room)
|
| 27 |
db.session.commit()
|
| 28 |
-
# add host membership
|
| 29 |
membership = RoomMembership(room_id=room.id, user_id=host_user_id, is_host=True)
|
| 30 |
db.session.add(membership)
|
| 31 |
db.session.commit()
|
|
|
|
|
|
|
| 32 |
return room
|
| 33 |
|
| 34 |
@staticmethod
|
| 35 |
def join_room(room_id, user_id):
|
| 36 |
existing = RoomMembership.query.filter_by(room_id=room_id, user_id=user_id, left_at=None).first()
|
| 37 |
if existing:
|
|
|
|
| 38 |
return existing
|
| 39 |
membership = RoomMembership(room_id=room_id, user_id=user_id)
|
| 40 |
db.session.add(membership)
|
| 41 |
db.session.commit()
|
|
|
|
|
|
|
| 42 |
return membership
|
| 43 |
|
| 44 |
@staticmethod
|
| 45 |
def get_active_members(room_id):
|
| 46 |
return RoomMembership.query.filter_by(room_id=room_id).filter(RoomMembership.left_at.is_(None)).all()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
|
|
|
| 2 |
from extensions import db
|
| 3 |
from models import Room, RoomMembership, User, ChatMessage
|
| 4 |
+
from services.telemetry import Telemetry
|
| 5 |
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
class RoomService:
|
| 10 |
@staticmethod
|
| 11 |
def create_room(host_user_id, name="", is_public=True, max_players=15, min_players=5):
|
|
|
|
| 12 |
room = Room(
|
| 13 |
+
name=name or f"Room {host_user_id}",
|
|
|
|
| 14 |
is_public=is_public,
|
| 15 |
max_players=max_players,
|
| 16 |
min_players=min_players,
|
|
|
|
| 18 |
)
|
| 19 |
db.session.add(room)
|
| 20 |
db.session.commit()
|
|
|
|
| 21 |
membership = RoomMembership(room_id=room.id, user_id=host_user_id, is_host=True)
|
| 22 |
db.session.add(membership)
|
| 23 |
db.session.commit()
|
| 24 |
+
logger.info("ROOM_CREATED room_id=%s host=%s min=%s max=%s", room.id, host_user_id, min_players, max_players)
|
| 25 |
+
Telemetry.log("room_create", user_id=host_user_id, room_id=room.id)
|
| 26 |
return room
|
| 27 |
|
| 28 |
@staticmethod
|
| 29 |
def join_room(room_id, user_id):
|
| 30 |
existing = RoomMembership.query.filter_by(room_id=room_id, user_id=user_id, left_at=None).first()
|
| 31 |
if existing:
|
| 32 |
+
logger.info("ROOM_JOIN_EXISTING room_id=%s user=%s", room_id, user_id)
|
| 33 |
return existing
|
| 34 |
membership = RoomMembership(room_id=room_id, user_id=user_id)
|
| 35 |
db.session.add(membership)
|
| 36 |
db.session.commit()
|
| 37 |
+
logger.info("ROOM_JOIN room_id=%s user=%s", room_id, user_id)
|
| 38 |
+
Telemetry.log("room_join", user_id=user_id, room_id=room_id)
|
| 39 |
return membership
|
| 40 |
|
| 41 |
@staticmethod
|
| 42 |
def get_active_members(room_id):
|
| 43 |
return RoomMembership.query.filter_by(room_id=room_id).filter(RoomMembership.left_at.is_(None)).all()
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def leave_room(room_id, user_id):
|
| 47 |
+
m = RoomMembership.query.filter_by(room_id=room_id, user_id=user_id, left_at=None).first()
|
| 48 |
+
if m:
|
| 49 |
+
m.left_at = db.func.now() if False else __import__('datetime').datetime.utcnow()
|
| 50 |
+
db.session.commit()
|
| 51 |
+
logger.info("ROOM_LEAVE room_id=%s user=%s", room_id, user_id)
|
services/test_players.py
CHANGED
|
@@ -1,34 +1,85 @@
|
|
| 1 |
-
|
| 2 |
import time
|
| 3 |
-
import
|
| 4 |
-
from flask import session
|
| 5 |
from extensions import db
|
| 6 |
from models import User, Room, RoomMembership, ChatMessage
|
| 7 |
from services.rooms import RoomService
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class TestMode:
|
|
|
|
|
|
|
| 10 |
@staticmethod
|
| 11 |
def is_enabled():
|
| 12 |
-
return
|
| 13 |
-
|
| 14 |
@staticmethod
|
| 15 |
-
def create_test_players(count=
|
|
|
|
| 16 |
test_users = []
|
| 17 |
for i in range(count):
|
| 18 |
-
uid = f"TEST{i}"
|
| 19 |
user = User.query.filter_by(nickname=f"TestBot{i}").first()
|
| 20 |
if not user:
|
| 21 |
-
user = User(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
db.session.add(user)
|
| 23 |
db.session.commit()
|
|
|
|
| 24 |
test_users.append(user)
|
| 25 |
return test_users
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
@staticmethod
|
| 28 |
-
def
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import threading
|
| 2 |
import time
|
| 3 |
+
import logging
|
|
|
|
| 4 |
from extensions import db
|
| 5 |
from models import User, Room, RoomMembership, ChatMessage
|
| 6 |
from services.rooms import RoomService
|
| 7 |
+
from config import Config
|
| 8 |
+
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
|
| 12 |
class TestMode:
|
| 13 |
+
_threads = {}
|
| 14 |
+
|
| 15 |
@staticmethod
|
| 16 |
def is_enabled():
|
| 17 |
+
return getattr(Config, "TEST_MODE", True)
|
| 18 |
+
|
| 19 |
@staticmethod
|
| 20 |
+
def create_test_players(count=None):
|
| 21 |
+
count = count or Config.TEST_BOT_COUNT
|
| 22 |
test_users = []
|
| 23 |
for i in range(count):
|
|
|
|
| 24 |
user = User.query.filter_by(nickname=f"TestBot{i}").first()
|
| 25 |
if not user:
|
| 26 |
+
user = User(
|
| 27 |
+
nickname=f"TestBot{i}",
|
| 28 |
+
avatar_style="bottts",
|
| 29 |
+
avatar_seed=f"TEST{i}",
|
| 30 |
+
avatar_bg="b6e3f4",
|
| 31 |
+
)
|
| 32 |
db.session.add(user)
|
| 33 |
db.session.commit()
|
| 34 |
+
logger.info("TESTBOT_CREATED id=%s name=%s", user.id, user.nickname)
|
| 35 |
test_users.append(user)
|
| 36 |
return test_users
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def start_chat_loop(app, room_id):
|
| 40 |
+
"""Start a background thread that makes test bots say DURRRR every N seconds."""
|
| 41 |
+
if room_id in TestMode._threads:
|
| 42 |
+
return
|
| 43 |
+
test_users = TestMode.create_test_players()
|
| 44 |
+
stop_event = threading.Event()
|
| 45 |
+
|
| 46 |
+
def _loop():
|
| 47 |
+
logger.info("TESTBOT_CHAT_LOOP_START room=%s interval=%s", room_id, Config.TEST_BOT_CHAT_INTERVAL)
|
| 48 |
+
while not stop_event.is_set():
|
| 49 |
+
time.sleep(Config.TEST_BOT_CHAT_INTERVAL)
|
| 50 |
+
if stop_event.is_set():
|
| 51 |
+
break
|
| 52 |
+
try:
|
| 53 |
+
with app.app_context():
|
| 54 |
+
for user in test_users:
|
| 55 |
+
msg = ChatMessage(room_id=room_id, user_id=user.id, content="DURRRR")
|
| 56 |
+
db.session.add(msg)
|
| 57 |
+
db.session.commit()
|
| 58 |
+
logger.info("TESTBOT_CHAT room=%s bots=%s", room_id, len(test_users))
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.exception("TESTBOT_CHAT_ERROR: %s", e)
|
| 61 |
+
try:
|
| 62 |
+
db.session.rollback()
|
| 63 |
+
except Exception:
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
t = threading.Thread(target=_loop, daemon=True, name=f"testbot-chat-{room_id}")
|
| 67 |
+
t.start()
|
| 68 |
+
TestMode._threads[room_id] = (t, stop_event)
|
| 69 |
+
logger.info("TESTBOT_THREAD_STARTED room=%s", room_id)
|
| 70 |
+
|
| 71 |
@staticmethod
|
| 72 |
+
def auto_setup_room(app, user_id):
|
| 73 |
+
"""Create a room with test bots and join the user. Returns room."""
|
| 74 |
+
with app.app_context():
|
| 75 |
+
test_users = TestMode.create_test_players()
|
| 76 |
+
room = RoomService.create_room(test_users[0].id, name="Auto-Test Room")
|
| 77 |
+
for u in test_users[1:]:
|
| 78 |
+
RoomService.join_room(room.id, u.id)
|
| 79 |
+
RoomService.join_room(room.id, user_id)
|
| 80 |
+
logger.warning("AUTO_ASSIGN: Room %s created with %s test bots + user %s", room.id, len(test_users), user_id)
|
| 81 |
+
from services.telemetry import Telemetry
|
| 82 |
+
Telemetry.log("auto_assign_trigger", user_id=user_id, room_id=room.id, payload={"players": len(test_users) + 1})
|
| 83 |
+
# Start chat loop in background
|
| 84 |
+
TestMode.start_chat_loop(app, room.id)
|
| 85 |
+
return room
|
templates/base.html
CHANGED
|
@@ -12,7 +12,10 @@
|
|
| 12 |
<nav class="bg-black/30 backdrop-blur p-4">
|
| 13 |
<div class="container mx-auto flex justify-between items-center">
|
| 14 |
<h1 class="text-2xl font-bold">🎮 cuddly happy game platform</h1>
|
| 15 |
-
<
|
|
|
|
|
|
|
|
|
|
| 16 |
</div>
|
| 17 |
</nav>
|
| 18 |
<main class="container mx-auto p-4">
|
|
|
|
| 12 |
<nav class="bg-black/30 backdrop-blur p-4">
|
| 13 |
<div class="container mx-auto flex justify-between items-center">
|
| 14 |
<h1 class="text-2xl font-bold">🎮 cuddly happy game platform</h1>
|
| 15 |
+
<div class="flex gap-4">
|
| 16 |
+
<a href="/" class="hover:text-pink-300">Lobby</a>
|
| 17 |
+
<a href="/inference" class="hover:text-pink-300">Inference Test</a>
|
| 18 |
+
</div>
|
| 19 |
</div>
|
| 20 |
</nav>
|
| 21 |
<main class="container mx-auto p-4">
|
templates/index.html
CHANGED
|
@@ -1,16 +1,16 @@
|
|
| 1 |
{% extends "base.html" %}
|
| 2 |
{% block content %}
|
| 3 |
-
<div class="grid grid-cols-1 md:grid-cols-
|
| 4 |
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 5 |
-
<h2 class="text-xl font-bold mb-4">🚀
|
| 6 |
<form action="/create" method="POST">
|
| 7 |
<input type="text" name="name" placeholder="Room name (optional)" class="w-full p-2 mb-2 rounded bg-gray-800 text-white">
|
| 8 |
<div class="flex gap-4 mb-2">
|
| 9 |
<label class="flex items-center gap-2">
|
| 10 |
<input type="checkbox" name="is_public" checked> Public
|
| 11 |
</label>
|
| 12 |
-
<input type="number" name="min_players" value="5" min="5" max="15" class="p-1 rounded bg-gray-800 text-white w-20">
|
| 13 |
-
<input type="number" name="max_players" value="15" min="5" max="15" class="p-1 rounded bg-gray-800 text-white w-20">
|
| 14 |
</div>
|
| 15 |
<button class="bg-pink-600 hover:bg-pink-700 px-4 py-2 rounded">Create & Enter</button>
|
| 16 |
</form>
|
|
@@ -20,14 +20,31 @@
|
|
| 20 |
<form action="/avatar/update" method="POST" class="space-y-2">
|
| 21 |
<select name="style" class="w-full p-2 rounded bg-gray-800 text-white">
|
| 22 |
{% for s in styles %}
|
| 23 |
-
<option value="{{ s }}">{{ s }}</option>
|
| 24 |
{% endfor %}
|
| 25 |
</select>
|
| 26 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
<button class="bg-purple-600 hover:bg-purple-700 px-4 py-2 rounded">Update Avatar</button>
|
| 28 |
</form>
|
| 29 |
<p class="text-xs mt-2 text-gray-400">Using DiceBear CC0 avatars</p>
|
| 30 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
</div>
|
| 32 |
<div class="mt-6 bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 33 |
<h2 class="text-xl font-bold mb-4">🌐 Public Lobbies</h2>
|
|
@@ -38,7 +55,7 @@
|
|
| 38 |
<span class="font-bold">{{ room.name }}</span>
|
| 39 |
<span class="text-sm text-gray-400">({{ room.min_players }}-{{ room.max_players }} players)</span>
|
| 40 |
</div>
|
| 41 |
-
<a href="/join/{{ room.
|
| 42 |
</div>
|
| 43 |
{% else %}
|
| 44 |
<p class="text-gray-400">No public lobbies yet. Create one!</p>
|
|
|
|
| 1 |
{% extends "base.html" %}
|
| 2 |
{% block content %}
|
| 3 |
+
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 4 |
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 5 |
+
<h2 class="text-xl font-bold mb-4">🚀 Create Room</h2>
|
| 6 |
<form action="/create" method="POST">
|
| 7 |
<input type="text" name="name" placeholder="Room name (optional)" class="w-full p-2 mb-2 rounded bg-gray-800 text-white">
|
| 8 |
<div class="flex gap-4 mb-2">
|
| 9 |
<label class="flex items-center gap-2">
|
| 10 |
<input type="checkbox" name="is_public" checked> Public
|
| 11 |
</label>
|
| 12 |
+
<input type="number" name="min_players" value="5" min="5" max="15" class="p-1 rounded bg-gray-800 text-white w-20" title="Min players">
|
| 13 |
+
<input type="number" name="max_players" value="15" min="5" max="15" class="p-1 rounded bg-gray-800 text-white w-20" title="Max players">
|
| 14 |
</div>
|
| 15 |
<button class="bg-pink-600 hover:bg-pink-700 px-4 py-2 rounded">Create & Enter</button>
|
| 16 |
</form>
|
|
|
|
| 20 |
<form action="/avatar/update" method="POST" class="space-y-2">
|
| 21 |
<select name="style" class="w-full p-2 rounded bg-gray-800 text-white">
|
| 22 |
{% for s in styles %}
|
| 23 |
+
<option value="{{ s }}" {% if user and user.avatar_style == s %}selected{% endif %}>{{ s }}</option>
|
| 24 |
{% endfor %}
|
| 25 |
</select>
|
| 26 |
+
<select name="bg" class="w-full p-2 rounded bg-gray-800 text-white">
|
| 27 |
+
{% for b in backgrounds %}
|
| 28 |
+
<option value="{{ b }}" {% if user and user.avatar_bg == b %}selected{% endif %}>{{ b }}</option>
|
| 29 |
+
{% endfor %}
|
| 30 |
+
</select>
|
| 31 |
+
<input type="text" name="seed" placeholder="Seed (random if empty)" value="{{ user.avatar_seed if user else '' }}" class="w-full p-2 rounded bg-gray-800 text-white">
|
| 32 |
<button class="bg-purple-600 hover:bg-purple-700 px-4 py-2 rounded">Update Avatar</button>
|
| 33 |
</form>
|
| 34 |
<p class="text-xs mt-2 text-gray-400">Using DiceBear CC0 avatars</p>
|
| 35 |
</div>
|
| 36 |
+
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 37 |
+
<h2 class="text-xl font-bold mb-4">👤 You</h2>
|
| 38 |
+
{% if user %}
|
| 39 |
+
<div class="flex items-center gap-4">
|
| 40 |
+
<img src="{{ avatar_url }}" alt="avatar" class="w-20 h-20 rounded-full bg-gray-700" onerror="this.style.display='none'">
|
| 41 |
+
<div>
|
| 42 |
+
<p class="font-bold">{{ user.nickname }}</p>
|
| 43 |
+
<p class="text-sm text-gray-400">{{ user.avatar_style }}</p>
|
| 44 |
+
</div>
|
| 45 |
+
</div>
|
| 46 |
+
{% endif %}
|
| 47 |
+
</div>
|
| 48 |
</div>
|
| 49 |
<div class="mt-6 bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 50 |
<h2 class="text-xl font-bold mb-4">🌐 Public Lobbies</h2>
|
|
|
|
| 55 |
<span class="font-bold">{{ room.name }}</span>
|
| 56 |
<span class="text-sm text-gray-400">({{ room.min_players }}-{{ room.max_players }} players)</span>
|
| 57 |
</div>
|
| 58 |
+
<a href="/join/{{ room.id }}" class="bg-blue-600 hover:bg-blue-700 px-3 py-1 rounded">Join</a>
|
| 59 |
</div>
|
| 60 |
{% else %}
|
| 61 |
<p class="text-gray-400">No public lobbies yet. Create one!</p>
|
templates/inference.html
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% extends "base.html" %}
|
| 2 |
+
{% block content %}
|
| 3 |
+
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 4 |
+
<h2 class="text-2xl font-bold mb-4">🧪 Inference Test (kept for fun)</h2>
|
| 5 |
+
<p class="text-gray-300 mb-4">This is the original HuggingFace inference smoke test. Run it via smoke.py for full functionality.</p>
|
| 6 |
+
<p class="text-sm text-gray-400">The smoke test queries trending conversational models and sends a tiny chat request to each.</p>
|
| 7 |
+
<a href="/" class="bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded inline-block mt-4">Back to Lobby</a>
|
| 8 |
+
</div>
|
| 9 |
+
{% endblock %}
|
templates/room.html
CHANGED
|
@@ -2,13 +2,13 @@
|
|
| 2 |
{% block content %}
|
| 3 |
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 4 |
<div class="md:col-span-2 bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 5 |
-
<h2 class="text-2xl font-bold mb-4">{{ room.name }}
|
| 6 |
<div class="mb-4">
|
| 7 |
<h3 class="font-bold mb-2">Players ({{ members|length }})</h3>
|
| 8 |
<div class="grid grid-cols-2 gap-2">
|
| 9 |
{% for m in members %}
|
| 10 |
<div class="bg-gray-800/50 p-2 rounded flex items-center gap-2">
|
| 11 |
-
<
|
| 12 |
<span>{{ m.user.nickname }}{% if m.membership.is_host %} 👑{% endif %}</span>
|
| 13 |
</div>
|
| 14 |
{% endfor %}
|
|
@@ -20,12 +20,16 @@
|
|
| 20 |
</div>
|
| 21 |
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 22 |
<h3 class="font-bold mb-2">💬 Chat</h3>
|
| 23 |
-
<div id="chat" class="h-64 overflow-y-auto bg-gray-900/50 p-2 mb-2 rounded space-y-1">
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
<input id="chat-input" class="w-full p-2 rounded bg-gray-800 text-white" placeholder="Type...">
|
| 25 |
</div>
|
| 26 |
</div>
|
| 27 |
<script>
|
| 28 |
-
const ws = new WebSocket((location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + location.host + '/ws/room/{{ room.
|
| 29 |
ws.onmessage = function(e) {
|
| 30 |
const data = JSON.parse(e.data);
|
| 31 |
if(data.type === 'chat') {
|
|
@@ -47,5 +51,11 @@ document.addEventListener('click', function(e) {
|
|
| 47 |
document.addEventListener('keypress', function(e) {
|
| 48 |
fetch('/api/telemetry', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({event_type:'keypress', room_id:{{ room.id }}, element:e.target.tagName})});
|
| 49 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
</script>
|
| 51 |
{% endblock %}
|
|
|
|
| 2 |
{% block content %}
|
| 3 |
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 4 |
<div class="md:col-span-2 bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 5 |
+
<h2 class="text-2xl font-bold mb-4">{{ room.name }}</h2>
|
| 6 |
<div class="mb-4">
|
| 7 |
<h3 class="font-bold mb-2">Players ({{ members|length }})</h3>
|
| 8 |
<div class="grid grid-cols-2 gap-2">
|
| 9 |
{% for m in members %}
|
| 10 |
<div class="bg-gray-800/50 p-2 rounded flex items-center gap-2">
|
| 11 |
+
<img src="{{ avatar_urls[m.user.id] }}" alt="avatar" class="w-10 h-10 rounded-full" onerror="this.style.display='none'">
|
| 12 |
<span>{{ m.user.nickname }}{% if m.membership.is_host %} 👑{% endif %}</span>
|
| 13 |
</div>
|
| 14 |
{% endfor %}
|
|
|
|
| 20 |
</div>
|
| 21 |
<div class="bg-black/40 rounded-lg p-6 backdrop-blur">
|
| 22 |
<h3 class="font-bold mb-2">💬 Chat</h3>
|
| 23 |
+
<div id="chat" class="h-64 overflow-y-auto bg-gray-900/50 p-2 mb-2 rounded space-y-1">
|
| 24 |
+
{% for c in chats %}
|
| 25 |
+
<div><b>{{ c.user }}:</b> {{ c.content }}</div>
|
| 26 |
+
{% endfor %}
|
| 27 |
+
</div>
|
| 28 |
<input id="chat-input" class="w-full p-2 rounded bg-gray-800 text-white" placeholder="Type...">
|
| 29 |
</div>
|
| 30 |
</div>
|
| 31 |
<script>
|
| 32 |
+
const ws = new WebSocket((location.protocol === 'https:' ? 'wss:' : 'ws:') + '//' + location.host + '/ws/room/{{ room.id }}');
|
| 33 |
ws.onmessage = function(e) {
|
| 34 |
const data = JSON.parse(e.data);
|
| 35 |
if(data.type === 'chat') {
|
|
|
|
| 51 |
document.addEventListener('keypress', function(e) {
|
| 52 |
fetch('/api/telemetry', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({event_type:'keypress', room_id:{{ room.id }}, element:e.target.tagName})});
|
| 53 |
});
|
| 54 |
+
// Typing telemetry
|
| 55 |
+
let typingTimer;
|
| 56 |
+
document.getElementById('chat-input').addEventListener('input', function() {
|
| 57 |
+
clearTimeout(typingTimer);
|
| 58 |
+
fetch('/api/telemetry', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({event_type:'typing', room_id:{{ room.id }}, element:'chat-input'})});
|
| 59 |
+
});
|
| 60 |
</script>
|
| 61 |
{% endblock %}
|