30 lines
833 B
Python
30 lines
833 B
Python
import datetime
|
|
import os
|
|
import threading
|
|
from urllib.parse import quote
|
|
|
|
from colony.core.storages.core import Storage, STORAGES_DIR
|
|
|
|
CHAT_DIR = os.path.join(STORAGES_DIR, "chat")
|
|
|
|
|
|
class ChatStorage(Storage):
|
|
_lock = threading.Lock()
|
|
|
|
def __init__(self, storage_dir=None):
|
|
super().__init__(storage_dir or CHAT_DIR)
|
|
|
|
@staticmethod
|
|
def _file(peer_id):
|
|
return quote(peer_id, safe="") + ".json"
|
|
|
|
def messages(self, peer_id):
|
|
return self.open(self._file(peer_id)) or []
|
|
|
|
def append(self, peer_id, direction, text):
|
|
at = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
|
with self._lock:
|
|
messages = self.messages(peer_id)
|
|
messages.append({"direction": direction, "text": text, "at": at})
|
|
self.save(self._file(peer_id), messages)
|