41 lines
1.5 KiB
Python
41 lines
1.5 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, sequence_id=None):
|
|
headers = {'Content-Type': 'text/plain; charset=utf-8', 'Title': title}
|
|
if sequence_id:
|
|
headers['X-Sequence-ID'] = str(sequence_id)[:64]
|
|
request = Request(
|
|
url,
|
|
data=message.encode('utf-8'),
|
|
headers=headers,
|
|
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, *, sequence_id=None):
|
|
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, sequence_id=sequence_id)
|
|
return True
|