gitscope
← marzneshin / v0.7.2 / app/notification/services.py
https://dev.kronoz.win/r/marzneshin.git
app/notification/services.py · Python
Blame Raw
 1from functools import lru_cache
 2from typing import List
 3from abc import ABC, abstractmethod
 4
 5from app.config.env import TELEGRAM_API_TOKEN, WEBHOOK_ADDRESS
 6from app.models.notification import Notification
 7from app.notification import telegram, webhook
 8
 9
10class BaseNotificationService(ABC):
11    @abstractmethod
12    async def send_notification(self, message: Notification):
13        raise NotImplementedError()
14
15
16class WebhookNotificationService(BaseNotificationService):
17    async def send_notification(self, message: Notification) -> None:
18        await webhook.send_notification(message)
19
20
21class TelegramNotificationService(BaseNotificationService):
22    async def send_notification(self, message: Notification) -> None:
23        await telegram.send_notification(message)
24
25
26class NotificationManager:
27    def __init__(self, strategies: List[BaseNotificationService]) -> None:
28        self.strategies = strategies
29
30    async def send_notification(self, message: Notification) -> None:
31        for strategy in self.strategies:
32            await strategy.send_notification(message)
33
34
35@lru_cache(maxsize=1)
36def get_notification_manager() -> NotificationManager:
37    services = []
38
39    if TELEGRAM_API_TOKEN:
40        services.append(TelegramNotificationService())
41
42    if WEBHOOK_ADDRESS:
43        services.append(WebhookNotificationService())
44
45    if not services:
46        raise ValueError("No notification services provided.")
47
48    return NotificationManager(services)