mirror of
https://github.com/lucaspalomodevelop/Party.git
synced 2026-03-13 00:07:21 +00:00
weird pymongo thing
This commit is contained in:
parent
efcc9fe9ec
commit
98bca3d461
@ -1,4 +1,5 @@
|
||||
from pymongo import MongoClient
|
||||
from pymongo import MongoClient, DESCENDING, ASCENDING
|
||||
from datetime import datetime
|
||||
|
||||
class Chat:
|
||||
CONNECTION_STRING = None
|
||||
@ -16,29 +17,42 @@ class Chat:
|
||||
|
||||
@classmethod
|
||||
def getAllMessages(self)-> list[dict]:
|
||||
messages = self.collection.find().sort('timestamp', -1)
|
||||
messages = self.collection.find().sort('timestamp', DESCENDING)
|
||||
return list(messages)
|
||||
|
||||
@classmethod
|
||||
def insertMessage(self, content: str, author: str, timestamp: str):
|
||||
if not (self.initialized): self.init()
|
||||
message = self.convertToMessage(content, author, timestamp)
|
||||
print(message)
|
||||
print(self.collection)
|
||||
self.collection.insert_one(message)
|
||||
print('inserted message')
|
||||
|
||||
@classmethod
|
||||
def getNextNMessages(self, count: int, skip: int) -> list[dict]:
|
||||
return list(self.collection.find()
|
||||
messages = list(self.collection.find()
|
||||
.skip(skip)
|
||||
.limit(count)
|
||||
.sort('timestamp', -1))
|
||||
.sort('timestamp', DESCENDING))
|
||||
|
||||
return messages
|
||||
|
||||
@classmethod
|
||||
def sortMessages(self, messages: list[dict], order: str) -> list[dict]:
|
||||
if order == 'asc':
|
||||
return sorted(messages, key=lambda message: message['timestamp'])
|
||||
elif order == 'desc':
|
||||
return sorted(messages, key=lambda message: message['timestamp'], reverse=True)
|
||||
else:
|
||||
return messages
|
||||
|
||||
@classmethod
|
||||
def convertToMessage(self, content: str, author: str, timestamp: str) -> dict:
|
||||
message = {
|
||||
'content': content,
|
||||
'text': content,
|
||||
'sender': author,
|
||||
'timestamp': timestamp,
|
||||
'timestamp': str(datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S'))
|
||||
}
|
||||
|
||||
return message
|
||||
|
||||
@ -67,7 +67,7 @@ def api_mate_status():
|
||||
|
||||
@app.route('/api/chat/', methods=['GET'])
|
||||
def api_chat():
|
||||
messages = Chat.getNextNMessages(100, 0) # 0 offset
|
||||
messages = Chat.getNextNMessages(160, 0) # 0 offset
|
||||
response = jsonify(success=True, messages=json_util.dumps(messages))
|
||||
response.status_code = 200
|
||||
return response
|
||||
@ -76,6 +76,7 @@ def api_chat():
|
||||
def handle_chat_message(data):
|
||||
print(data)
|
||||
Chat.insertMessage(data['text'], data['sender'], data['timestamp'])
|
||||
emit('chat-message', data, broadcast=True)
|
||||
|
||||
@socketio.on('chat-get-messages')
|
||||
def handle_chat_get_message(data):
|
||||
|
||||
@ -7,7 +7,7 @@ function getNChatMessages(socket, count, skip) {
|
||||
|
||||
for (let message of data) {
|
||||
console.log(message)
|
||||
message_array.push(buildChatMessage(message.sender, message.text, message.timestamp['$date']));
|
||||
message_array.push(buildChatMessage(message.sender, message.text, message.timestamp));
|
||||
}
|
||||
|
||||
const chatBox = document.getElementById('chatBox');
|
||||
@ -56,11 +56,17 @@ function sendMessage() {
|
||||
const chatInput = document.getElementById('chatInputField');
|
||||
if (chatInput.value.length < 0) return;
|
||||
|
||||
const userName = window.sessionStorage.getItem('name');
|
||||
let userName = window.sessionStorage.getItem('name');
|
||||
if (!userName) {
|
||||
userName = 'Peter';
|
||||
}
|
||||
|
||||
const messageDate = new Date();
|
||||
const dt = new Date();
|
||||
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
|
||||
|
||||
const message = { sender: userName, text: chatInput.value, timestamp: messageDate };
|
||||
const dateStr = `${ dt.getFullYear()}-${ padL(dt.getMonth()+1)}-${ padL(dt.getDate())} ${ padL(dt.getHours())}:${ padL(dt.getMinutes())}:${ padL(dt.getSeconds())}`; // magic date formatter
|
||||
|
||||
const message = { sender: userName, text: chatInput.value, timestamp: dateStr };
|
||||
|
||||
console.log(message);
|
||||
|
||||
@ -72,6 +78,10 @@ function sendMessage() {
|
||||
|
||||
socket.on('chat-message', (data) => {
|
||||
const chatBox = document.getElementById('chatBox');
|
||||
chatBox.appendChild(buildChatMessage(data.sender, data.text, data.timestamp['$date'])); // $date is mongodb date
|
||||
console.log(data);
|
||||
// check if sender is given
|
||||
let message = buildChatMessage(data.sender, data.text, data.timestamp); // $date is mongodb date
|
||||
console.log(data.timestamp);
|
||||
chatBox.appendChild(message);
|
||||
chatBox.scrollTop = chatBox.scrollHeight;
|
||||
});
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
from datetime import datetime, timedelta
|
||||
from faker import Faker
|
||||
import pymongo
|
||||
|
||||
@ -10,14 +11,19 @@ def get_connection():
|
||||
|
||||
connection = get_connection()
|
||||
|
||||
def generate_message():
|
||||
fmt = '%Y-%m-%d %H:%M:%S'
|
||||
now = datetime.now()
|
||||
|
||||
def generate_message(i: int):
|
||||
date = now - timedelta(days=i)
|
||||
date = date.strftime(fmt)
|
||||
message = {
|
||||
'sender': fake.name(),
|
||||
'text': fake.sentence() * 2,
|
||||
'timestamp': fake.date_time_this_year()
|
||||
'text': fake.sentence() + ' ' + fake.sentence(),
|
||||
'timestamp': date
|
||||
}
|
||||
connection.insert_one(message)
|
||||
|
||||
MESSAGE_COUNT = 1000
|
||||
MESSAGE_COUNT = 150
|
||||
for i in range(MESSAGE_COUNT):
|
||||
generate_message()
|
||||
generate_message(i)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user