ungana

Unnamed repository; edit this file 'description' to name the repository.
Info | Log | Files | Refs | README

commit 0a95a8a2bef159c55da7aa97865d962bfed294e6
parent dc666df7747f7aefdb2ee89a08e4cfc8fd303977
Author: Carlosokumu <carlosokumu254@gmail.com>
Date:   Tue, 19 Aug 2025 14:49:51 +0300

add an AttachmentManager that:
- creates attachment
- validates attachment file type according to ctx rules.
- returns a SHA256 digest of the file content.

Diffstat:
Acalendarapp/attachment/attachment_manager.py | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 51 insertions(+), 0 deletions(-)

diff --git a/calendarapp/attachment/attachment_manager.py b/calendarapp/attachment/attachment_manager.py @@ -0,0 +1,50 @@ +import os +import hashlib +import mimetypes + +class AttachmentManager: + def __init__(self): + pass + + def create_attachment(self, file_path: str, ctx: str): + if not os.path.exists(file_path): + raise FileNotFoundError(f"Attachment file not found: {file_path}") + if not os.access(file_path, os.R_OK): + raise PermissionError(f"Cannot read attachment file: {file_path}") + + self.validate(file_path, ctx) + digest = self.digest(file_path) + + mime_type, _ = mimetypes.guess_type(file_path) + if not mime_type: + raise ValueError(f"Cannot determine MIME type of {file_path}") + + value = f"sha256:{digest}" + params = { + "FMTTYPE": mime_type, + "CTX": ctx, + } + return ("ATTACH", value, params) + + + + def validate(self, file_path: str, ctx: str) -> None: + """Validate attachment file type according to ctx rules.""" + if not os.path.isfile(file_path): + raise FileNotFoundError(f"Attachment file not found: {file_path}") + + mime_type, _ = mimetypes.guess_type(file_path) + + if ctx == "poster" and not (mime_type and mime_type.startswith("image/")): + raise ValueError(f"Poster must be an image file, got {mime_type}") + + if ctx == "long" and not (mime_type and mime_type.startswith("text/")): + raise ValueError(f"Long attachment must be a text file, got {mime_type}") + + def digest(self, file_path: str) -> str: + """Return SHA256 digest of the file content.""" + h = hashlib.sha256() + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(4096), b""): + h.update(chunk) + return h.hexdigest() +\ No newline at end of file