log and retrieve chat messages

This commit is contained in:
iou1name 2018-06-17 21:10:41 -04:00
parent 35c052350d
commit 67a1b0471a
4 changed files with 32 additions and 7 deletions

View File

@ -84,3 +84,30 @@ def verify_username(username):
return user
else:
return False
def log_chat_message(data):
"""
Logs chat messages into the database.
'data' should be a dict containing: message, date, room_id, name, and
user_id (optional).
"""
message = data["message"]
date = data["date"]
room_id = int(data["room"])
name = data["name"]
user_id = data.get("user_id")
_DB.execute(
"INSERT INTO `chat_messages` (" \
+ "`message`, `room_id`, `date`, `name`, `name_id`) VALUES (" \
+ "%s, %s, %s, %s, %s)", (message, room_id, date, name, user_id))
def get_chat_messages(room_id):
"""
Retrieves all chat messages for the provided room_id.
"""
res = _DB.execute(
"SELECT * FROM `chat_messages` WHERE `room_id` = %s " \
+ "ORDER BY `date` ASC", (room_id,)).fetchall()
return res

View File

@ -28,7 +28,6 @@ def text(data):
room = data["room"]
message = data["message"]
name = data["name"]
date = int(time.time())
data["date"] = date
@ -45,4 +44,5 @@ def text(data):
message = "<br />".join(lines)
data["message"] = message
db.log_chat_message(data)
emit("message", data, room=room)

View File

@ -16,7 +16,7 @@
});
socket.on('message', function(data) {
date = new Date(data.date * 1000);
date_str = date.getFullYear() + '-' + padToTwo(date.getMonth()) + '-' + padToTwo(date.getDay()) + ' ';
date_str = date.getFullYear() + '-' + padToTwo(date.getMonth()+1) + '-' + padToTwo(date.getDate()) + ' ';
date_str += padToTwo(date.getHours()) + ':' + padToTwo(date.getMinutes()) + ':' + padToTwo(date.getSeconds());
msg_str = '<div class="messageHeader">\n<span class="messageName">' + data.name + '</span> ';
@ -57,9 +57,9 @@
{% for message in messages %}
<div class="message">
<div class="messageHeader">
<span class="messageName">{{ message["name"] }}</span> <span class="messageDate">{{ message["date"] | strftime }}</span>
<span class="messageName">{{ message[1] }}</span> <span class="messageDate">{{ message[3] | strftime }}</span>
</div>
<div class="messageMessage">{{ message["message"] }}</div>
<div class="messageMessage">{{ message[4] }}</div>
</div>
{% endfor %}
</div>

View File

@ -63,9 +63,7 @@ def quest(quest_title):
abort(404)
quest_id, quest_title, _, owner_id, quest_data = data
res = db._DB.execute("SELECT * FROM `chat_messages` WHERE `room_id` = '%s'",
(quest_id,))
messages = res.fetchall()
messages = db.get_chat_messages(quest_id)
return render_template('quest.html',
quest_title=quest_title,
quest_body=quest_data,