from flask import Flask, render_template, request, session, redirect, url_for from flask_socketio import join_room, leave_room, send, SocketIO, emit import random from string import ascii_uppercase rooms = {} def generate_unique_code(length): while True: code = "" for _ in range(length): code += random.choice(ascii_uppercase) if code not in rooms: break return code app = Flask(__name__) # Change this to something more secure in production app.config["SECRET_KEY"] = '3fa3cf7f8d88a8e2dbd8dd57350d583536e447a24b0a8f21' socketio = SocketIO(app) @app.route("/", methods=["GET", "POST"]) def home(): session.clear() if request.method == "POST": name = request.form.get("name") code = request.form.get("code") join = request.form.get("join", False) create = request.form.get("create", False) if not name: return render_template("home.html", error="Please enter a name!", code=code, name=name) if join != False and not code: return render_template("home.html", error="Please enter a room code!", code=code, name=name) room = code if create != False: room = generate_unique_code(6) rooms[room] = {"members": 0, "messages": []} elif code not in rooms: return render_template("home.html", error="Room does not exist!", code=code, name=name) session["room"] = room session["name"] = name return redirect(url_for("room")) return render_template("home.html") @app.route("/room") def room(): room = session.get("room") if room is None or session.get("name") is None or room not in rooms: return redirect(url_for("home")) return render_template("room.html", code=room, messages=rooms[room]["messages"]) @socketio.on("message") def message(data): room = session.get("room") if room not in rooms: return content = { "name": session.get("name"), "message": data["data"] } send(content, to=room) rooms[room]["messages"].append(content) print(f"{session.get('name')} said: {data['data']}") @socketio.on("connect") def connect(auth): room = session.get("room") name = session.get("name") if room is None or name is None: return if room not in rooms: leave_room(room) return join_room(room) send({"name": name, "message": "has joined the room"}, to=room) rooms[room]["members"] += 1 emit("member_join", {"name": name, "members_count": rooms[room]["members"]}, to=room) print(f"{name} has joined room {room}") @socketio.on("disconnect") def disconnect(): room = session.get("room") name = session.get("name") leave_room(room) if room in rooms: rooms[room]["members"] -= 1 if rooms[room]["members"] <= 0: del rooms[room] send({"name": name, "message": "has left the room"}, to=room) emit("member_leave", {"name": name, "members_count": rooms.get( room, {}).get("members", 0)}, to=room) print(f"{name} has left room {room}") print(f"Room {room} has been deleted") if __name__ == "__main__": socketio.run(app, debug=True, host="0.0.0.0", port=5000)