added compass direction finding
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+14
-2
@@ -1,8 +1,20 @@
|
||||
from django import forms
|
||||
from .models import Member
|
||||
from .models import Member, UserSettings
|
||||
|
||||
class MemberForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Member
|
||||
fields = ["first_name", "last_name", "phone"]
|
||||
|
||||
|
||||
|
||||
|
||||
class UserSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ["ntfy_url", "ntfy_enabled"]
|
||||
widgets = {
|
||||
"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"}),
|
||||
}
|
||||
|
||||
def clean_ntfy_url(self):
|
||||
return self.cleaned_data["ntfy_url"].strip()
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 07:38
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('members', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ntfy_url', models.URLField(blank=True)),
|
||||
('ntfy_enabled', models.BooleanField(default=False)),
|
||||
('ntfy_last_tested_at', models.DateTimeField(blank=True, null=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='notification_settings', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'User settings',
|
||||
'verbose_name_plural': 'User settings',
|
||||
},
|
||||
),
|
||||
]
|
||||
Binary file not shown.
+17
-1
@@ -1,3 +1,4 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
@@ -8,4 +9,19 @@ class Member(models.Model):
|
||||
joined_date = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.first_name} {self.last_name}"
|
||||
return f"{self.first_name} {self.last_name}"
|
||||
|
||||
class UserSettings(models.Model):
|
||||
"""Per-user configuration for optional notification providers."""
|
||||
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_settings")
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = "User settings"
|
||||
verbose_name_plural = "User settings"
|
||||
|
||||
def __str__(self):
|
||||
return f"Notification settings for {self.user}"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.user_settings, name="user_settings"),
|
||||
path("notifications/ntfy/test/", views.test_ntfy_notification, name="ntfy_test_notification"),
|
||||
]
|
||||
@@ -0,0 +1,29 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Sign in · Sound Signal</title>
|
||||
<style>body{min-width:320px;min-height:100vh;display:grid;place-items:center;margin:0;padding:1.5rem;color:#eef3ff;font-family:Inter,system-ui,sans-serif;background:radial-gradient(circle at 8% 0,#263a76,transparent 31rem),#090e1d}.card{width:min(100%,27rem);padding:2rem;border:1px solid #2b3d68;border-radius:1.25rem;background:#172443;box-shadow:0 1.75rem 5rem #01030c99}h1{margin:.5rem 0}.intro{color:#aab9d8;line-height:1.5}.error{margin:1rem 0;padding:.75rem;border-radius:.6rem;color:#fee2e2;background:#7f1d1d}label{display:block;margin:1rem 0 .35rem;font-weight:700}input{width:100%;min-height:2.8rem;padding:.65rem;border:1px solid #526b9f;border-radius:.55rem;color:#eef3ff;font:inherit;background:#0a1123}button{width:100%;min-height:2.9rem;margin-top:1.5rem;border:0;border-radius:.65rem;color:#17132b;font:inherit;font-weight:850;background:linear-gradient(135deg,#99c8ff,#c6adff);cursor:pointer}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<p>✦ Sound Signal</p>
|
||||
<h1>Sign in</h1>
|
||||
<p class="intro">Sign in to manage your notification settings.</p>
|
||||
{% if form.errors %}
|
||||
<div class="error">Your username and password did not match. Please try again.</div>
|
||||
{% endif %}
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<label for="{{ form.username.id_for_label }}">Username</label>
|
||||
{{ form.username }}
|
||||
<label for="{{ form.password.id_for_label }}">Password</label>
|
||||
{{ form.password }}
|
||||
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
<p class="intro">You will return to the page you requested.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
|
||||
@@ -0,0 +1,32 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Settings · Sound Signal</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
<style>body{min-width:320px;margin:0;padding:2rem;color:#eef3ff;font-family:Inter,system-ui,sans-serif;background:#090e1d}.card{width:min(100%,42rem);margin:auto;padding:2rem;border:1px solid #2b3d68;border-radius:1rem;background:#172443}h1{margin-top:0}h2{margin:0}.intro,.help{color:#aab9d8;line-height:1.5}.section{margin-top:2rem;padding-top:1.5rem;border-top:1px solid #2b3d68}label{display:block;margin:.9rem 0 .35rem;font-weight:700}input[type=url]{width:100%;min-height:2.8rem;padding:.65rem;border:1px solid #526b9f;border-radius:.55rem;color:#eef3ff;font:inherit;background:#0a1123}.check{display:flex;gap:.6rem;align-items:center}.check label{margin:0}.button{min-height:2.8rem;margin-top:1rem;padding:.6rem 1rem;border:0;border-radius:.55rem;color:#17132b;font:inherit;font-weight:800;background:#a6ccff;cursor:pointer}.button--secondary{margin-right:.7rem;background:#d8c1fb}.alert,.errorlist{margin-top:1rem;padding:.75rem;border-radius:.55rem}.alert--success{color:#d1fae5;background:#14532d}.alert--error,.errorlist{color:#fee2e2;background:#7f1d1d}.messages{padding:0;list-style:none}@media(max-width:32rem){body{padding:1rem}.card{padding:1.4rem}}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Settings</h1>
|
||||
<p class="intro">Manage personal notification preferences.</p>
|
||||
{% if messages %}<ul class="messages">{% for message in messages %}<li class="alert alert--success">{{ message }}</li>{% endfor %}</ul>{% endif %}
|
||||
<form method="post" action="{% url 'user_settings' %}">
|
||||
{% csrf_token %}
|
||||
<section class="section" aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p class="help">Use a topic URL from your ntfy server. Test the current URL before saving it.</p>
|
||||
<label for="ntfy-url">Topic URL</label>
|
||||
{{ form.ntfy_url }}
|
||||
{{ form.ntfy_url.errors }}
|
||||
<div class="check">{{ form.ntfy_enabled }}<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label></div>
|
||||
<button class="button button--secondary" type="button" hx-post="{% url 'ntfy_test_notification' %}" hx-include="#ntfy-url, [name='csrfmiddlewaretoken']" hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
|
||||
<div id="ntfy-test-result" aria-live="polite"></div>
|
||||
</section>
|
||||
<button class="button" type="submit">Save settings</button>
|
||||
</form>
|
||||
</main>
|
||||
<script>document.querySelector("#ntfy-url").addEventListener("input", () => { document.querySelector("#ntfy-test-result").replaceChildren(); });</script>
|
||||
</body>
|
||||
</html>
|
||||
+163
-2
@@ -1,3 +1,164 @@
|
||||
from django.test import TestCase
|
||||
from socket import timeout as SocketTimeout
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
# Create your tests here.
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from notifications.services import NotificationError, send_notification, send_ntfy_notification
|
||||
|
||||
from .models import UserSettings
|
||||
|
||||
|
||||
|
||||
class NtfyNotificationServiceTests(SimpleTestCase):
|
||||
@patch("notifications.services.urlopen")
|
||||
def test_posts_a_title_and_message_to_the_topic_url(self, mock_urlopen):
|
||||
response = MagicMock()
|
||||
response.getcode.return_value = 200
|
||||
mock_urlopen.return_value = response
|
||||
|
||||
self.assertTrue(send_ntfy_notification("https://ntfy.example.com/private-topic", "Fireworks Detector", "Test message"))
|
||||
|
||||
request = mock_urlopen.call_args.args[0]
|
||||
self.assertEqual(request.get_method(), "POST")
|
||||
self.assertEqual(request.data, b"Test message")
|
||||
self.assertEqual(request.get_header("Title"), "Fireworks Detector")
|
||||
|
||||
@patch("notifications.services.urlopen", side_effect=HTTPError("https://ntfy.example.com/topic", 503, "Unavailable", None, None))
|
||||
def test_non_success_http_response_is_a_safe_failure(self, mock_urlopen):
|
||||
with self.assertRaisesMessage(NotificationError, "HTTP 503"):
|
||||
send_ntfy_notification("https://ntfy.example.com/topic", "Title", "Message")
|
||||
|
||||
@patch("notifications.services.urlopen", side_effect=URLError(SocketTimeout()))
|
||||
def test_timeout_is_a_safe_failure(self, mock_urlopen):
|
||||
with self.assertRaisesMessage(NotificationError, "timed out"):
|
||||
send_ntfy_notification("https://ntfy.example.com/topic", "Title", "Message")
|
||||
|
||||
|
||||
class UserSettingsNtfyTests(TestCase):
|
||||
url = "https://ntfy.example.com/private-topic"
|
||||
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="first-user", password="secret")
|
||||
self.other_user = get_user_model().objects.create_user(username="other-user", password="secret")
|
||||
self.client.force_login(self.user)
|
||||
|
||||
def test_test_endpoint_requires_login(self):
|
||||
self.client.logout()
|
||||
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 302)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_invalid_url_is_rejected_without_sending(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": "not a URL"})
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "valid HTTP or HTTPS", status_code=400)
|
||||
mock_send.assert_not_called()
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_successful_test_returns_inline_success_and_marks_current_url_in_session(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test notification sent successfully")
|
||||
mock_send.assert_called_once_with(
|
||||
self.url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
)
|
||||
|
||||
@patch("members.views.send_ntfy_notification", side_effect=NotificationError("Connection to the ntfy server timed out."))
|
||||
def test_delivery_failure_returns_an_inline_safe_error(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 502)
|
||||
self.assertContains(response, "timed out", status_code=502)
|
||||
|
||||
def test_user_cannot_save_an_untested_url(self):
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
settings = UserSettings.objects.get(user=self.user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
self.assertEqual(settings.ntfy_url, "")
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_successfully_tested_url_can_be_saved(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertRedirects(response, reverse("user_settings"))
|
||||
settings = UserSettings.objects.get(user=self.user)
|
||||
self.assertEqual(settings.ntfy_url, self.url)
|
||||
self.assertTrue(settings.ntfy_enabled)
|
||||
self.assertIsNotNone(settings.ntfy_last_tested_at)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_changing_the_url_requires_another_successful_test(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
changed_url = "https://ntfy.example.com/another-topic"
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": changed_url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).ntfy_url, self.url)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_one_users_successful_test_cannot_authorize_another_users_settings(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
self.client.force_login(self.other_user)
|
||||
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
settings = UserSettings.objects.get(user=self.other_user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
|
||||
@patch("notifications.services.send_ntfy_notification")
|
||||
def test_reusable_sender_only_delivers_for_enabled_user_settings(self, mock_send):
|
||||
self.assertFalse(send_notification(self.user, "Title", "Message"))
|
||||
UserSettings.objects.create(user=self.user, ntfy_url=self.url, ntfy_enabled=True)
|
||||
|
||||
self.assertTrue(send_notification(self.user, "Title", "Message"))
|
||||
mock_send.assert_called_once_with(self.url, "Title", "Message")
|
||||
|
||||
|
||||
class FrontendAuthenticationTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="profile-user", password="secret")
|
||||
|
||||
def test_frontend_login_page_is_available(self):
|
||||
response = self.client.get(reverse("login"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Sign in")
|
||||
self.assertContains(response, "csrfmiddlewaretoken")
|
||||
|
||||
def test_frontend_login_authenticates_and_returns_home(self):
|
||||
response = self.client.post(reverse("login"), {"username": "profile-user", "password": "secret"})
|
||||
|
||||
self.assertRedirects(response, "/")
|
||||
|
||||
def test_protected_settings_redirects_to_frontend_login(self):
|
||||
response = self.client.get(reverse("user_settings"))
|
||||
|
||||
self.assertRedirects(response, "/login/?next=/settings/")
|
||||
|
||||
def test_profile_circle_is_visible_only_for_authenticated_users(self):
|
||||
anonymous_response = self.client.get(reverse("hello"))
|
||||
self.assertNotContains(anonymous_response, "class=\"profile-circle\"")
|
||||
|
||||
self.client.force_login(self.user)
|
||||
authenticated_response = self.client.get(reverse("hello"))
|
||||
self.assertContains(authenticated_response, "class=\"profile-circle\"")
|
||||
self.assertContains(authenticated_response, reverse("user_settings"))
|
||||
|
||||
+85
-3
@@ -1,6 +1,16 @@
|
||||
from hashlib import sha256
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.shortcuts import render, redirect
|
||||
from .forms import MemberForm
|
||||
from .models import Member
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from notifications.services import NotificationError, send_ntfy_notification
|
||||
from .forms import MemberForm, UserSettingsForm
|
||||
from .models import Member, UserSettings
|
||||
|
||||
def member_create(request):
|
||||
if request.method == "POST":
|
||||
@@ -32,4 +42,76 @@ def hello_form(request):
|
||||
else:
|
||||
message = "Please enter your name."
|
||||
|
||||
return render(request, "hello-form.html", {"message": message})
|
||||
return render(request, "hello-form.html", {"message": message})
|
||||
|
||||
NTFY_TEST_SESSION_PREFIX = "ntfy_tested_url_fingerprint"
|
||||
|
||||
|
||||
def _validated_ntfy_url(value):
|
||||
url = value.strip()
|
||||
if not url:
|
||||
raise ValidationError("Enter an ntfy topic URL.")
|
||||
URLValidator(schemes=["http", "https"])(url)
|
||||
return url
|
||||
|
||||
|
||||
def _ntfy_test_session_key(user):
|
||||
return f"{NTFY_TEST_SESSION_PREFIX}:{user.pk}"
|
||||
|
||||
|
||||
def _url_fingerprint(url):
|
||||
return sha256(url.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@login_required
|
||||
def user_settings(request):
|
||||
settings, _ = UserSettings.objects.get_or_create(user=request.user)
|
||||
saved_ntfy_url = settings.ntfy_url
|
||||
if request.method == "POST":
|
||||
form = UserSettingsForm(request.POST, instance=settings)
|
||||
if form.is_valid():
|
||||
url = form.cleaned_data["ntfy_url"]
|
||||
tested_fingerprint = request.session.get(_ntfy_test_session_key(request.user))
|
||||
was_previously_tested = saved_ntfy_url == url and settings.ntfy_last_tested_at is not None
|
||||
if url and tested_fingerprint != _url_fingerprint(url) and not was_previously_tested:
|
||||
form.add_error("ntfy_url", "Test this URL successfully before saving notification settings.")
|
||||
else:
|
||||
settings = form.save(commit=False)
|
||||
if not url:
|
||||
settings.ntfy_enabled = False
|
||||
settings.ntfy_last_tested_at = None
|
||||
elif tested_fingerprint == _url_fingerprint(url):
|
||||
settings.ntfy_last_tested_at = timezone.now()
|
||||
settings.save()
|
||||
request.session.pop(_ntfy_test_session_key(request.user), None)
|
||||
messages.success(request, "Notification settings saved.")
|
||||
return redirect("user_settings")
|
||||
else:
|
||||
form = UserSettingsForm(instance=settings)
|
||||
return render(request, "members/user_settings.html", {"form": form})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def test_ntfy_notification(request):
|
||||
try:
|
||||
url = _validated_ntfy_url(request.POST.get("ntfy_url", ""))
|
||||
except ValidationError:
|
||||
return render(
|
||||
request,
|
||||
"members/ntfy_test_result.html",
|
||||
{"error": "Enter a valid HTTP or HTTPS ntfy topic URL."},
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
send_ntfy_notification(
|
||||
url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
)
|
||||
except NotificationError as error:
|
||||
return render(request, "members/ntfy_test_result.html", {"error": str(error)}, status=502)
|
||||
|
||||
request.session[_ntfy_test_session_key(request.user)] = _url_fingerprint(url)
|
||||
return render(request, "members/ntfy_test_result.html", {"success": True})
|
||||
|
||||
Reference in New Issue
Block a user