-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
89 lines (72 loc) · 2.29 KB
/
web_server.py
File metadata and controls
89 lines (72 loc) · 2.29 KB
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
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, join_room, leave_room
from crypto_utils import generate_key, encrypt_message, decrypt_message
import json
import os
app = Flask(__name__,
static_folder='static',
static_url_path='/static',
template_folder='templates'
)
app.config['SECRET_KEY'] = 'lan_cryptochat_secret'
socketio = SocketIO(app)
encryption_key = generate_key()
connected_users = {}
user_rooms = {}
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def handle_connect():
print('Client connesso')
@socketio.on('join')
def handle_join(data):
username = data['username']
room = data['room']
if request.sid in user_rooms:
old_room = user_rooms[request.sid]
leave_room(old_room)
emit('status', {
'msg': f'{username} ha lasciato la chat',
'room': old_room
}, room=old_room)
connected_users[request.sid] = username
user_rooms[request.sid] = room
join_room(room)
emit('encryption_key', {'key': encryption_key.decode()})
emit('status', {
'msg': f'{username} è entrato nella chat',
'room': room
}, room=room)
@socketio.on('leave_room')
def handle_leave_room(data):
room = data['room']
username = connected_users.get(request.sid, 'Anonimo')
leave_room(room)
emit('status', {
'msg': f'{username} ha lasciato la chat',
'room': room
}, room=room)
@socketio.on('message')
def handle_message(data):
room = data['room']
username = connected_users.get(request.sid, 'Anonimo')
emit('message', {
'username': username,
'message': data['message']
}, room=room)
@socketio.on('disconnect')
def handle_disconnect():
if request.sid in connected_users:
username = connected_users[request.sid]
room = user_rooms.get(request.sid)
del connected_users[request.sid]
if request.sid in user_rooms:
del user_rooms[request.sid]
if room:
emit('status', {
'msg': f'{username} ha lasciato la chat',
'room': room
}, room=room)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, debug=True)