38 lines
1.4 KiB
Python
38 lines
1.4 KiB
Python
import socket
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
from planner.models import UserSettings
|
|
|
|
|
|
class NotificationError(Exception):
|
|
"""A delivery error safe to display without exposing the topic URL."""
|
|
|
|
|
|
def send_ntfy_notification(url, title, message, timeout=10):
|
|
request = Request(
|
|
url,
|
|
data=message.encode('utf-8'),
|
|
headers={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
|
|
method='POST',
|
|
)
|
|
try:
|
|
with urlopen(request, timeout=timeout) as response:
|
|
status = response.getcode()
|
|
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, OSError):
|
|
raise NotificationError('Could not connect to the ntfy server.') from None
|
|
if not 200 <= status < 300:
|
|
raise NotificationError(f'ntfy server responded with HTTP {status}.')
|
|
|
|
|
|
def send_notification(user, title, message):
|
|
preferences = UserSettings.objects.filter(user=user).first()
|
|
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
|
|
return False
|
|
send_ntfy_notification(preferences.ntfy_url, title, message)
|
|
return True
|