forked from Bamimore-Tomi/fauna-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
289 lines (259 loc) · 9.26 KB
/
main.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import hashlib, os, time
from functools import wraps
from datetime import datetime
import pytz
from flask import (
Flask,
render_template,
request,
flash,
redirect,
url_for,
session,
Response,
)
from flask_socketio import SocketIO, join_room
from faunadb import query as q
from faunadb.objects import Ref
from faunadb.client import FaunaClient
from dotenv import load_dotenv
load_dotenv()
# Initialize client connection to database
client = FaunaClient(secret=os.getenv("FAUNA_KEY"))
app = Flask(__name__, template_folder="templates")
app.config["SECRET_KEY"] = "vnkdjnfjknfl1232#"
# Initialize socketio application
socketio = SocketIO(app)
# Login decorator to ensure user is logged in before accessing certain routes
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if "user" not in session:
return redirect(url_for("login"))
return f(*args, **kwargs)
return decorated
# Index route, this route redirects to login/register page
@app.route("/", methods=["GET", "POST"])
def index():
return redirect(url_for("login"))
# Register a new user and hash password
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
# To setup validator for email
email = request.form["email"].strip().lower()
username = request.form["username"].strip().lower()
password = request.form["password"]
# Make sure no ther user with similar credentials is already registered
try:
user = client.query(q.get(q.match(q.index("users_index"), username)))
flash("User already exists with that username.")
return redirect(url_for("login"))
except:
user = client.query(
q.create(
q.collection("users"),
{
"data": {
"username": username,
"email": email,
"password": hashlib.sha512(password.encode()).hexdigest(),
"date": datetime.now(pytz.UTC),
}
},
)
)
# Create a new chat list for newly registered user
chat = client.query(
q.create(
q.collection("chats"),
{
"data": {
"user_id": user["ref"].id(),
"chat_list": [],
}
},
)
)
flash("Registration successful.")
return redirect(url_for("login"))
return render_template("auth.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
# To add email validator here
email = request.form["email"].strip().lower()
password = request.form["password"]
try:
# Query the data base for the inputted email address
user = client.query(q.get(q.match(q.index("user_index"), email)))
if (
hashlib.sha512(password.encode()).hexdigest()
== user["data"]["password"]
):
# Create new session for newly logged in user
session["user"] = {
"id": user["ref"].id(),
"username": user["data"]["username"],
"email": user["data"]["email"],
}
return redirect(url_for("chat"))
else:
raise Exception()
except Exception as e:
flash("You have supplied invalid login credentials, please try again!")
return redirect(url_for("login"))
return render_template("auth.html")
@app.route("/new-chat", methods=["POST"])
@login_required
def new_chat():
user_id = session["user"]["id"]
new_chat = request.form["email"].strip().lower()
# If user is trying to add their self, do nothing
if new_chat == session["user"]["email"]:
return redirect(url_for("chat"))
try:
# If user tries to add a chat that has not registerd, do nothing
new_chat_id = client.query(q.get(q.match(q.index("user_index"), new_chat)))
except:
return redirect(url_for("chat"))
# Get the chats related to both user
chats = client.query(q.get(q.match(q.index("chat_index"), user_id)))
recepient_chats = client.query(
q.get(q.match(q.index("chat_index"), new_chat_id["ref"].id()))
)
# Check if the chat the users is trying to add has not been added before
try:
chat_list = [list(i.values())[0] for i in chats["data"]["chat_list"]]
except:
chat_list = []
if new_chat_id["ref"].id() not in chat_list:
# Append the new chat to the chat list of the user
room_id = str(int(new_chat_id["ref"].id()) + int(user_id))[-4:]
chats["data"]["chat_list"].append(
{"user_id": new_chat_id["ref"].id(), "room_id": room_id}
)
recepient_chats["data"]["chat_list"].append(
{"user_id": user_id, "room_id": room_id}
)
# Update chat list for both users
client.query(
q.update(
q.ref(q.collection("chats"), chats["ref"].id()),
{"data": {"chat_list": chats["data"]["chat_list"]}},
)
)
client.query(
q.update(
q.ref(q.collection("chats"), recepient_chats["ref"].id()),
{"data": {"chat_list": recepient_chats["data"]["chat_list"]}},
)
)
client.query(
q.create(
q.collection("messages"),
{"data": {"room_id": room_id, "conversation": []}},
)
)
return redirect(url_for("chat"))
@app.route("/chat/", methods=["GET", "POST"])
@login_required
def chat():
# Get the room id in the url or set to None
room_id = request.args.get("rid", None)
# Initialize context that contains information about the chat room
data = []
try:
# Get the chat list for the user in the room i.e all of the people they have a chat histor with on the application
chat_list = client.query(
q.get(q.match(q.index("chat_index"), session["user"]["id"]))
)["data"]["chat_list"]
except:
chat_list = []
for i in chat_list:
# Query the database to get the user name of users in a user's chat list
username = client.query(q.get(q.ref(q.collection("users"), i["user_id"])))[
"data"
]["username"]
is_active = False
# If the room id in the url is the same with any of the room id in a user's chat list, that room is currently the active room
if room_id == i["room_id"]:
is_active = True
try:
# Get the last message for each chat room
last_message = client.query(
q.get(q.match(q.index("message_index"), i["room_id"]))
)["data"]["conversation"][-1]["message"]
except:
# Set variable to this when no messages have been sent to the room
last_message = "This place is empty. No messages ..."
data.append(
{
"username": username,
"room_id": i["room_id"],
"is_active": is_active,
"last_message": last_message,
}
)
# Get all the message history in a certian room
messages = []
if room_id != None:
messages = client.query(q.get(q.match(q.index("message_index"), room_id)))[
"data"
]["conversation"]
return render_template(
"chat.html",
user_data=session["user"],
room_id=room_id,
data=data,
messages=messages,
)
# Custom time filter to be used in the jinja template
@app.template_filter("ftime")
def ftime(date):
return datetime.fromtimestamp(int(date)).strftime("%m.%d. %H:%M")
# Join-chat event. Emit online message to ther users and join the room
@socketio.on("join-chat")
def join_private_chat(data):
room = data["rid"]
join_room(room=room)
socketio.emit(
"joined-chat",
{"msg": f"{room} is now online."},
room=room,
# include_self=False,
)
# Outgoing event handler
@socketio.on("outgoing")
def chatting_event(json, methods=["GET", "POST"]):
room_id = json["rid"]
timestamp = json["timestamp"]
message = json["message"]
sender_id = json["sender_id"]
sender_username = json["sender_username"]
messages = client.query(q.get(q.match(q.index("message_index"), room_id)))
conversation = messages["data"]["conversation"]
conversation.append(
{
"timestamp": timestamp,
"sender_username": sender_username,
"sender_id": sender_id,
"message": message,
}
)
# Updated the database with the new message
client.query(
q.update(
q.ref(q.collection("messages"), messages["ref"].id()),
{"data": {"conversation": conversation}},
)
)
# Emit the message(s) sent to other users in the room
socketio.emit(
"message",
json,
room=room_id,
include_self=False,
)
if __name__ == "__main__":
socketio.run(app, debug=True)