Add retry-safe scan completion notifications
This commit is contained in:
@@ -9,11 +9,14 @@ class NotificationError(Exception):
|
||||
"""A delivery error safe to display without exposing the topic URL."""
|
||||
|
||||
|
||||
def send_ntfy_notification(url, title, message, timeout=10):
|
||||
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={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
|
||||
headers=headers,
|
||||
method='POST',
|
||||
)
|
||||
try:
|
||||
@@ -29,9 +32,9 @@ def send_ntfy_notification(url, title, message, timeout=10):
|
||||
raise NotificationError(f'ntfy server responded with HTTP {status}.')
|
||||
|
||||
|
||||
def send_notification(user, title, message):
|
||||
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)
|
||||
send_ntfy_notification(preferences.ntfy_url, title, message, sequence_id=sequence_id)
|
||||
return True
|
||||
|
||||
@@ -5,7 +5,7 @@ from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import UserSettings
|
||||
from .services.notifications import NotificationError, send_notification
|
||||
from .services.notifications import NotificationError, send_notification, send_ntfy_notification
|
||||
|
||||
|
||||
class NtfySettingsTests(TestCase):
|
||||
@@ -47,3 +47,15 @@ class NtfySettingsTests(TestCase):
|
||||
def test_disabled_preference_suppresses_delivery(self, sender):
|
||||
self.assertFalse(send_notification(self.user, 'Title', 'Message'))
|
||||
sender.assert_not_called()
|
||||
|
||||
@patch('planner.services.notifications.urlopen')
|
||||
def test_send_ntfy_notification_includes_stable_sequence_id(self, urlopen):
|
||||
response = Mock()
|
||||
response.getcode.return_value = 200
|
||||
urlopen.return_value.__enter__.return_value = response
|
||||
|
||||
send_ntfy_notification(self.topic, 'Title', 'Message', sequence_id='inventory-scan-123')
|
||||
|
||||
request = urlopen.call_args.args[0]
|
||||
headers = {key.lower(): value for key, value in request.header_items()}
|
||||
self.assertEqual(headers['x-sequence-id'], 'inventory-scan-123')
|
||||
|
||||
Reference in New Issue
Block a user