-
Notifications
You must be signed in to change notification settings - Fork 0
/
m2m.py
91 lines (73 loc) · 2.75 KB
/
m2m.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import time
from flask import Flask, redirect, render_template, request, jsonify
from flask_socketio import SocketIO, join_room, leave_room
import uuid
app = Flask(__name__)
socketio = SocketIO(app,
cors_allowed_origins="*",
#max_http_buffer_size=9999999999
)
rooms = {} # For simplicity, store rooms in-memory
@app.route('/create_room', methods=['POST'])
def create_room():
room_id = uuid.uuid4().hex[:8] # short unique id for room
if room_id in rooms:
return jsonify(success=False, message="Room already exists"), 400
rooms[room_id] = {"participants": []}
return jsonify({
"success": True,
"room_id": room_id
})
@app.route('/get_rooms', methods=['GET'])
def get_rooms():
return jsonify(list(rooms.keys()))
@app.route('/delete_room/<room_id>', methods=['GET'])
def delete_room(room_id):
del rooms[room_id]
return jsonify({
"success": True,
"message": "Room deleted"
})
@socketio.on('join')
def on_join(data):
username = data['username']
room_id = data['room_id']
if room_id not in rooms:
return {"success": False, "message": "Room not found"}
join_room(room_id)
rooms[room_id]["participants"].append(username)
# Notify other users in the room about the new user
for participant in rooms[room_id]["participants"]:
if participant != username:
socketio.emit('user_joined', {"username": username, "userId": request.sid}, room=participant)
time.sleep(5)
print(f"User {username} has joined room {room_id}")
# Notify other users in the room about the new user
socketio.emit('user_joined', {"username": username, "userId": request.sid}, room=room_id)
@socketio.on('leave')
def on_leave(data):
username = data['username']
room_id = data['room_id']
if room_id not in rooms:
return {"success": False, "message": "Room not found"}
leave_room(room_id)
rooms[room_id]["participants"].remove(username)
socketio.emit('user_left', {"username": username, "userId": request.sid}, room=room_id)
@socketio.on('signal')
def on_signal(data):
target_user = data['userId']
room_id = data['room_id']
signal = data['signal']
print(f"Signal from {request.sid} to {target_user}")
# Send the signal to the specified user in the room
socketio.emit('signal', {"userId": request.sid, "signal": signal}, room=target_user)
@app.route('/room_join/<room_id>')
def room_join(room_id):
if room_id in rooms.keys():
return render_template('m2m_2.html', room_id=room_id)
return redirect('/')
@app.route('/')
def index():
return render_template('m2m_1.html')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', debug=True)