From 694b1934acf8704456ec0052b730b037363cdb7e Mon Sep 17 00:00:00 2001 From: KKlochko Date: Thu, 14 Dec 2023 15:36:08 +0200 Subject: [PATCH] Add saving of notifications to the directory. --- notification_client/client.py | 7 +++++- notification_client/notification_saver.py | 26 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 notification_client/notification_saver.py diff --git a/notification_client/client.py b/notification_client/client.py index a0f1e7e..c70f53f 100644 --- a/notification_client/client.py +++ b/notification_client/client.py @@ -24,14 +24,17 @@ import sys from notification_client.MessagePrinter import MessagePrinter from notification_client.notitication import Notification from notification_client.timestamp import Timestamp +from notification_client.notification_saver import NotificationSaver class Client: BUFFER_SIZE = 1024 + NOTIFICATION_DIR = 'notifications' - def __init__(self, ip: str, port: int): + def __init__(self, ip: str, port: int, notification_dir: str = 'notifications'): self.__ip = ip self.__port = port + self.NOTIFICATION_DIR = notification_dir async def connect(self): try: @@ -62,6 +65,8 @@ class Client: Notification.notify(title, message) + NotificationSaver.save_notification(self.NOTIFICATION_DIR, title, message, now) + except asyncio.CancelledError: print('Something went wrong') finally: diff --git a/notification_client/notification_saver.py b/notification_client/notification_saver.py new file mode 100644 index 0000000..964656f --- /dev/null +++ b/notification_client/notification_saver.py @@ -0,0 +1,26 @@ +from datetime import datetime +import os + + +class NotificationSaver: + @staticmethod + def create_folders_if_needed(path): + os.makedirs(path, exist_ok=True) + + @staticmethod + def get_date_folder(base_dir='notifications'): + date = str(datetime.now().date()) + return os.path.join(base_dir, date) + + @staticmethod + def save_notification(base_dir, title, message, timestamp) -> bool: + dirname = NotificationSaver.get_date_folder(base_dir) + filename = f'{title}_{timestamp}.md' + + full_file_name = os.path.join(dirname, filename) + full_folder_name = os.path.dirname(full_file_name) + NotificationSaver.create_folders_if_needed(full_folder_name) + + with open(full_file_name, 'w') as file: + file.write(message) +