diff --git a/database.py b/database.py index fe8a9aa..b66b6ef 100644 --- a/database.py +++ b/database.py @@ -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 diff --git a/events.py b/events.py index 47d891b..5263896 100644 --- a/events.py +++ b/events.py @@ -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 = "
".join(lines) data["message"] = message + db.log_chat_message(data) emit("message", data, room=room) diff --git a/templates/quest.html b/templates/quest.html index 4d24f4e..cc118fa 100644 --- a/templates/quest.html +++ b/templates/quest.html @@ -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 = '
\n' + data.name + ' '; @@ -57,9 +57,9 @@ {% for message in messages %}
- {{ message["name"] }} {{ message["date"] | strftime }} + {{ message[1] }} {{ message[3] | strftime }}
-
{{ message["message"] }}
+
{{ message[4] }}
{% endfor %}
diff --git a/views.py b/views.py index 0c3ab9d..f17169b 100644 --- a/views.py +++ b/views.py @@ -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,