|
| 1 | +import json |
| 2 | +from datetime import datetime |
| 3 | +from pathlib import Path |
| 4 | + |
| 5 | +from elementary.messages.message_body import MessageBody |
| 6 | +from elementary.messages.messaging_integrations.base_messaging_integration import ( |
| 7 | + BaseMessagingIntegration, |
| 8 | + MessageSendResult, |
| 9 | +) |
| 10 | +from elementary.messages.messaging_integrations.empty_message_context import ( |
| 11 | + EmptyMessageContext, |
| 12 | +) |
| 13 | +from elementary.messages.messaging_integrations.exceptions import ( |
| 14 | + MessagingIntegrationError, |
| 15 | +) |
| 16 | +from elementary.utils.log import get_logger |
| 17 | + |
| 18 | +logger = get_logger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class FileSystemMessagingIntegration( |
| 22 | + BaseMessagingIntegration[str, EmptyMessageContext] |
| 23 | +): |
| 24 | + def __init__(self, directory: str, create_if_missing: bool = True) -> None: |
| 25 | + self.directory = Path(directory).expanduser().resolve() |
| 26 | + self._create_if_missing = create_if_missing |
| 27 | + |
| 28 | + if not self.directory.exists(): |
| 29 | + if self._create_if_missing: |
| 30 | + logger.info( |
| 31 | + f"Creating directory for FileSystemMessagingIntegration: {self.directory}" |
| 32 | + ) |
| 33 | + self.directory.mkdir(parents=True, exist_ok=True) |
| 34 | + else: |
| 35 | + raise MessagingIntegrationError( |
| 36 | + f"Directory {self.directory} does not exist and create_if_missing is False" |
| 37 | + ) |
| 38 | + |
| 39 | + def supports_reply(self) -> bool: |
| 40 | + return False |
| 41 | + |
| 42 | + def send_message( |
| 43 | + self, destination: str, body: MessageBody |
| 44 | + ) -> MessageSendResult[EmptyMessageContext]: |
| 45 | + channel_dir = self.directory / destination |
| 46 | + if not channel_dir.exists(): |
| 47 | + if self._create_if_missing: |
| 48 | + channel_dir.mkdir(parents=True, exist_ok=True) |
| 49 | + else: |
| 50 | + raise MessagingIntegrationError( |
| 51 | + f"Channel directory {channel_dir} does not exist and create_if_missing is False" |
| 52 | + ) |
| 53 | + |
| 54 | + filename = datetime.utcnow().strftime("%Y%m%dT%H%M%S_%fZ.json") |
| 55 | + file_path = channel_dir / filename |
| 56 | + |
| 57 | + try: |
| 58 | + json_str = json.dumps(body.dict(), indent=2) |
| 59 | + file_path.write_text(json_str, encoding="utf-8") |
| 60 | + except Exception as exc: |
| 61 | + logger.error( |
| 62 | + f"Failed to write alert message to file {file_path}: {exc}", |
| 63 | + exc_info=True, |
| 64 | + ) |
| 65 | + raise MessagingIntegrationError( |
| 66 | + f"Failed writing alert message to file {file_path}" |
| 67 | + ) from exc |
| 68 | + |
| 69 | + return MessageSendResult( |
| 70 | + timestamp=datetime.utcnow(), |
| 71 | + message_format="json", |
| 72 | + message_context=EmptyMessageContext(), |
| 73 | + ) |
0 commit comments