"""Small reusable notification helpers for project notification providers.""" import socket from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen class NotificationError(Exception): """A safe, user-displayable notification delivery failure.""" def send_ntfy_notification(url, title, message, timeout=10): """Publish a plain-text notification to an ntfy topic URL.""" request = Request( url, data=message.encode("utf-8"), headers={"Content-Type": "text/plain; charset=utf-8", "Title": title}, method="POST", ) try: response = urlopen(request, timeout=timeout) status_code = response.getcode() response.close() except HTTPError as error: raise NotificationError(f"ntfy server responded with HTTP {error.code}.") from error except (TimeoutError, socket.timeout): raise NotificationError("Connection to the ntfy server timed out.") from None except URLError as error: if isinstance(error.reason, (TimeoutError, socket.timeout)): raise NotificationError("Connection to the ntfy server timed out.") from error raise NotificationError("Could not connect to the ntfy server.") from error except OSError as error: raise NotificationError("Could not connect to the ntfy server.") from error if not 200 <= status_code < 300: raise NotificationError(f"ntfy server responded with HTTP {status_code}.") return True def send_notification(user, title, message): """Send through the user's enabled provider, or safely do nothing.""" from members.models import UserSettings try: settings = UserSettings.objects.get(user=user) except UserSettings.DoesNotExist: return False if not settings.ntfy_enabled or not settings.ntfy_url: return False send_ntfy_notification(settings.ntfy_url, title, message) return True