latest changes before manual submissions redesign

This commit is contained in:
Joren de Graaf
2026-10-06 19:31:30 +02:00
parent 46ad514a70
commit c13a405d96
124 changed files with 1023 additions and 112 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
View File
@@ -0,0 +1,37 @@
import logging
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils import translation
from django.utils.translation import gettext as _
from members.models import PendingNotificationBatch, UserSettings
from notifications.services import NotificationError, send_notification
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Send one ntfy summary per user for each completed minute of Pending arrivals."
def handle(self, *args, **options):
current_minute = timezone.now().replace(second=0, microsecond=0)
batches = PendingNotificationBatch.objects.filter(minute__lt=current_minute).select_related("user").order_by("minute", "pk")
for batch in batches.iterator():
if not UserSettings.objects.filter(user=batch.user, ntfy_enabled=True).exclude(ntfy_url="").exists():
batch.delete()
continue
try:
with translation.override(batch.user.notification_settings.preferred_language):
parts = []
if batch.manual_count:
parts.append(_("%(count)d manual") % {"count": batch.manual_count})
if batch.sensor_count:
parts.append(_("%(count)d sensor") % {"count": batch.sensor_count})
total = batch.manual_count + batch.sensor_count
message = _("%(count)d new Pending event(s): %(sources)s.") % {"count": total, "sources": ", ".join(parts)}
send_notification(batch.user, _("Pending events"), message)
except NotificationError as error:
logger.warning("Could not send Pending notification for user %s: %s", batch.user_id, error)
continue
batch.delete()
@@ -0,0 +1,27 @@
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("members", "0003_usersettings_preferred_language"),
]
operations = [
migrations.CreateModel(
name="PendingNotificationBatch",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("minute", models.DateTimeField()),
("manual_count", models.PositiveIntegerField(default=0)),
("sensor_count", models.PositiveIntegerField(default=0)),
("user", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddConstraint(
model_name="pendingnotificationbatch",
constraint=models.UniqueConstraint(fields=("user", "minute"), name="unique_pending_notification_minute"),
),
]
+12
View File
@@ -29,3 +29,15 @@ class UserSettings(models.Model):
def __str__(self):
return _("Settings for %(user)s") % {"user": self.user}
class PendingNotificationBatch(models.Model):
"""One minute of new Pending events for one notification recipient."""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
minute = models.DateTimeField()
manual_count = models.PositiveIntegerField(default=0)
sensor_count = models.PositiveIntegerField(default=0)
class Meta:
constraints = [models.UniqueConstraint(fields=["user", "minute"], name="unique_pending_notification_minute")]
+33 -1
View File
@@ -19,13 +19,33 @@ def owned_sensor(request, pk):
return get_object_or_404(Sensor, pk=pk, owner=request.user, archived_at__isnull=True)
def is_htmx(request):
return request.headers.get("HX-Request") == "true"
def render_sensor_list(request):
return render(request, "members/partials/sensor_list.html", {
"sensors": Sensor.objects.filter(owner=request.user, archived_at__isnull=True),
})
def render_sensor(request, sensor, form=None, token=None):
return render(request, "members/sensor_manage.html", {
response = render(request, "members/partials/sensor_detail.html" if is_htmx(request) else "members/sensor_manage.html", {
"sensor": sensor,
"form": form or SensorForm(instance=sensor),
"token": token,
"heartbeat": sensor.heartbeat_status(),
})
if token:
response["Cache-Control"] = "no-store"
return response
@login_required
def sensor_list(request):
if is_htmx(request):
return render_sensor_list(request)
return redirect("user_settings")
@login_required
@@ -35,6 +55,8 @@ def create_sensor(request):
form = SensorForm(request.POST)
if not form.is_valid():
messages.error(request, _("Enter a valid sensor name. Names must be unique."))
if is_htmx(request):
return render_sensor_list(request)
return redirect("user_settings")
sensor = form.save(commit=False)
sensor.owner = request.user
@@ -57,6 +79,8 @@ def rename_sensor(request, pk):
if form.is_valid():
form.save()
messages.success(request, _("Sensor renamed."))
if is_htmx(request):
return render_sensor(request, sensor)
return redirect("manage_sensor", pk=pk)
return render_sensor(request, sensor, form=form)
@@ -67,6 +91,8 @@ def toggle_sensor(request, pk):
sensor = owned_sensor(request, pk)
sensor.is_active = not sensor.is_active
sensor.save(update_fields=["is_active"])
if is_htmx(request):
return render_sensor(request, sensor)
return redirect("manage_sensor", pk=pk)
@@ -77,6 +103,8 @@ def rotate_sensor(request, pk):
sensor = owned_sensor(request, pk)
if request.POST.get("confirm") != "rotate":
messages.error(request, _("Confirm token rotation first."))
if is_htmx(request):
return render_sensor(request, sensor)
return redirect("manage_sensor", pk=pk)
token = sensor.issue_token()
return render_sensor(request, sensor, token=token)
@@ -88,7 +116,11 @@ def remove_sensor(request, pk):
sensor = owned_sensor(request, pk)
if request.POST.get("confirm") != "remove":
messages.error(request, _("Confirm sensor removal first."))
if is_htmx(request):
return render_sensor(request, sensor)
return redirect("manage_sensor", pk=pk)
sensor.archive()
messages.success(request, _("Sensor removed. Historical events were preserved."))
if is_htmx(request):
return render_sensor_list(request)
return redirect("user_settings")
+1
View File
@@ -8,6 +8,7 @@ urlpatterns = [
path("", views.user_settings, name="user_settings"),
path("notifications/ntfy/test/", views.test_ntfy_notification, name="ntfy_test_notification"),
path("sensors/create/", sensor_views.create_sensor, name="create_sensor"),
path("sensors/", sensor_views.sensor_list, name="sensor_list"),
path("sensors/<int:pk>/", sensor_views.manage_sensor, name="manage_sensor"),
path("sensors/<int:pk>/rename/", sensor_views.rename_sensor, name="rename_sensor"),
path("sensors/<int:pk>/toggle/", sensor_views.toggle_sensor, name="toggle_sensor"),
+1
View File
@@ -24,6 +24,7 @@
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
<button type="submit">{% trans "Sign in" %}</button>
</form>
<p class="intro">{% trans "New here?" %} <a href="{% url 'register' %}{% if next %}?next={{ next|urlencode }}{% endif %}">{% trans "Create an account" %}</a></p>
<p class="intro">{% trans "You will return to the page you requested." %}</p>
</main>
</body>
@@ -0,0 +1,50 @@
{% load i18n %}
<div class="sensor-detail">
<div class="sensor-detail__header">
<div><p class="eyebrow">{% trans "Sensor settings" %}</p><h2 id="sensors-title">{{ sensor.name }}</h2></div>
<a class="sensor-close" href="{% url 'user_settings' %}" hx-get="{% url 'sensor_list' %}" hx-target="#sensor-card-content" hx-swap="innerHTML" aria-label="{% trans 'Close sensor settings' %}"><span aria-hidden="true">×</span> {% trans "Close" %}</a>
</div>
{% if messages %}<ul class="messages sensor-messages" role="status">{% for message in messages %}<li class="alert {% if message.tags == 'error' %}alert--error{% else %}alert--success{% endif %}">{{ message }}</li>{% endfor %}</ul>{% endif %}
{% if token %}<section class="token-once" aria-label="{% trans 'New API token' %}">
<strong>{% trans "Copy this token now. For security reasons it will not be shown again." %}</strong>
<code id="sensor-token">{{ token }}</code>
<button class="button button--secondary" type="button" data-copy-sensor-token>{% trans "Copy token" %}</button>
</section>{% endif %}
<section class="sensor-detail__overview" aria-label="{% trans 'Sensor overview' %}">
{% with status=heartbeat %}<span class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</span>{% endwith %}
<dl class="sensor-detail__facts">
<div><dt>{% trans "Last heartbeat" %}</dt><dd>{{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Last submission" %}</dt><dd>{{ sensor.last_submission|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Token prefix" %}</dt><dd><code>{{ sensor.token_prefix|default:"—" }}</code></dd></div>
<div><dt>{% trans "Created" %}</dt><dd>{{ sensor.created_at|date:"j M Y, H:i" }}</dd></div>
</dl>
</section>
<div class="sensor-detail__actions">
<section class="sensor-detail__section"><h3>{% trans "Rename" %}</h3>
<form class="settings-form" method="post" action="{% url 'rename_sensor' sensor.pk %}" hx-post="{% url 'rename_sensor' sensor.pk %}" hx-target="#sensor-card-content" hx-swap="innerHTML">{% csrf_token %}
<div class="field"><label for="id_name">{% trans "Device name" %}</label>{{ form.name }}{{ form.name.errors }}</div>
<button class="button" type="submit">{% trans "Save name" %}</button>
</form>
</section>
<section class="sensor-detail__section"><h3>{% trans "Device access" %}</h3>
<p class="help">{% if sensor.is_active %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}</p>
<form method="post" action="{% url 'toggle_sensor' sensor.pk %}" hx-post="{% url 'toggle_sensor' sensor.pk %}" hx-target="#sensor-card-content" hx-swap="innerHTML">{% csrf_token %}
<button class="button button--secondary" type="submit">{% if sensor.is_active %}{% trans "Disable sensor" %}{% else %}{% trans "Enable sensor" %}{% endif %}</button>
</form>
</section>
<section class="sensor-detail__section"><h3>{% trans "Reissue API token" %}</h3>
<p class="help">{% trans "The old token will immediately stop authenticating." %}</p>
<form method="post" action="{% url 'rotate_sensor' sensor.pk %}" hx-post="{% url 'rotate_sensor' sensor.pk %}" hx-target="#sensor-card-content" hx-swap="innerHTML">{% csrf_token %}
<label class="sensor-confirm"><input type="checkbox" name="confirm" value="rotate" required>{% trans "I understand the old token will stop working" %}</label>
<button class="button button--secondary" type="submit">{% trans "Reissue token" %}</button>
</form>
</section>
<section class="sensor-detail__section"><h3>{% trans "Remove sensor" %}</h3>
<p class="help">{% trans "This disables the device and revokes its token. Historical events remain linked to it." %}</p>
<form method="post" action="{% url 'remove_sensor' sensor.pk %}" hx-post="{% url 'remove_sensor' sensor.pk %}" hx-target="#sensor-card-content" hx-swap="innerHTML">{% csrf_token %}
<label class="sensor-confirm"><input type="checkbox" name="confirm" value="remove" required>{% trans "I understand this device will be removed" %}</label>
<button class="button button--danger" type="submit">{% trans "Remove sensor" %}</button>
</form>
</section>
</div>
</div>
@@ -0,0 +1,27 @@
{% load i18n %}
<div class="sensor-list__intro"><div><p class="eyebrow">{% trans "Connected devices" %}</p><h2 id="sensors-title">{% trans "My sensors" %}</h2><p class="help">{% trans "Manage the devices that authenticate with BoomCast." %}</p></div></div>
{% if messages %}<ul class="messages sensor-messages" role="status">{% for message in messages %}<li class="alert {% if message.tags == 'error' %}alert--error{% else %}alert--success{% endif %}">{{ message }}</li>{% endfor %}</ul>{% endif %}
<div class="sensor-list">
{% for sensor in sensors %}
<article class="sensor-card">
<div class="sensor-card__heading"><h3>{{ sensor.name }}</h3>{% with status=sensor.heartbeat_status %}<span class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</span>{% endwith %}</div>
<span class="sensor-access {% if not sensor.is_active %}sensor-access--off{% endif %}">{% if sensor.is_active %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}</span>
<dl class="sensor-card__facts">
<div><dt>{% trans "Last heartbeat" %}</dt><dd>{{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }}</dd></div>
<div><dt>{% trans "Created" %}</dt><dd>{{ sensor.created_at|date:"j M Y" }}</dd></div>
<div><dt>{% trans "Token prefix" %}</dt><dd><code>{{ sensor.token_prefix|default:"—" }}</code></dd></div>
</dl>
<a class="button button--secondary" href="{% url 'manage_sensor' sensor.pk %}" hx-get="{% url 'manage_sensor' sensor.pk %}" hx-target="#sensor-card-content" hx-swap="innerHTML">{% trans "Manage" %}</a>
</article>
{% empty %}
<p class="sensor-empty">{% trans "No sensors yet. Add a device to receive an API token for hardware submissions." %}</p>
{% endfor %}
</div>
<form class="settings-form sensor-form" method="post" action="{% url 'create_sensor' %}" hx-post="{% url 'create_sensor' %}" hx-target="#sensor-card-content" hx-swap="innerHTML">
{% csrf_token %}
<div><h3>{% trans "Add a sensor" %}</h3><p class="help">{% trans "Give your device a name so you can recognise it later." %}</p></div>
<div class="sensor-form__controls">
<div class="field"><label for="new-sensor-name">{% trans "Device name" %}</label><input id="new-sensor-name" name="name" type="text" maxlength="100" required></div>
<button class="button" type="submit">{% trans "Add sensor" %}</button>
</div>
</form>
+31
View File
@@ -0,0 +1,31 @@
{% load i18n vite %}
<!doctype html>
<html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% trans "Create an account · Sound Signal" %}</title>
{% vite_asset "frontend/src/entries/login.js" %}
{% include "js_translations.html" %}
</head>
<body>
<main class="card">
<p>✦ Sound Signal</p>
<h1>{% trans "Create an account" %}</h1>
<p class="intro">{% trans "Only a username and password are needed." %}</p>
<form method="post">
{% csrf_token %}
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
{{ form.non_field_errors }}
<label for="{{ form.username.id_for_label }}">{% trans "Username" %}</label>
{{ form.username }} {{ form.username.errors }}
<label for="{{ form.password1.id_for_label }}">{% trans "Password" %}</label>
{{ form.password1 }} {{ form.password1.errors }}
<label for="{{ form.password2.id_for_label }}">{% trans "Confirm password" %}</label>
{{ form.password2 }} {{ form.password2.errors }}
<button type="submit">{% trans "Create account" %}</button>
</form>
<p class="intro">{% trans "Already have an account?" %} <a href="{% url 'login' %}{% if next %}?next={{ next|urlencode }}{% endif %}">{% trans "Sign in" %}</a></p>
</main>
</body>
</html>
+12 -43
View File
@@ -5,48 +5,17 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ sensor.name }} · {% trans "Settings" %}</title>
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
{% vite_asset "frontend/src/entries/settings.js" %}
{% include "js_translations.html" %}
</head>
<body><main class="card">
<a href="{% url 'user_settings' %}">← {% trans "Settings" %}</a>
<h1>{{ sensor.name }}</h1>
{% if messages %}<ul class="messages">{% for message in messages %}<li class="alert alert--error">{{ message }}</li>{% endfor %}</ul>{% endif %}
{% if token %}<section class="token-once" aria-label="{% trans 'New API token' %}">
<strong>{% trans "Copy this token now. For security reasons it will not be shown again." %}</strong>
<code id="sensor-token">{{ token }}</code>
<button class="button button--secondary" type="button" onclick="navigator.clipboard.writeText(document.getElementById('sensor-token').textContent)">{% trans "Copy token" %}</button>
</section>{% endif %}
<section class="section">
{% with status=heartbeat %}<p class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</p>{% endwith %}
<p>{% trans "Last heartbeat" %}: {{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }}</p>
<p>{% trans "Last submission" %}: {{ sensor.last_submission|date:"j M Y, H:i"|default:"—" }}</p>
<p>{% trans "Token prefix" %}: {{ sensor.token_prefix|default:"—" }}</p>
<p>{% trans "Created" %}: {{ sensor.created_at|date:"j M Y, H:i" }}</p>
</section>
<section class="section"><h2>{% trans "Rename" %}</h2>
<form method="post" action="{% url 'rename_sensor' sensor.pk %}">{% csrf_token %}
<label for="id_name">{% trans "Device name" %}</label>{{ form.name }}{{ form.name.errors }}
<button class="button" type="submit">{% trans "Save name" %}</button>
</form>
</section>
<section class="section"><h2>{% trans "Device access" %}</h2>
<p>{% if sensor.is_active %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}</p>
<form method="post" action="{% url 'toggle_sensor' sensor.pk %}">{% csrf_token %}
<button class="button button--secondary" type="submit">{% if sensor.is_active %}{% trans "Disable sensor" %}{% else %}{% trans "Enable sensor" %}{% endif %}</button>
</form>
</section>
<section class="section"><h2>{% trans "Reissue API token" %}</h2>
<p class="help">{% trans "The old token will immediately stop authenticating." %}</p>
<form method="post" action="{% url 'rotate_sensor' sensor.pk %}">{% csrf_token %}
<div class="check"><input type="checkbox" id="confirm-rotate" name="confirm" value="rotate" required><label for="confirm-rotate">{% trans "I understand the old token will stop working" %}</label></div>
<button class="button" type="submit">{% trans "Reissue token" %}</button>
</form>
</section>
<section class="section"><h2>{% trans "Remove sensor" %}</h2>
<p class="help">{% trans "This disables the device and revokes its token. Historical events remain linked to it." %}</p>
<form method="post" action="{% url 'remove_sensor' sensor.pk %}">{% csrf_token %}
<div class="check"><input type="checkbox" id="confirm-remove" name="confirm" value="remove" required><label for="confirm-remove">{% trans "I understand this device will be removed" %}</label></div>
<button class="button button--danger" type="submit">{% trans "Remove sensor" %}</button>
</form>
</section>
</main></body></html>
<body>
<main class="settings-shell">
{% include "fireworks_detect/includes/navigation.html" %}
<div class="settings-content">
<div class="settings-heading"><p class="eyebrow">{% trans "Your preferences" %}</p><h1>{% trans "Settings" %}</h1></div>
<section class="card" id="sensor-card" aria-labelledby="sensors-title"><div id="sensor-card-content">{% include "members/partials/sensor_detail.html" %}</div></section>
</div>
</main>
</body>
</html>
+35 -44
View File
@@ -9,55 +9,46 @@
{% vite_asset "frontend/src/entries/settings.js" %}
{% include "js_translations.html" %}</head>
<body>
<main class="card">
<h1>{% trans "Settings" %}</h1>
<p class="intro">{% trans "Manage your personal 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="language-title">
<main class="settings-shell">
{% include "fireworks_detect/includes/navigation.html" %}
<div class="settings-content">
<div class="settings-heading">
<p class="eyebrow">{% trans "Your preferences" %}</p>
<h1>{% trans "Settings" %}</h1>
<p class="intro">{% trans "Manage your personal preferences." %}</p>
</div>
{% if messages %}<ul class="messages" role="status">{% for message in messages %}<li class="alert alert--success">{{ message }}</li>{% endfor %}</ul>{% endif %}
<form class="card settings-form" method="post" action="{% url 'user_settings' %}">
{% csrf_token %}
<h2 id="language-title">{% trans "Language" %}</h2>
<label for="{{ language_form.preferred_language.id_for_label }}">{% trans "Preferred language" %}</label>
{{ language_form.preferred_language }}
{{ language_form.preferred_language.errors }}
</section>
<button class="button" type="submit" name="save_language" value="1">{% trans "Save language" %}</button>
</form>
<form method="post" action="{% url 'user_settings' %}">
{% csrf_token %}
<section class="section" aria-labelledby="ntfy-title">
<div class="field">
<label for="{{ language_form.preferred_language.id_for_label }}">{% trans "Preferred language" %}</label>
{{ language_form.preferred_language }}
{{ language_form.preferred_language.errors }}
</div>
<button class="button" type="submit" name="save_language" value="1">{% trans "Save language" %}</button>
</form>
<form class="card settings-form" method="post" action="{% url 'user_settings' %}">
{% csrf_token %}
<h2 id="ntfy-title">{% trans "Notifications / ntfy" %}</h2>
<p class="help">{% trans "Use a topic URL from your ntfy server. Test the current URL before saving it." %}</p>
<label for="ntfy-url">{% trans "Topic URL" %}</label>
{{ form.ntfy_url }}
{{ form.ntfy_url.errors }}
<div class="check">{{ form.ntfy_enabled }}<label for="{{ form.ntfy_enabled.id_for_label }}">{% trans "Enable ntfy notifications" %}</label></div>
<p class="help">{% trans "Use a topic URL from your ntfy server. Test the URL before enabling notifications." %}</p>
<div class="field">
<label for="ntfy-url">{% trans "Topic URL" %}</label>
{{ form.ntfy_url }}
{{ form.ntfy_url.errors }}
</div>
<label class="switch-row" for="{{ form.ntfy_enabled.id_for_label }}">
<span class="switch-copy"><strong>{% trans "Enable ntfy notifications" %}</strong><small>{% trans "Save below to apply this change." %}</small></span>
<span class="switch-control">{{ form.ntfy_enabled }}<span class="switch-track" aria-hidden="true"></span></span>
</label>
<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">{% trans "Test notification" %}</button>
<div id="ntfy-test-result" aria-live="polite"></div>
</section>
<button class="button" type="submit">{% trans "Save settings" %}</button>
</form>
<section class="section" aria-labelledby="sensors-title">
<h2 id="sensors-title">{% trans "My sensors" %}</h2>
<p class="help">{% trans "Manage the devices that authenticate with BoomCast." %}</p>
{% for sensor in sensors %}
<div class="sensor-card">
<strong>{{ sensor.name }}</strong>
{% with status=sensor.heartbeat_status %}<span class="sensor-status sensor-status--{{ status.0 }}">● {{ status.1 }}</span>{% endwith %}
<p>{% if sensor.is_active %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %} · {% trans "Token prefix" %}: {{ sensor.token_prefix|default:"—" }}</p>
<p>{% trans "Last heartbeat" %}: {{ sensor.last_heartbeat|date:"j M Y, H:i"|default:"—" }} · {% trans "Created" %}: {{ sensor.created_at|date:"j M Y" }}</p>
<a class="button button--secondary" href="{% url 'manage_sensor' sensor.pk %}">{% trans "Manage" %}</a>
</div>
{% empty %}
<p class="help">{% trans "No sensors yet. Add a device to receive an API token for hardware submissions." %}</p>
{% endfor %}
<form method="post" action="{% url 'create_sensor' %}">
{% csrf_token %}
<label for="new-sensor-name">{% trans "Device name" %}</label>
<input id="new-sensor-name" name="name" type="text" maxlength="100" required>
<button class="button" type="submit">{% trans "Add sensor" %}</button>
<button class="button" type="submit">{% trans "Save settings" %}</button>
</form>
</section>
<section class="card" id="sensor-card" aria-labelledby="sensors-title">
<div id="sensor-card-content">{% include "members/partials/sensor_list.html" %}</div>
</section>
</div>
</main>
</body>
</html>
+35
View File
@@ -39,6 +39,41 @@ class SensorSettingsTests(TestCase):
self.assertContains(listing, "Bob&#x27;s device")
self.assertNotContains(listing, "Balcony")
def test_htmx_sensor_card_opens_updates_and_closes(self):
sensor = Sensor.objects.create(name="Balcony", owner=self.alice)
headers = {"HTTP_HX_REQUEST": "true"}
detail = self.client.get(reverse("manage_sensor", args=[sensor.pk]), **headers)
self.assertContains(detail, "Balcony")
self.assertContains(detail, reverse("sensor_list"))
self.assertNotContains(detail, "<!doctype html>")
renamed = self.client.post(reverse("rename_sensor", args=[sensor.pk]), {"name": "Roof"}, **headers)
self.assertContains(renamed, "Roof")
self.assertNotContains(renamed, "<!doctype html>")
listing = self.client.get(reverse("sensor_list"), **headers)
self.assertContains(listing, "Roof")
self.assertContains(listing, reverse("manage_sensor", args=[sensor.pk]))
full_page = self.client.get(reverse("manage_sensor", args=[sensor.pk]))
self.assertContains(full_page, "<!doctype html>")
self.assertContains(full_page, "settings-shell")
def test_htmx_create_shows_token_once_and_remove_restores_list(self):
headers = {"HTTP_HX_REQUEST": "true"}
created = self.client.post(reverse("create_sensor"), {"name": "Portable"}, **headers)
sensor = Sensor.objects.get(name="Portable")
token = created.context["token"]
self.assertContains(created, token)
self.assertIn("no-store", created["Cache-Control"])
self.assertNotContains(self.client.get(reverse("manage_sensor", args=[sensor.pk]), **headers), token)
removed = self.client.post(reverse("remove_sensor", args=[sensor.pk]), {"confirm": "remove"}, **headers)
self.assertContains(removed, "My sensors")
self.assertNotContains(removed, "Portable")
self.assertEqual(self.client.get(reverse("manage_sensor", args=[sensor.pk]), **headers).status_code, 404)
def test_owner_can_manage_rotate_and_archive_preserving_history(self):
sensor = Sensor.objects.create(name="Balcony", owner=self.alice)
old_token = sensor.issue_token()
+98 -1
View File
@@ -4,13 +4,14 @@ from urllib.error import HTTPError, URLError
from django.contrib.auth import get_user_model
from django.conf import settings
from django.core.management import call_command
from django.test import SimpleTestCase, TestCase
from django.urls import reverse
from django.utils import translation
from notifications.services import NotificationError, send_notification, send_ntfy_notification
from .models import UserSettings
from .models import PendingNotificationBatch, UserSettings
@@ -90,6 +91,58 @@ class UserSettingsNtfyTests(TestCase):
self.assertFalse(settings.ntfy_enabled)
self.assertEqual(settings.ntfy_url, "")
def test_unchecked_url_can_be_saved_without_testing_then_requires_test_to_enable(self):
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url})
self.assertRedirects(response, reverse("user_settings"))
saved = UserSettings.objects.get(user=self.user)
self.assertEqual(saved.ntfy_url, self.url)
self.assertFalse(saved.ntfy_enabled)
self.assertIsNone(saved.ntfy_last_tested_at)
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
self.assertContains(response, "Test deze URL")
@patch("notifications.services.send_ntfy_notification")
def test_pending_arrivals_are_grouped_by_minute_and_source(self, mock_send):
from datetime import timedelta
from django.utils import timezone
from fireworks_detect.models import PendingEvent
UserSettings.objects.create(user=self.user, ntfy_url=self.url, ntfy_enabled=True)
PendingEvent.objects.create(original_filename="manual", classifier_response={}, source_type=PendingEvent.SourceType.MANUAL)
PendingEvent.objects.create(original_filename="sensor", classifier_response={})
PendingEvent.objects.create(original_filename="sensor2", classifier_response={})
batch = PendingNotificationBatch.objects.get(user=self.user)
self.assertEqual((batch.manual_count, batch.sensor_count), (1, 2))
call_command("send_pending_notifications")
mock_send.assert_not_called()
PendingNotificationBatch.objects.filter(pk=batch.pk).update(minute=timezone.now() - timedelta(minutes=2))
call_command("send_pending_notifications")
mock_send.assert_called_once()
self.assertIn("1 handmatig", mock_send.call_args.args[2])
self.assertIn("2 sensor", mock_send.call_args.args[2])
self.assertFalse(PendingNotificationBatch.objects.exists())
PendingEvent.objects.create(original_filename="next", classifier_response={})
self.assertEqual(PendingNotificationBatch.objects.get(user=self.user).sensor_count, 1)
@patch("notifications.services.send_ntfy_notification", side_effect=NotificationError("Could not connect"))
def test_failed_summary_is_kept_for_retry(self, mock_send):
from datetime import timedelta
from django.utils import timezone
from fireworks_detect.models import PendingEvent
UserSettings.objects.create(user=self.user, ntfy_url=self.url, ntfy_enabled=True)
PendingEvent.objects.create(original_filename="manual", classifier_response={}, source_type=PendingEvent.SourceType.MANUAL)
PendingNotificationBatch.objects.update(minute=timezone.now() - timedelta(minutes=2))
call_command("send_pending_notifications")
self.assertEqual(PendingNotificationBatch.objects.get().manual_count, 1)
def test_disabled_user_does_not_accumulate_pending_summaries(self):
from fireworks_detect.models import PendingEvent
UserSettings.objects.create(user=self.user, ntfy_url=self.url, ntfy_enabled=False)
PendingEvent.objects.create(original_filename="manual", classifier_response={}, source_type=PendingEvent.SourceType.MANUAL)
self.assertFalse(PendingNotificationBatch.objects.exists())
@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})
@@ -145,13 +198,54 @@ class FrontendAuthenticationTests(TestCase):
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Sign in")
self.assertContains(response, reverse("register"))
self.assertContains(response, "csrfmiddlewaretoken")
def test_registration_creates_minimal_account_and_signs_in(self):
response = self.client.post(reverse("register"), {
"username": "new-user",
"password1": "long-unique-password-5842",
"password2": "long-unique-password-5842",
})
self.assertRedirects(response, "/")
user = get_user_model().objects.get(username="new-user")
self.assertEqual(user.email, "")
self.assertEqual(str(self.client.session["_auth_user_id"]), str(user.pk))
def test_registration_preserves_safe_login_destination(self):
login_page = self.client.get(reverse("login"), {"next": "/settings/"})
self.assertContains(login_page, "/register/?next=/settings/")
response = self.client.post(reverse("register"), {
"username": "another-new-user",
"password1": "long-unique-password-5842",
"password2": "long-unique-password-5842",
"next": "/settings/",
})
self.assertRedirects(response, "/settings/")
def test_registration_rejects_external_destination(self):
response = self.client.post(reverse("register"), {
"username": "safe-user",
"password1": "long-unique-password-5842",
"password2": "long-unique-password-5842",
"next": "https://example.com/steal",
})
self.assertRedirects(response, "/")
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_frontend_logout_uses_post_and_returns_home(self):
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse("logout")).status_code, 405)
response = self.client.post(reverse("logout"))
self.assertRedirects(response, "/")
self.assertNotIn("_auth_user_id", self.client.session)
def test_protected_settings_redirects_to_frontend_login(self):
response = self.client.get(reverse("user_settings"))
@@ -160,11 +254,14 @@ class FrontendAuthenticationTests(TestCase):
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.assertContains(anonymous_response, f'href="{reverse("login")}"')
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"))
self.assertContains(authenticated_response, f'action="{reverse("logout")}"')
self.assertNotContains(authenticated_response, f'href="{reverse("login")}"')
class LanguageSettingsTests(TestCase):
+20 -1
View File
@@ -1,11 +1,14 @@
from hashlib import sha256
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.shortcuts import render, redirect
from django.utils import timezone
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext as _
from django.views.decorators.http import require_POST
@@ -14,6 +17,20 @@ from fireworks_detect.models import Sensor
from .forms import LanguageSettingsForm, MemberForm, UserSettingsForm
from .models import Member, UserSettings
def register(request):
if request.user.is_authenticated:
return redirect("hello")
next_url = request.POST.get("next") or request.GET.get("next", "")
if not url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
next_url = ""
form = UserCreationForm(request.POST or None)
if request.method == "POST" and form.is_valid():
user = form.save()
login(request, user)
return redirect(next_url or "hello")
return render(request, "members/register.html", {"form": form, "next": next_url})
def member_create(request):
if request.method == "POST":
form = MemberForm(request.POST)
@@ -84,7 +101,7 @@ def user_settings(request):
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:
if form.cleaned_data["ntfy_enabled"] and 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)
@@ -93,6 +110,8 @@ def user_settings(request):
settings.ntfy_last_tested_at = None
elif tested_fingerprint == _url_fingerprint(url):
settings.ntfy_last_tested_at = timezone.now()
elif saved_ntfy_url != url:
settings.ntfy_last_tested_at = None
settings.save()
request.session.pop(_ntfy_test_session_key(request.user), None)
messages.success(request, _("Notification settings saved."))