latest changes before manual submissions redesign
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
# Ntfy blueprint for a Django tasks and health tracker
|
||||
|
||||
This is a portable version of this project's `/settings` integration. It gives each user a topic URL, a test button, an enable switch, and one function that task or health code can call. Replace `accounts` with the app that owns your user preferences. The examples assume an authenticated `/settings/` page and Django's standard CSRF and messages middleware.
|
||||
|
||||
## 1. Store preferences
|
||||
|
||||
In `accounts/models.py` (merge these fields into an existing per-user settings model if you have one):
|
||||
|
||||
```python
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
class NotificationSettings(models.Model):
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
```
|
||||
|
||||
Run `python manage.py makemigrations accounts` and `python manage.py migrate`.
|
||||
|
||||
## 2. Add the sender
|
||||
|
||||
Create `notifications/services.py` (and an empty `notifications/__init__.py` if needed):
|
||||
|
||||
```python
|
||||
import socket
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
class NotificationError(Exception):
|
||||
"""A delivery error safe to display to a user."""
|
||||
|
||||
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 as error:
|
||||
raise NotificationError("Could not connect to the ntfy server.") from error
|
||||
except OSError as error:
|
||||
raise NotificationError("Could not connect to the ntfy server.") from error
|
||||
if not 200 <= status < 300:
|
||||
raise NotificationError(f"ntfy server responded with HTTP {status}.")
|
||||
|
||||
def send_notification(user, title, message):
|
||||
from accounts.models import NotificationSettings
|
||||
preferences = NotificationSettings.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
|
||||
```
|
||||
|
||||
The URL is a destination and may contain a private topic name. Keep it out of logs and error messages. A user supplied server URL also lets the server make outbound requests; restrict destinations or allow only your trusted ntfy host if your deployment needs that boundary. Add authentication headers if your ntfy server requires them; this example uses a topic URL only.
|
||||
|
||||
## 3. Form, views, and routes
|
||||
|
||||
In `accounts/forms.py`:
|
||||
|
||||
```python
|
||||
from django import forms
|
||||
from .models import NotificationSettings
|
||||
|
||||
class NotificationSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = NotificationSettings
|
||||
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()
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if data.get("ntfy_enabled") and not data.get("ntfy_url"):
|
||||
self.add_error("ntfy_url", "Enter a topic URL before enabling notifications.")
|
||||
return data
|
||||
```
|
||||
|
||||
In `accounts/views.py`:
|
||||
|
||||
```python
|
||||
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 redirect, render
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from notifications.services import NotificationError, send_ntfy_notification
|
||||
from .forms import NotificationSettingsForm
|
||||
from .models import NotificationSettings
|
||||
|
||||
def test_key(user):
|
||||
return f"ntfy_tested_url_fingerprint:{user.pk}"
|
||||
|
||||
def fingerprint(url):
|
||||
return sha256(url.encode("utf-8")).hexdigest()
|
||||
|
||||
@login_required
|
||||
def settings_page(request):
|
||||
preferences, _ = NotificationSettings.objects.get_or_create(user=request.user)
|
||||
old_url = preferences.ntfy_url
|
||||
form = NotificationSettingsForm(request.POST or None, instance=preferences)
|
||||
if request.method == "POST" and form.is_valid():
|
||||
url = form.cleaned_data["ntfy_url"]
|
||||
just_tested = bool(url) and request.session.get(test_key(request.user)) == fingerprint(url)
|
||||
previously_tested = url == old_url and preferences.ntfy_last_tested_at is not None
|
||||
if form.cleaned_data["ntfy_enabled"] and not (just_tested or previously_tested):
|
||||
form.add_error("ntfy_url", "Test this URL successfully before enabling notifications.")
|
||||
else:
|
||||
preferences = form.save(commit=False)
|
||||
if not url:
|
||||
preferences.ntfy_enabled = False
|
||||
preferences.ntfy_last_tested_at = None
|
||||
elif just_tested:
|
||||
preferences.ntfy_last_tested_at = timezone.now()
|
||||
elif url != old_url:
|
||||
preferences.ntfy_last_tested_at = None
|
||||
preferences.save()
|
||||
request.session.pop(test_key(request.user), None)
|
||||
messages.success(request, "Notification settings saved.")
|
||||
return redirect("settings_page")
|
||||
return render(request, "accounts/settings.html", {"form": form})
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def test_ntfy(request):
|
||||
url = request.POST.get("ntfy_url", "").strip()
|
||||
try:
|
||||
URLValidator(schemes=["http", "https"])(url)
|
||||
except ValidationError:
|
||||
return render(request, "accounts/ntfy_test_result.html", {"error": "Enter a valid HTTP or HTTPS topic URL."}, status=400)
|
||||
try:
|
||||
send_ntfy_notification(url, "Tasks & Health", "Test notification sent successfully.")
|
||||
except NotificationError as error:
|
||||
return render(request, "accounts/ntfy_test_result.html", {"error": str(error)}, status=502)
|
||||
request.session[test_key(request.user)] = fingerprint(url)
|
||||
return render(request, "accounts/ntfy_test_result.html", {"success": True})
|
||||
```
|
||||
|
||||
In `accounts/urls.py`, include these routes under `/settings/` in the project URLconf:
|
||||
|
||||
```python
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.settings_page, name="settings_page"),
|
||||
path("notifications/ntfy/test/", views.test_ntfy, name="ntfy_test"),
|
||||
]
|
||||
```
|
||||
|
||||
## 4. Settings UI
|
||||
|
||||
Put this section inside your existing `/settings/` template. It uses htmx for the inline test response; load htmx once in the page layout (or replace `hx-post` with a small `fetch` handler). Keep the CSRF input inside the form.
|
||||
|
||||
```html
|
||||
<form method="post" action="{% url 'settings_page' %}">
|
||||
{% csrf_token %}
|
||||
<section aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p>Use a topic URL from your ntfy server. Test it before enabling notifications.</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 type="button" hx-post="{% url 'ntfy_test' %}"
|
||||
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 type="submit">Save settings</button>
|
||||
</form>
|
||||
<script>
|
||||
document.querySelector("#ntfy-url").addEventListener("input", () => {
|
||||
document.querySelector("#ntfy-test-result").replaceChildren();
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
`accounts/ntfy_test_result.html`:
|
||||
|
||||
```html
|
||||
{% 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 %}
|
||||
```
|
||||
|
||||
Suggested CSS, scoped to your existing settings styles:
|
||||
|
||||
```css
|
||||
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
|
||||
.check { display: flex; gap: .6rem; align-items: center; }
|
||||
.check label { margin: 0; }
|
||||
.alert { margin-top: 1rem; padding: .75rem; border-radius: .55rem; }
|
||||
.alert--success { color: #d1fae5; background: #14532d; }
|
||||
.alert--error { color: #fee2e2; background: #7f1d1d; }
|
||||
```
|
||||
|
||||
## 5. Trigger from tasks or health events
|
||||
|
||||
Call the provider agnostic `send_notification` after a meaningful state change. Put delivery on a background worker for normal operation, since the HTTP call can take up to ten seconds. Queue the job after the database commit so it cannot announce a rolled back change.
|
||||
|
||||
```python
|
||||
from django.db import transaction
|
||||
|
||||
# After saving a task completion, missed deadline, check-in, or health alert:
|
||||
user_id = task.user_id
|
||||
task_id = task.pk
|
||||
transaction.on_commit(lambda: enqueue_task_event_notification(user_id, task_id))
|
||||
```
|
||||
|
||||
`enqueue_task_event_notification` is your existing Celery, RQ, or job queue entry point. In its worker, reload the user and task, confirm that the event still qualifies, then call `send_notification(user, "Task due", "Your task is due today.")`. Catch `NotificationError`, log a safe error without the topic URL, and retry according to your queue policy. Use an event ID or unique job key if duplicate delivery matters. If you have no worker yet, a management command run by cron can drain a small notification outbox instead.
|
||||
|
||||
Typical mapping for this app:
|
||||
|
||||
| App event | Suggested message | Trigger location |
|
||||
| --- | --- | --- |
|
||||
| Task due | “Your task is due today.” | Scheduled due-date job |
|
||||
| Task completed | “Task completed.” | Completion service, after commit |
|
||||
| Check-in missed | “Your daily check-in is still open.” | Scheduled reminder job |
|
||||
| Health threshold crossed | “A tracked value crossed your chosen threshold.” | Threshold evaluator, after commit |
|
||||
|
||||
Avoid including sensitive health measurements in the notification unless the user explicitly opts in. Define the event's recipient and idempotency rule in the app service, rather than in the ntfy sender.
|
||||
|
||||
## 6. Minimum verification
|
||||
|
||||
Test an invalid URL, a failed test, a successful test followed by save, a changed URL requiring a new test, and disabled settings suppressing sends. Mock `urlopen` or `send_ntfy_notification`; do not send real notifications in tests. Check one actual device delivery manually with a private topic before enabling event triggers.
|
||||
|
||||
Source implementation in this repo: `members/views.py`, `members/forms.py`, `members/models.py`, `members/templates/members/user_settings.html`, `notifications/services.py`, and `fireworks_detect/signals.py`. The source app groups Pending events by minute with `PendingNotificationBatch` and a scheduled command; use that pattern if your tracker needs digest notifications.
|
||||
@@ -121,3 +121,32 @@ server mode requires an audio file or browser mode.
|
||||
Browser assets are loaded only after the user enables the toggle and selects a
|
||||
file. Regenerate the self-hosted model using [the YAMNet build guide](scripts/BROWSER_YAMNET.md),
|
||||
then run `npm run build` and `python manage.py collectstatic --noinput`.
|
||||
# Pending event notifications
|
||||
|
||||
Users can test and enable an ntfy topic in Settings. New Pending events are
|
||||
counted by source (manual or sensor) in one-minute batches per enabled user.
|
||||
Run `python manage.py send_pending_notifications` once per minute with the
|
||||
application's Python environment and working directory. For example, a cron
|
||||
entry can use `* * * * * cd /path/to/django && /path/to/python manage.py send_pending_notifications`.
|
||||
It sends completed minute batches,
|
||||
then removes them; failed deliveries remain queued for the next run.
|
||||
|
||||
For a systemd user timer on the laptop, install the units in
|
||||
[`deploy/systemd/`](deploy/systemd/) and start the timer:
|
||||
|
||||
```sh
|
||||
cd /home/jorenmartijn/python/django
|
||||
/usr/bin/python3 -m venv /home/jorenmartijn/python/.venv-notifications
|
||||
/home/jorenmartijn/python/.venv-notifications/bin/python -m pip install -r requirements.txt
|
||||
/home/jorenmartijn/python/.venv-notifications/bin/python manage.py check
|
||||
mkdir -p ~/.config/systemd/user
|
||||
cp deploy/systemd/send-pending-notifications.service deploy/systemd/send-pending-notifications.timer ~/.config/systemd/user/
|
||||
systemctl --user daemon-reload
|
||||
systemctl --user enable --now send-pending-notifications.timer
|
||||
systemctl --user list-timers send-pending-notifications.timer
|
||||
```
|
||||
|
||||
The service runs `/home/jorenmartijn/python/.venv-notifications/bin/python` with this
|
||||
project as its working directory. To keep the user timer running after logout,
|
||||
run `sudo loginctl enable-linger jorenmartijn` once on the laptop. Check a run
|
||||
with `journalctl --user -u send-pending-notifications.service -n 30`.
|
||||
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Send batched Pending event ntfy notifications
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=/home/jorenmartijn/python/django
|
||||
ExecStart=/home/jorenmartijn/python/.venv-notifications/bin/python /home/jorenmartijn/python/django/manage.py send_pending_notifications
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Send Pending event ntfy summaries every minute
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:*:00
|
||||
AccuracySec=1s
|
||||
Persistent=true
|
||||
Unit=send-pending-notifications.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
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.
Binary file not shown.
@@ -3,3 +3,6 @@ from django.apps import AppConfig
|
||||
|
||||
class FireworksDetectConfig(AppConfig):
|
||||
name = 'fireworks_detect'
|
||||
|
||||
def ready(self):
|
||||
from . import signals # noqa: F401
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
from django.db.models import F
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.utils import timezone
|
||||
|
||||
from members.models import PendingNotificationBatch, UserSettings
|
||||
|
||||
from .models import PendingEvent
|
||||
|
||||
|
||||
@receiver(post_save, sender=PendingEvent)
|
||||
def count_new_pending_event(sender, instance, created, **kwargs):
|
||||
if not created:
|
||||
return
|
||||
minute = timezone.now().replace(second=0, microsecond=0)
|
||||
field = "manual_count" if instance.source_type == PendingEvent.SourceType.MANUAL else "sensor_count"
|
||||
for user_id in UserSettings.objects.filter(ntfy_enabled=True).exclude(ntfy_url="").values_list("user_id", flat=True):
|
||||
batch, _ = PendingNotificationBatch.objects.get_or_create(user_id=user_id, minute=minute)
|
||||
PendingNotificationBatch.objects.filter(pk=batch.pk).update(**{field: F(field) + 1})
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
<section class="upload-card" aria-label="{% trans "Upload audio for classification" %}">
|
||||
{% include "fireworks_detect/includes/audio_upload_form.html" %}
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
|
||||
@@ -35,4 +35,17 @@
|
||||
</div>
|
||||
</form>
|
||||
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
|
||||
<div id="manual-compass" class="manual-compass" role="img" aria-label="{% trans 'Compass direction' %}" hidden>
|
||||
<div class="manual-compass__dial" aria-hidden="true">
|
||||
<div id="manual-compass-rose" class="manual-compass__rose">
|
||||
<span class="manual-compass__north">N</span>
|
||||
<span class="manual-compass__east">E</span>
|
||||
<span class="manual-compass__south">S</span>
|
||||
<span class="manual-compass__west">W</span>
|
||||
</div>
|
||||
<span class="manual-compass__pointer"></span>
|
||||
<span class="manual-compass__center"></span>
|
||||
</div>
|
||||
<span id="manual-compass-heading" class="manual-compass__heading"></span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
<a href="{% url "fireworks_detect:fireworks" %}"{% if active_page == "analyse" %} aria-current="page"{% endif %}>{% trans "Analyse" %}</a>
|
||||
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>{% trans "Map" %}</a>
|
||||
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>{% trans "Events" %}</a>
|
||||
{% if request.user.is_authenticated %}
|
||||
<form action="{% url 'logout' %}" method="post">
|
||||
{% csrf_token %}
|
||||
<button type="submit">{% trans "Sign out" %}</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<a href="{% url 'login' %}">{% trans "Sign in" %}</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% if not request.user.is_authenticated %}
|
||||
<form class="public-language" action="{% url 'set_anonymous_language' %}" method="post" style="display:flex;align-items:center;gap:.3rem;color:var(--muted,#aab9d8);font-size:.78rem">
|
||||
|
||||
@@ -160,6 +160,8 @@ class ManualPendingEventTests(TestCase):
|
||||
self.assertContains(response, "I heard fireworks — send to Pending")
|
||||
self.assertContains(response, "Capture direction")
|
||||
self.assertContains(response, 'manual-direction-panel" hidden')
|
||||
self.assertContains(response, 'id="manual-compass"')
|
||||
self.assertContains(response, 'aria-label="Compass direction" hidden')
|
||||
self.assertContains(response, "htmx.min.js")
|
||||
self.assertContains(response, "/static/vite/")
|
||||
self.assertContains(response, 'type="module"')
|
||||
|
||||
@@ -3,6 +3,7 @@ import "../styles/pages/fireworks-home.css";
|
||||
import "../styles/pages/map.css";
|
||||
import "../styles/pages/dashboard.css";
|
||||
import "../styles/components/burst-listener.css";
|
||||
import "../styles/components/manual-compass.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/manual-report.js";
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import "../styles/pages/home.css";
|
||||
import "../styles/components/burst-listener.css";
|
||||
import "../styles/components/manual-compass.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/manual-report.js";
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import "../styles/pages/settings.css";
|
||||
import "../styles/components/fireworks-navigation.css";
|
||||
import "../styles/theme.css";
|
||||
import "../scripts/theme.js";
|
||||
import "../scripts/user-settings.js";
|
||||
|
||||
@@ -11,11 +11,15 @@
|
||||
const captureDirectionButton = document.querySelector("#manual-capture-direction");
|
||||
const directionStatus = document.querySelector("#manual-direction-status");
|
||||
const directionPanel = document.querySelector("#manual-direction-panel");
|
||||
const compass = document.querySelector("#manual-compass");
|
||||
const compassRose = document.querySelector("#manual-compass-rose");
|
||||
const compassHeading = document.querySelector("#manual-compass-heading");
|
||||
const isMobileDevice = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini/.test(navigator.userAgent)
|
||||
|| (navigator.userAgent.includes("Macintosh") && navigator.maxTouchPoints > 1);
|
||||
if (isMobileDevice) directionPanel.hidden = false;
|
||||
let orientationListener;
|
||||
let compassUnavailableTimeout;
|
||||
let compassRotation = null;
|
||||
const burstListener = createBurstListener();
|
||||
|
||||
const isUsableNumber = (value) => Number.isFinite(value);
|
||||
@@ -27,6 +31,27 @@
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
orientationListener = null;
|
||||
compassUnavailableTimeout = null;
|
||||
compass.hidden = true;
|
||||
compassRotation = null;
|
||||
};
|
||||
|
||||
const updateCompass = (heading) => {
|
||||
const targetRotation = -heading;
|
||||
if (compassRotation === null) {
|
||||
compassRotation = targetRotation;
|
||||
compassRose.style.transition = "none";
|
||||
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
||||
// Restore the short rotation animation after the initial reading.
|
||||
compassRose.offsetWidth;
|
||||
compassRose.style.transition = "";
|
||||
} else {
|
||||
const change = ((targetRotation - compassRotation + 540) % 360) - 180;
|
||||
compassRotation += change;
|
||||
compassRose.style.transform = `rotate(${compassRotation}deg)`;
|
||||
}
|
||||
compassHeading.textContent = `${displayDegrees(heading)}° · ${cardinalDirection(heading)}`;
|
||||
compass.setAttribute("aria-label", `${t.compassDirection || "Compass direction"} ${displayDegrees(heading)}° ${cardinalDirection(heading)}`);
|
||||
compass.hidden = false;
|
||||
};
|
||||
|
||||
const showCapturedDirection = (heading, accuracy) => {
|
||||
@@ -53,6 +78,7 @@
|
||||
directionDegrees.value = heading;
|
||||
directionAccuracy.value = accuracy === null ? "" : accuracy;
|
||||
showCapturedDirection(heading, accuracy);
|
||||
updateCompass(heading);
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
};
|
||||
window.addEventListener("deviceorientation", orientationListener);
|
||||
|
||||
@@ -1 +1,10 @@
|
||||
document.querySelector("#ntfy-url").addEventListener("input", () => { document.querySelector("#ntfy-test-result").replaceChildren(); });
|
||||
document.querySelector("#ntfy-url")?.addEventListener("input", () => {
|
||||
document.querySelector("#ntfy-test-result")?.replaceChildren();
|
||||
});
|
||||
|
||||
document.addEventListener("click", async (event) => {
|
||||
const button = event.target.closest("[data-copy-sensor-token]");
|
||||
if (!button) return;
|
||||
const token = document.querySelector("#sensor-token")?.textContent;
|
||||
if (token) await navigator.clipboard.writeText(token);
|
||||
});
|
||||
|
||||
@@ -37,7 +37,8 @@
|
||||
background: #111a31d9;
|
||||
box-shadow: 0 .5rem 1.5rem #03071440;
|
||||
}
|
||||
.fireworks-nav a {
|
||||
.fireworks-nav a,
|
||||
.fireworks-nav button {
|
||||
padding: .5rem .75rem;
|
||||
border-radius: .5rem;
|
||||
color: var(--muted, var(--m, #aab9d8));
|
||||
@@ -45,7 +46,10 @@
|
||||
font-weight: 750;
|
||||
text-decoration: none;
|
||||
}
|
||||
.fireworks-nav a:hover { color: var(--ink, var(--i, #eef3ff)); background: #20345f; }
|
||||
.fireworks-nav form { display: flex; margin: 0; }
|
||||
.fireworks-nav button { border: 0; background: transparent; font: inherit; cursor: pointer; }
|
||||
.fireworks-nav a:hover,
|
||||
.fireworks-nav button:hover { color: var(--ink, var(--i, #eef3ff)); background: #20345f; }
|
||||
.fireworks-nav a[aria-current="page"] { color: var(--ink, var(--i, #eef3ff)); background: #2a3b67; }
|
||||
.theme-toggle--inline {
|
||||
position: static;
|
||||
@@ -59,8 +63,10 @@
|
||||
background: #edf4ff;
|
||||
box-shadow: 0 .45rem 1.25rem rgba(34, 68, 117, .12);
|
||||
}
|
||||
:root[data-theme="light"] .fireworks-nav a { color: #47617f; }
|
||||
:root[data-theme="light"] .fireworks-nav a:hover { color: #234a7b; background: #dceaff; }
|
||||
:root[data-theme="light"] .fireworks-nav a,
|
||||
:root[data-theme="light"] .fireworks-nav button { color: #47617f; }
|
||||
:root[data-theme="light"] .fireworks-nav a:hover,
|
||||
:root[data-theme="light"] .fireworks-nav button:hover { color: #234a7b; background: #dceaff; }
|
||||
:root[data-theme="light"] .fireworks-nav a[aria-current="page"] {
|
||||
color: #173d6a;
|
||||
background: #cfe3ff;
|
||||
@@ -89,6 +95,10 @@
|
||||
.fireworks-header__controls { display: none; flex-basis: 100%; width: 100%; flex-direction: column; align-items: stretch; }
|
||||
.fireworks-menu-toggle[aria-expanded="true"] ~ .fireworks-header__controls { display: flex; }
|
||||
.fireworks-nav { flex-direction: column; }
|
||||
.fireworks-nav a { padding: .75rem; }
|
||||
.fireworks-nav a,
|
||||
.fireworks-nav button { padding: .75rem; }
|
||||
.fireworks-nav form,
|
||||
.fireworks-nav button { width: 100%; }
|
||||
.fireworks-nav button { text-align: left; }
|
||||
.theme-toggle--inline { width: 100%; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
.manual-compass {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
width: 7rem;
|
||||
margin: .6rem 0 0 auto;
|
||||
color: #fff3d7;
|
||||
font-size: .78rem;
|
||||
font-weight: 850;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.manual-compass[hidden] { display: none; }
|
||||
.manual-compass__dial {
|
||||
position: relative;
|
||||
width: 5.75rem;
|
||||
aspect-ratio: 1;
|
||||
border: 2px solid #f2d7a8;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, #342441 0 28%, #211a32 75%);
|
||||
box-shadow: 0 .35rem 1rem #09061566, inset 0 0 0 .25rem #ffffff12;
|
||||
}
|
||||
.manual-compass__rose { position: absolute; inset: 0; transition: transform 120ms ease-out; }
|
||||
.manual-compass__rose span { position: absolute; line-height: 1; }
|
||||
.manual-compass__north { top: .38rem; left: 50%; color: #ff9e78; transform: translateX(-50%); }
|
||||
.manual-compass__east { right: .47rem; top: 50%; transform: translateY(-50%); }
|
||||
.manual-compass__south { bottom: .38rem; left: 50%; transform: translateX(-50%); }
|
||||
.manual-compass__west { left: .47rem; top: 50%; transform: translateY(-50%); }
|
||||
.manual-compass__pointer {
|
||||
position: absolute;
|
||||
top: -.55rem;
|
||||
left: 50%;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-right: .37rem solid transparent;
|
||||
border-bottom: .65rem solid #ffbd62;
|
||||
border-left: .37rem solid transparent;
|
||||
transform: translateX(-50%);
|
||||
filter: drop-shadow(0 .1rem .15rem #160d1b);
|
||||
}
|
||||
.manual-compass__center {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: .5rem;
|
||||
aspect-ratio: 1;
|
||||
border-radius: 50%;
|
||||
background: #ffbd62;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
.manual-compass__heading { margin-top: .5rem; white-space: nowrap; }
|
||||
:root[data-theme="light"] .manual-compass { color: #43243d; }
|
||||
:root[data-theme="light"] .manual-compass__dial { border-color: #996a9b; background: radial-gradient(circle, #f8ebf8 0 28%, #e8d7e9 75%); }
|
||||
:root[data-theme="light"] .manual-compass__east,
|
||||
:root[data-theme="light"] .manual-compass__south,
|
||||
:root[data-theme="light"] .manual-compass__west { color: #43243d; }
|
||||
@media (prefers-reduced-motion: reduce) { .manual-compass__rose { transition: none; } }
|
||||
@@ -1,11 +1,51 @@
|
||||
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}}
|
||||
.sensor-card{margin:1rem 0;padding:1rem;border:1px solid var(--theme-line);border-radius:.7rem;background:var(--theme-surface-raised)}
|
||||
.sensor-card p{margin:.5rem 0;color:var(--theme-muted)}
|
||||
.sensor-card .button{display:inline-block;text-decoration:none}
|
||||
.sensor-status{display:inline-block;margin-left:.5rem;color:#ef4444;font-weight:700}
|
||||
.sensor-status--online{color:#22c55e}.sensor-status--delayed{color:#f59e0b}
|
||||
input[type=text]{box-sizing:border-box;width:100%;min-height:2.8rem;padding:.65rem;border:1px solid var(--theme-line);border-radius:.55rem;color:var(--theme-ink);font:inherit;background:var(--theme-input)}
|
||||
.token-once{margin:1rem 0;padding:1rem;border:1px solid #f59e0b;border-radius:.7rem;background:var(--theme-surface-raised)}
|
||||
.token-once code{display:block;overflow-wrap:anywhere;margin-top:.7rem;padding:.7rem;border-radius:.4rem;background:var(--theme-input);user-select:all}
|
||||
.button--danger{color:#fff;background:#991b1b}
|
||||
:root[data-theme=light] .sensor-status:not(.sensor-status--online):not(.sensor-status--delayed){color:#b91c1c}
|
||||
/* Settings cards follow the shared blue and violet theme. */
|
||||
*{box-sizing:border-box}
|
||||
body{min-height:100vh;padding:0;color:var(--theme-ink);background:var(--theme-bg)}
|
||||
.settings-shell{width:min(100% - 3.5rem,73.75rem);margin:auto;padding:4rem 0 5rem}
|
||||
.settings-content{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:2.25rem 2rem;width:100%}
|
||||
.settings-heading,.messages{grid-column:1/-1}
|
||||
.settings-heading{margin-bottom:0}
|
||||
.eyebrow{margin:0 0 .7rem;color:#9fc5ff;font-size:.74rem;font-weight:800;letter-spacing:.1em;text-transform:uppercase}
|
||||
h1,h2{font-family:Georgia,ui-serif,serif;font-weight:700}
|
||||
h1{margin:0;font-size:clamp(2.3rem,4vw,3.5rem);letter-spacing:-.045em;line-height:1.12}
|
||||
h2{margin:0 0 .45rem;font-size:1.5rem;letter-spacing:-.02em}
|
||||
.intro,.help{margin:.45rem 0 0;color:var(--theme-muted);line-height:1.55}
|
||||
.card{min-width:0;width:100%;margin:0;padding:1.75rem;border:1px solid var(--theme-line);border-radius:1.125rem;background:var(--theme-surface);box-shadow:0 1.125rem 2.8rem #02071429}
|
||||
.settings-form{display:flex;flex-direction:column;gap:1rem}.settings-form h2+.field{margin-top:.4rem}
|
||||
.settings-form>.button[type=submit]{margin-top:auto}
|
||||
.field label{display:block;margin:0 0 .375rem;font-size:.85rem;font-weight:700}
|
||||
.field input,.field select{display:block;width:100%;min-height:2.625rem;padding:.55rem .625rem;border:1px solid var(--theme-line);border-radius:.56rem;color:var(--theme-ink);background:var(--theme-input);font:inherit}
|
||||
.field input:focus-visible,.field select:focus-visible,.button:focus-visible,.switch-control input:focus-visible+.switch-track{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.errorlist{margin:.5rem 0 0;padding:.7rem .9rem;border-radius:.55rem;color:#fee2e2;background:#7f1d1d}
|
||||
.button{display:inline-flex;align-items:center;justify-content:center;width:100%;min-height:2.875rem;margin:0;padding:.65rem 1.2rem;border:1px solid transparent;border-radius:999px;color:#111c30;background:#a6ccff;font:inherit;font-size:.9rem;font-weight:800;text-align:center;text-decoration:none;cursor:pointer;transition:transform .16s ease,box-shadow .16s ease,background .16s ease}
|
||||
.button:hover{transform:translateY(-1px);background:#c0ddff;box-shadow:0 .45rem 1rem #5899f733}
|
||||
.button--secondary{border-color:#6386bd;color:#d7e8ff;background:#223755}.button--secondary:hover{color:#111c30;background:#a6ccff}
|
||||
.switch-row{display:flex;align-items:center;justify-content:space-between;gap:1.125rem;min-height:4.375rem;padding:.8rem 1rem;border:1px solid #3d5879;border-radius:.94rem;background:#1a2a43;cursor:pointer}
|
||||
.switch-row:hover{border-color:#739ad0;background:#203554}.switch-copy{display:grid;gap:.2rem;min-width:0}.switch-copy strong{font-size:.92rem}.switch-copy small{color:var(--theme-muted);font-size:.77rem;line-height:1.35}
|
||||
.switch-control{position:relative;display:block;flex:0 0 3.1875rem;width:3.1875rem;height:1.9375rem}.switch-control input{position:absolute;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}.switch-track{display:block;width:100%;height:100%;border-radius:999px;background:#62758b;pointer-events:none;transition:background .16s ease}
|
||||
.switch-track::after{content:"";position:absolute;top:2px;left:2px;width:27px;height:27px;border-radius:50%;background:#fff;box-shadow:0 1px 4px #0004;transition:transform .16s ease}.switch-control input:checked+.switch-track{background:#34c76a}.switch-control input:checked+.switch-track::after{transform:translateX(20px)}
|
||||
.messages{margin:0;padding:0;list-style:none}.alert{margin:.5rem 0 0;padding:.75rem 1rem;border-radius:.65rem;line-height:1.45}#ntfy-test-result:empty{display:none}
|
||||
.sensor-list__intro{padding-bottom:1.25rem;border-bottom:1px solid var(--theme-line)}.sensor-list__intro .eyebrow{margin-bottom:.35rem}
|
||||
.sensor-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:1.5rem 0}.sensor-card{display:flex;flex-direction:column;min-width:0;margin:0;padding:1.3rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}
|
||||
.sensor-card__heading{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem 1rem}.sensor-card__heading h3{margin:0;font-family:Georgia,ui-serif,serif;font-size:1.25rem;overflow-wrap:anywhere}.sensor-card .sensor-status{display:inline-flex;padding:.32rem .65rem;border-radius:999px;background:var(--theme-input);font-size:.78rem;white-space:nowrap}
|
||||
.sensor-status{color:var(--theme-muted);font-weight:700}.sensor-status--online{color:#64dca0}.sensor-status--delayed{color:#f5c46b}.sensor-status--offline{color:#f49aa7}
|
||||
.sensor-access{align-self:flex-start;margin-top:.7rem;padding:.25rem .55rem;border:1px solid #3d806b;border-radius:999px;color:#8be0b9;font-size:.72rem;font-weight:800}.sensor-access--off{border-color:#806b75;color:#d4b9c5}
|
||||
.sensor-card__facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem 1rem;margin:1.3rem 0}.sensor-card__facts div{min-width:0}.sensor-card__facts dt{margin-bottom:.25rem;color:var(--theme-muted);font-size:.75rem;font-weight:700}.sensor-card__facts dd{margin:0;font-size:.88rem;font-weight:600;overflow-wrap:anywhere}.sensor-card__facts code{font:inherit}.sensor-card__facts div:last-child{grid-column:1/-1}
|
||||
.sensor-card .button{margin-top:auto}.sensor-empty{grid-column:1/-1;margin:0;padding:1.5rem;border:1px dashed var(--theme-line);border-radius:1rem;color:var(--theme-muted);text-align:center;line-height:1.5}
|
||||
.sensor-form{margin-top:1.5rem;padding:1.3rem;border:1px dashed #6386bd;border-radius:1rem;background:var(--theme-surface-raised)}.sensor-form h3{margin:0;font-family:Georgia,ui-serif,serif;font-size:1.2rem}.sensor-form .help{margin-top:.3rem}.sensor-form__controls{display:grid;grid-template-columns:minmax(0,1fr) 11rem;align-items:end;gap:1rem}
|
||||
.settings-content>#sensor-card{grid-column:1/-1}
|
||||
.sensor-detail__header{display:flex;align-items:start;justify-content:space-between;gap:1rem;padding-bottom:1.2rem;border-bottom:1px solid var(--theme-line)}.sensor-detail__header .eyebrow{margin-bottom:.35rem}.sensor-detail__header h2{margin:0;font-size:clamp(1.6rem,3vw,2rem);overflow-wrap:anywhere}.sensor-close{display:inline-flex;align-items:center;gap:.35rem;flex:none;padding:.45rem .85rem;border:1px solid var(--theme-line);border-radius:999px;color:var(--theme-ink);background:var(--theme-surface-raised);font-size:.85rem;font-weight:700;text-decoration:none}.sensor-close:hover{border-color:#86ade0;background:#2b4266}.sensor-close:focus-visible{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.sensor-detail__overview{margin:1.25rem 0 1.5rem;padding:1.2rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}.sensor-detail__overview>.sensor-status{display:inline-flex;margin:0 0 1rem;padding:.35rem .7rem;border-radius:999px;background:var(--theme-input);font-size:.85rem}
|
||||
.sensor-detail__facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem 1.5rem;margin:0}.sensor-detail__facts div{min-width:0}.sensor-detail__facts dt{margin:0 0 .3rem;color:var(--theme-muted);font-size:.78rem;font-weight:700}.sensor-detail__facts dd{margin:0;overflow-wrap:anywhere;font-size:.92rem;font-weight:600}.sensor-detail__facts code{font:inherit}
|
||||
.sensor-detail__actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.sensor-detail__section{display:flex;flex-direction:column;min-width:0;padding:1.2rem;border:1px solid var(--theme-line);border-radius:1rem;background:var(--theme-surface-raised)}.sensor-detail__section h3{margin:0 0 .35rem;font-family:Georgia,ui-serif,serif;font-size:1.15rem}.sensor-detail__section>.help{margin:0}.sensor-detail__section form{display:flex;flex:1;flex-direction:column;gap:.8rem;margin-top:1rem}.sensor-detail__section form .button{margin-top:auto}.sensor-detail__section .field{width:100%}.sensor-detail__section:last-child{border-color:#945f68;background:#392432}.sensor-detail__section:last-child .button--danger{border-color:#dc7b89;color:#fff;background:#a43c50}.sensor-detail__section:last-child .button--danger:hover{background:#bd4a60}
|
||||
.sensor-confirm{display:flex;align-items:start;gap:.6rem;line-height:1.4;font-size:.82rem;cursor:pointer}.sensor-confirm input{flex:none;width:1.1rem;height:1.1rem;margin:.15rem 0 0;accent-color:#84baff}.sensor-confirm input:focus-visible{outline:3px solid #80b6ff;outline-offset:3px}
|
||||
.sensor-messages{margin-top:1rem}.token-once{margin:1.25rem 0;padding:1rem;border:1px solid #e4ad55;border-radius:.8rem;background:var(--theme-surface-raised)}.token-once code{display:block;margin:.75rem 0;padding:.7rem;border-radius:.5rem;background:var(--theme-input);overflow-wrap:anywhere;user-select:all}
|
||||
.button--danger{color:#fff;background:#991b1b}.button--danger:hover{color:#fff;background:#b91c1c}
|
||||
:root[data-theme=light] .eyebrow{color:#23578d}:root[data-theme=light] .card{box-shadow:0 1.125rem 2.8rem #20365c1a}:root[data-theme=light] .button:not(.button--secondary):not(.button--danger){color:#fff;background:#245b96}:root[data-theme=light] .button:not(.button--secondary):not(.button--danger):hover{background:#174877}:root[data-theme=light] .button--secondary{border-color:#9cc0ed;color:#245b96;background:#edf4ff}:root[data-theme=light] .button--secondary:hover{color:#fff;background:#245b96}:root[data-theme=light] .switch-row{border-color:#d4e0ef;background:#f2f7fe}:root[data-theme=light] .switch-row:hover{border-color:#9cc0ed;background:#eaf3ff}:root[data-theme=light] .switch-track{background:#c1cbd8}:root[data-theme=light] .switch-control input:checked+.switch-track{background:#34c76a}
|
||||
:root[data-theme=light] .sensor-close:hover{background:#e4efff}:root[data-theme=light] .sensor-detail__section:last-child{border-color:#ecc6cb;background:#fff5f6}:root[data-theme=light] .sensor-detail__section:last-child .button--danger{color:#fff;background:#a43c50}
|
||||
:root[data-theme=light] .sensor-access{border-color:#b8dfca;color:#256147;background:#ecf8f0}:root[data-theme=light] .sensor-access--off{border-color:#dbcbd3;color:#80556a;background:#fbf4f7}:root[data-theme=light] .sensor-form{border-color:#9cc0ed}
|
||||
@media(max-width:48rem){.settings-content{grid-template-columns:minmax(0,1fr)}.settings-shell{width:min(100% - 2.25rem,73.75rem);padding:2.5rem 0 3rem}}
|
||||
@media(max-width:48rem){.sensor-detail__actions,.sensor-list{grid-template-columns:minmax(0,1fr)}}
|
||||
@media(max-width:30rem){.sensor-detail__facts{grid-template-columns:minmax(0,1fr)}.sensor-detail__header{align-items:start}.sensor-close span{display:none}}
|
||||
@media(max-width:35rem){.card{padding:1.25rem}.sensor-form__controls{grid-template-columns:minmax(0,1fr)}}
|
||||
@media(prefers-reduced-motion:reduce){.button,.switch-track,.switch-track::after{transition:none}.button:hover{transform:none}}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
test("compass stays hidden until permission and a heading, then rotates and hides when stopped", async () => {
|
||||
const dom = new JSDOM(`<!doctype html><html><body>
|
||||
<form id="manual-report-form" action="/submit">
|
||||
<input id="manual-latitude"><input id="manual-longitude">
|
||||
<input id="manual-direction-degrees"><input id="manual-direction-accuracy">
|
||||
<div id="manual-direction-panel" hidden><button id="manual-capture-direction" type="button"></button><div id="manual-direction-status"></div></div>
|
||||
<button id="manual-submit" type="button"></button>
|
||||
<button id="burst-start" type="button"></button><div id="burst-panel"></div><strong id="burst-heading"></strong>
|
||||
<div id="burst-detail"></div><canvas id="burst-waveform"></canvas><audio id="burst-preview"></audio>
|
||||
<button id="burst-resume" type="button"></button><button id="burst-discard" type="button"></button>
|
||||
<button id="burst-stop" type="button"></button><p id="burst-error"></p>
|
||||
</form>
|
||||
<div id="manual-submission"></div>
|
||||
<div id="manual-compass" hidden><div id="manual-compass-rose"></div><span id="manual-compass-heading"></span></div>
|
||||
</body></html>`, { url: "https://example.test/" });
|
||||
const { window } = dom;
|
||||
Object.defineProperty(window, "isSecureContext", { value: true });
|
||||
let resolvePermission;
|
||||
class MockOrientation {}
|
||||
MockOrientation.requestPermission = () => new Promise((resolve) => { resolvePermission = resolve; });
|
||||
window.DeviceOrientationEvent = MockOrientation;
|
||||
const previous = Object.fromEntries(["window", "document", "navigator", "DeviceOrientationEvent"].map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
for (const [key, value] of Object.entries({ window, document: window.document, navigator: window.navigator, DeviceOrientationEvent: MockOrientation })) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
try {
|
||||
await import("../src/scripts/manual-report.js?compass=visual");
|
||||
const compass = window.document.querySelector("#manual-compass");
|
||||
const rose = window.document.querySelector("#manual-compass-rose");
|
||||
const button = window.document.querySelector("#manual-capture-direction");
|
||||
assert.equal(compass.hidden, true);
|
||||
button.click();
|
||||
assert.equal(compass.hidden, true);
|
||||
resolvePermission("granted");
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const reading = (heading) => {
|
||||
const event = new window.Event("deviceorientation");
|
||||
Object.defineProperty(event, "webkitCompassHeading", { value: heading });
|
||||
window.dispatchEvent(event);
|
||||
};
|
||||
reading(359);
|
||||
assert.equal(compass.hidden, false);
|
||||
assert.equal(rose.style.transform, "rotate(-359deg)");
|
||||
reading(1);
|
||||
assert.equal(rose.style.transform, "rotate(-361deg)");
|
||||
assert.equal(window.document.querySelector("#manual-direction-degrees").value, "1");
|
||||
button.click();
|
||||
assert.equal(compass.hidden, true);
|
||||
} finally {
|
||||
for (const [key, descriptor] of Object.entries(previous)) {
|
||||
if (descriptor === undefined) delete globalThis[key];
|
||||
else Object.defineProperty(globalThis, key, descriptor);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -924,9 +924,20 @@ msgid "Notifications / ntfy"
|
||||
msgstr "Meldingen / ntfy"
|
||||
|
||||
#: members/templates/members/user_settings.html:30
|
||||
msgid ""
|
||||
"Use a topic URL from your ntfy server. Test the current URL before saving it."
|
||||
msgstr "Gebruik een onderwerp-URL van je ntfy-server. Test de URL voordat je hem opslaat."
|
||||
msgid "Use a topic URL from your ntfy server. Test the URL before enabling notifications."
|
||||
msgstr "Gebruik een onderwerp-URL van je ntfy-server. Test de URL voordat je meldingen inschakelt."
|
||||
|
||||
msgid "Pending events"
|
||||
msgstr "Wachtende meldingen"
|
||||
|
||||
msgid "%(count)d manual"
|
||||
msgstr "%(count)d handmatig"
|
||||
|
||||
msgid "%(count)d sensor"
|
||||
msgstr "%(count)d sensor"
|
||||
|
||||
msgid "%(count)d new Pending event(s): %(sources)s."
|
||||
msgstr "%(count)d nieuwe wachtende melding(en): %(sources)s."
|
||||
|
||||
#: members/templates/members/user_settings.html:31
|
||||
msgid "Topic URL"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
RIFF0000WAVEdata
|
||||
@@ -0,0 +1 @@
|
||||
RIFF0000WAVEdata
|
||||
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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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"),
|
||||
),
|
||||
]
|
||||
Binary file not shown.
@@ -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
@@ -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")
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -39,6 +39,41 @@ class SensorSettingsTests(TestCase):
|
||||
self.assertContains(listing, "Bob'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
@@ -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
@@ -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."))
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -9,11 +9,14 @@ from django.views.static import serve
|
||||
from fireworks_detect.views import dashboard_view
|
||||
from hello.views import hello_view
|
||||
from members.language_views import set_anonymous_language
|
||||
from members.views import register
|
||||
|
||||
urlpatterns = [
|
||||
path("language/", set_anonymous_language, name="set_anonymous_language"),
|
||||
path("admin/", admin.site.urls),
|
||||
path("login/", auth_views.LoginView.as_view(template_name="members/login.html"), name="login"),
|
||||
path("register/", register, name="register"),
|
||||
path("logout/", auth_views.LogoutView.as_view(next_page="/"), name="logout"),
|
||||
path("classifications/", include("fireworks_detect.classification_urls")),
|
||||
path("settings/", include("members.settings_urls")),
|
||||
path("fireworks/", include("fireworks_detect.urls")),
|
||||
|
||||
Binary file not shown.
Binary file not shown.
+1
-1
@@ -7,7 +7,7 @@
|
||||
"dev": "concurrently --kill-others-on-fail --names django,vite --prefix-colors blue,magenta \"npm:django\" \"npm:vite\"",
|
||||
"django": "node scripts/dev-django.mjs",
|
||||
"vite": "vite",
|
||||
"build": "vite build"
|
||||
"build": "vite build && python manage.py collectstatic --noinput"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user