-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
165 lines (134 loc) · 5.91 KB
/
app.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from datetime import datetime
from multiprocessing.spawn import import_main_path
from bson.json_util import dumps
from flask import Flask, url_for, render_template, request, redirect
from flask_socketio import SocketIO, join_room
from flask_login import LoginManager, current_user, login_user, logout_user, login_required
from pymongo.errors import DuplicateKeyError
from db import get_messages, get_user, save_user, save_room, add_room_members, get_rooms_for_user, get_room, is_room_member, \
get_room_members, is_room_admin, update_room, remove_room_members, save_message
app = Flask(__name__)
app.config['SECRET_KEY'] = "secret"
socketio = SocketIO(app, cors_allowed_origins='*')
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@app.route('/')
def home():
rooms = []
if current_user.is_authenticated:
rooms = get_rooms_for_user(current_user.username)
return render_template("index.html", rooms=rooms)
@app.route('/logout')
@login_required
def logout():
logout_user()
return "logged out"
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if current_user.is_authenticated:
return redirect(url_for('home'))
message = ''
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
try:
save_user(username, email, password)
return redirect(url_for('login'))
except DuplicateKeyError:
message = 'User already exists!'
return render_template('signup.html', message=message)
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('home'))
message = ''
if request.method == 'POST':
username = request.form.get('username')
password_input = request.form.get('password')
user = get_user(username)
if user and user.check_password(password_input):
login_user(user)
return redirect(url_for('home'))
else:
message = 'Failed to login !'
return render_template('login.html', message=message)
@app.route('/rooms/<room_id>/')
@login_required
def view_room(room_id):
room = get_room(room_id)
messages = get_messages(room_id)
if room and is_room_member(room_id, current_user.username):
room_members = get_room_members(room_id)
return render_template('view_room.html', room=room, room_members=room_members, username=current_user.username, messages=messages)
else:
return 'Room not found', 404
@app.route('/create-room', methods=['GET', 'POST'])
@login_required
def create_room():
message = ''
if request.method == 'POST':
room_name = request.form.get('room_name')
usernames = [username.strip() for username in request.form.get('members').split(',')]
if len(room_name) and len(usernames):
room_id = save_room(room_name, current_user.username)
if current_user.username in usernames:
usernames.remove(current_user.username)
add_room_members(room_id, room_name, usernames, current_user.username)
return redirect(url_for('view_room', room_id=room_id))
else:
message = 'Failed to create the room'
return render_template('create_room.html', message=message)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/rooms/<room_id>/edit', methods=['GET','POST'])
def edit_room(room_id):
message = ''
room = get_room(room_id)
if room and is_room_admin(room_id, current_user.username):
ext_room_members = [member['_id']['username']for member in get_room_members(room_id)]
room_members_str = ",".join(ext_room_members)
if request.method == 'POST':
room_name = request.form.get('room_name')
update_room(room_id, room_name)
room['name'] = room_name
new_members = [username.strip() for username in request.form.get('members').split(',')]
members_to_add = list(set(new_members)-set(ext_room_members))
members_to_remove = list(set(ext_room_members)-set(new_members))
if len(members_to_add):
add_room_members(room_id, room_name, members_to_add, current_user.username)
if len(members_to_remove):
remove_room_members(room_id, members_to_remove)
message = "Room edited successfully"
room_members_str = ",".join(new_members)
return render_template('edit_room.html', room=room, message=message, room_members_str=room_members_str)
else:
return 'Room not found', 404
@app.route('/rooms/<room_id>/messages')
@login_required
def get_older_messages(room_id):
room = get_room(room_id)
if room and is_room_member(room_id, current_user.username):
page = int(request.args.get('page',0))
messages = get_messages(room_id,page=page)
return dumps(messages)
else:
return 'Room not found', 404
@socketio.on('join_room')
def handle_join_room_event(data):
app.logger.info(f" {data['username']} has joined the room {data['room']}")
join_room((data['room']))
socketio.emit('join_room_annoncement', data, room=data['room'])
@socketio.on('send_message')
def handle_send_message_event(data):
data['created_at'] = datetime.now().strftime("%d %b, %H:%M")
app.logger.info(f" {data['username']} has sent messaget to the room {data['room']}:{data['message']}")
socketio.emit('receive_message', data, room=data['room'])
save_message(data['room'], data['message'], data['username'])
@login_manager.user_loader
def load_user(username):
return get_user(username)
if __name__ == '__main__':
socketio.run(app, debug=True)