added compass direction finding
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# Frontend development server
|
||||
VITE_HOST=127.0.0.1
|
||||
VITE_PORT=5173
|
||||
VITE_DEV_SERVER_URL=http://127.0.0.1:5173/
|
||||
VITE_USE_DEV_SERVER=true
|
||||
|
||||
# Django development process (override the whole command for uv, docker, etc.)
|
||||
DJANGO_HOST=127.0.0.1
|
||||
DJANGO_PORT=8000
|
||||
# DJANGO_DEV_COMMAND=python manage.py runserver 127.0.0.1:8000
|
||||
|
||||
# Production build output and Django static namespace
|
||||
VITE_OUT_DIR=vite_integration/static/vite
|
||||
VITE_STATIC_PREFIX=vite
|
||||
# Must match Django STATIC_URL plus VITE_STATIC_PREFIX (for example, /static/vite/).
|
||||
VITE_BASE_URL=/static/vite/
|
||||
@@ -0,0 +1,3 @@
|
||||
vite_integration/static/vite/*
|
||||
!vite_integration/static/vite/.gitkeep
|
||||
node_modules/
|
||||
@@ -0,0 +1,91 @@
|
||||
# Portable Django + Vite integration
|
||||
|
||||
This repository did not previously contain Vite configuration, package scripts, a manifest, or Vite-aware Django templates. Its only asset setup was Django native static files. The files below add an isolated, reusable Vite integration without attaching any Vite bundle to existing pages.
|
||||
|
||||
## What is included
|
||||
|
||||
- `vite_integration/`: reusable Django app and `{% vite_asset %}` tag
|
||||
- `frontend/src/main.js`: replaceable example entry point
|
||||
- `vite.config.mjs`: Vite output, manifest, host, port, and entry configuration
|
||||
- `package.json`: `dev`, `django`, `vite`, and `build` scripts
|
||||
- `scripts/dev-django.mjs`: configurable backend process for `concurrently`
|
||||
- `.env.vite.example`: documented development and production variables
|
||||
|
||||
Vite builds into `vite_integration/static/vite/`. Because this is a Django app static directory, Django's staticfiles finders and `collectstatic` discover the manifest and built assets automatically.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python and the Django environment for the project
|
||||
- Node.js 20+ and npm
|
||||
- A configured Django `STATIC_URL` and `STATIC_ROOT` for production
|
||||
|
||||
## Install in this repository
|
||||
|
||||
```sh
|
||||
cp .env.vite.example .env.vite
|
||||
npm install
|
||||
set -a; . ./.env.vite; set +a
|
||||
npm run dev
|
||||
```
|
||||
|
||||
`npm run dev` starts Django and Vite together using `concurrently`. It runs `python manage.py runserver 127.0.0.1:8000` and Vite on `127.0.0.1:5173` by default. Change the variables before starting it, or set `DJANGO_DEV_COMMAND` to replace the backend command completely.
|
||||
|
||||
## Add an entry point to a template
|
||||
|
||||
Choose an entry point and include it once in the relevant base template:
|
||||
|
||||
```django
|
||||
{% load vite %}
|
||||
{% vite_asset "frontend/src/main.js" %}
|
||||
```
|
||||
|
||||
The tag renders Vite's HMR client and the entry point when `VITE_USE_DEV_SERVER=true`. Otherwise it reads Vite's manifest and renders the fingerprinted CSS and JavaScript under Django's static URL. See `vite_integration/templates/vite_integration/example_assets.html` for the same snippet.
|
||||
|
||||
## Production
|
||||
|
||||
```sh
|
||||
set -a; . ./.env.vite; set +a
|
||||
VITE_USE_DEV_SERVER=false npm run build
|
||||
VITE_USE_DEV_SERVER=false python manage.py collectstatic --noinput
|
||||
```
|
||||
|
||||
Build before `collectstatic`. The generated `vite/.vite/manifest.json` and `vite/assets/*` are collected with all other Django static files. Do not use the Vite development server in production.
|
||||
|
||||
## Reuse in a fresh Django project
|
||||
|
||||
Copy these files and directories:
|
||||
|
||||
```text
|
||||
vite_integration/
|
||||
frontend/src/
|
||||
scripts/dev-django.mjs
|
||||
vite.config.mjs
|
||||
package.json
|
||||
.env.vite.example
|
||||
```
|
||||
|
||||
Then add `vite_integration` to `INSTALLED_APPS`, add the template tag to a base template, configure `STATIC_URL`/`STATIC_ROOT`, install npm packages, and use the development or production commands above. The integration contains no application names, routes, or backend URLs.
|
||||
|
||||
## Configuration values to customize
|
||||
|
||||
| Variable/setting | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `DJANGO_DEV_COMMAND` | `python manage.py runserver <host>:<port>` | Complete backend development command |
|
||||
| `DJANGO_HOST`, `DJANGO_PORT` | `127.0.0.1`, `8000` | Default backend bind address |
|
||||
| `VITE_HOST`, `VITE_PORT` | `127.0.0.1`, `5173` | Vite bind address and port |
|
||||
| `VITE_DEV_SERVER_URL` | `http://127.0.0.1:5173/` | URL Django templates use for HMR |
|
||||
| `VITE_USE_DEV_SERVER` | `false` | Enables HMR tags; set only for development |
|
||||
| `VITE_ENTRY` | `frontend/src/main.js` | Vite Rollup entry point |
|
||||
| `VITE_OUT_DIR` | `vite_integration/static/vite` | Build output relative to project root |
|
||||
| `VITE_STATIC_PREFIX` | `vite` | Django static namespace for built files |
|
||||
| `VITE_BASE_URL` | `/static/vite/` | Public base URL emitted by Vite |
|
||||
| `VITE_MANIFEST_PATH` | staticfiles finder | Optional explicit manifest location |
|
||||
|
||||
Django settings override environment variables with the same names. `VITE_BASE_URL` must equal the public `STATIC_URL` followed by `VITE_STATIC_PREFIX` (for example, `/static/vite/`). A `.env.vite` file is not automatically read by Django; export/source it in the process manager, shell, container, or deployment configuration.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Vite manifest not found:** run `npm run build` before `collectstatic`; check that `VITE_OUT_DIR` ends below a Django app `static/` directory and that its final segment matches `VITE_STATIC_PREFIX`.
|
||||
- **Browser cannot reach HMR:** set `VITE_DEV_SERVER_URL` to the browser-reachable Vite address, and use matching `VITE_HOST`/`VITE_PORT`. For containers or remote browsers this is often `0.0.0.0` for the host plus a public hostname for the URL.
|
||||
- **A page fails in development:** set `VITE_USE_DEV_SERVER=true` only while `npm run vite` or `npm run dev` is running.
|
||||
- **Assets return 404 after deployment:** rerun both the build and `collectstatic`; ensure the web server serves `STATIC_ROOT` at `STATIC_URL`.
|
||||
|
||||
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.
@@ -4,17 +4,28 @@ from django.contrib import admin, messages
|
||||
from django.utils import timezone
|
||||
from django.utils.html import format_html
|
||||
|
||||
from .models import Event, PendingEvent, Sensor
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
@admin.register(ClassificationRule)
|
||||
class ClassificationRuleAdmin(admin.ModelAdmin):
|
||||
list_display = ("value", "rule_type", "enabled")
|
||||
list_filter = ("rule_type", "enabled")
|
||||
search_fields = ("value",)
|
||||
|
||||
|
||||
class ClassificationAdmin(admin.ModelAdmin):
|
||||
list_display = ("original_filename", "sensor", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("created_at",)
|
||||
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
|
||||
list_filter = ("source_type", "visually_confirmed", "created_at")
|
||||
search_fields = ("original_filename",)
|
||||
readonly_fields = ("audio_file", "sensor", "original_filename", "created_at", "pretty_classifier_response")
|
||||
fields = ("audio_file", "sensor", "original_filename", "created_at")
|
||||
readonly_fields = ("audio_file", "sensor", "h3_cell", "direction_display", "direction_accuracy_degrees", "original_filename", "created_at", "pretty_classifier_response")
|
||||
fields = ("audio_file", "sensor", "source_type", "occurrences", "location", "latitude", "longitude", "h3_cell", "direction_display", "direction_accuracy_degrees", "visually_confirmed", "original_filename", "created_at")
|
||||
change_form_template = "admin/fireworks_detect/classification_audio_change_form.html"
|
||||
|
||||
@admin.display(description="Direction")
|
||||
def direction_display(self, obj):
|
||||
return obj.direction_display
|
||||
|
||||
@admin.display(description="Classifier response")
|
||||
def pretty_classifier_response(self, obj):
|
||||
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.urls import path
|
||||
|
||||
from .views import classification_blacklist, classification_whitelist
|
||||
|
||||
|
||||
app_name = "classification_rules"
|
||||
|
||||
urlpatterns = [
|
||||
path("whitelist/", classification_whitelist, name="whitelist"),
|
||||
path("blacklist/", classification_blacklist, name="blacklist"),
|
||||
]
|
||||
@@ -0,0 +1,42 @@
|
||||
import h3
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
|
||||
|
||||
|
||||
def h3_resolution():
|
||||
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
|
||||
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
|
||||
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
|
||||
return resolution
|
||||
|
||||
|
||||
def cell_from_coordinates(latitude, longitude):
|
||||
if latitude is None or longitude is None:
|
||||
return None
|
||||
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
|
||||
|
||||
|
||||
def cell_boundary(cell):
|
||||
try:
|
||||
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_center(cell):
|
||||
"""Return the centre of an H3 cell without exposing its source coordinate."""
|
||||
try:
|
||||
latitude, longitude = h3.cell_to_latlng(cell)
|
||||
return [latitude, longitude]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_disk(cell, distance=1):
|
||||
try:
|
||||
return sorted(h3.grid_disk(cell, distance))
|
||||
except (ValueError, h3.H3Error):
|
||||
return []
|
||||
@@ -0,0 +1,33 @@
|
||||
import h3
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
|
||||
|
||||
|
||||
def h3_resolution():
|
||||
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
|
||||
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
|
||||
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
|
||||
return resolution
|
||||
|
||||
|
||||
def cell_from_coordinates(latitude, longitude):
|
||||
if latitude is None or longitude is None:
|
||||
return None
|
||||
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
|
||||
|
||||
|
||||
def cell_boundary(cell):
|
||||
try:
|
||||
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
|
||||
except (ValueError, h3.H3Error):
|
||||
return None
|
||||
|
||||
|
||||
def cell_disk(cell, distance=1):
|
||||
try:
|
||||
return sorted(h3.grid_disk(cell, distance))
|
||||
except (ValueError, h3.H3Error):
|
||||
return []
|
||||
@@ -0,0 +1 @@
|
||||
"""Management commands for fireworks detection."""
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
"""Fireworks detection management commands."""
|
||||
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from fireworks_detect.h3_utils import cell_from_coordinates, h3_resolution
|
||||
from fireworks_detect.models import Event, PendingEvent
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Populate H3 cells for coordinate-bearing Pending and approved events."
|
||||
|
||||
def handle(self, *args, **options):
|
||||
updated = 0
|
||||
for model in (PendingEvent, Event):
|
||||
for record in model.objects.exclude(latitude__isnull=True).exclude(longitude__isnull=True):
|
||||
h3_cell = cell_from_coordinates(record.latitude, record.longitude)
|
||||
if record.h3_cell == h3_cell:
|
||||
continue
|
||||
record.h3_cell = h3_cell
|
||||
record.save(update_fields=["h3_cell"])
|
||||
updated += 1
|
||||
|
||||
self.stdout.write(
|
||||
self.style.SUCCESS(
|
||||
f"Updated {updated} record(s) at H3 resolution {h3_resolution()}."
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,35 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("fireworks_detect", "0002_sensor_event_sensor_pendingevent_sensor"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="ClassificationRule",
|
||||
fields=[
|
||||
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
||||
("value", models.CharField(max_length=255)),
|
||||
(
|
||||
"rule_type",
|
||||
models.CharField(
|
||||
choices=[("whitelist", "Whitelist"), ("blacklist", "Blacklist")],
|
||||
max_length=10,
|
||||
),
|
||||
),
|
||||
("enabled", models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
"ordering": ["value"],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="classificationrule",
|
||||
constraint=models.UniqueConstraint(fields=("value", "rule_type"), name="unique_classification_rule"),
|
||||
),
|
||||
]
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 20:59
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0003_classificationrule'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='location',
|
||||
field=models.CharField(blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='occurrences',
|
||||
field=models.PositiveIntegerField(default=1),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='source_type',
|
||||
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='visually_confirmed',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='location',
|
||||
field=models.CharField(blank=True, max_length=255),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='occurrences',
|
||||
field=models.PositiveIntegerField(default=1),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='source_type',
|
||||
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='visually_confirmed',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='event',
|
||||
name='audio_file',
|
||||
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='pendingevent',
|
||||
name='audio_file',
|
||||
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
|
||||
),
|
||||
]
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 21:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0004_event_location_event_occurrences_event_source_type_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 21:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0005_event_latitude_event_longitude_pendingevent_latitude_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='h3_cell',
|
||||
field=models.CharField(blank=True, db_index=True, max_length=20),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='h3_cell',
|
||||
field=models.CharField(blank=True, db_index=True, max_length=20),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,43 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 07:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('fireworks_detect', '0006_event_h3_cell_pendingevent_h3_cell'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_accuracy_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='event',
|
||||
name='direction_source',
|
||||
field=models.CharField(blank=True, max_length=32),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_accuracy_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_degrees',
|
||||
field=models.FloatField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pendingevent',
|
||||
name='direction_source',
|
||||
field=models.CharField(blank=True, max_length=32),
|
||||
),
|
||||
]
|
||||
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -1,6 +1,8 @@
|
||||
import math
|
||||
import secrets
|
||||
|
||||
from django.contrib.auth.hashers import check_password, make_password
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.files.storage import default_storage
|
||||
from django.db import models, transaction
|
||||
from django.utils import timezone
|
||||
@@ -44,13 +46,48 @@ class Sensor(models.Model):
|
||||
self.save(update_fields=fields)
|
||||
|
||||
|
||||
class ClassificationRule(models.Model):
|
||||
"""A configurable inclusion or exclusion rule for a classification label."""
|
||||
|
||||
class RuleType(models.TextChoices):
|
||||
WHITELIST = "whitelist", "Whitelist"
|
||||
BLACKLIST = "blacklist", "Blacklist"
|
||||
|
||||
value = models.CharField(max_length=255)
|
||||
rule_type = models.CharField(max_length=10, choices=RuleType.choices)
|
||||
enabled = models.BooleanField(default=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ["value"]
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["value", "rule_type"], name="unique_classification_rule"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.value} ({self.get_rule_type_display()})"
|
||||
|
||||
|
||||
class ClassifiedAudio(models.Model):
|
||||
"""Shared fields for a classifier response and its original audio upload."""
|
||||
|
||||
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d")
|
||||
class SourceType(models.TextChoices):
|
||||
SENSOR = "sensor", "Sensor"
|
||||
MANUAL = "manual", "Manual report"
|
||||
|
||||
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d", blank=True)
|
||||
sensor = models.ForeignKey(Sensor, null=True, blank=True, on_delete=models.SET_NULL, related_name="%(class)s_records")
|
||||
original_filename = models.CharField(max_length=255)
|
||||
classifier_response = models.JSONField()
|
||||
source_type = models.CharField(max_length=10, choices=SourceType.choices, default=SourceType.SENSOR)
|
||||
occurrences = models.PositiveIntegerField(default=1)
|
||||
location = models.CharField(max_length=255, blank=True)
|
||||
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True)
|
||||
h3_cell = models.CharField(max_length=20, blank=True, db_index=True)
|
||||
visually_confirmed = models.BooleanField(default=False)
|
||||
direction_degrees = models.FloatField(null=True, blank=True)
|
||||
direction_accuracy_degrees = models.FloatField(null=True, blank=True)
|
||||
direction_source = models.CharField(max_length=32, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
@@ -60,6 +97,36 @@ class ClassifiedAudio(models.Model):
|
||||
def __str__(self):
|
||||
return self.original_filename
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
errors = {}
|
||||
if self.direction_degrees is not None and (
|
||||
not math.isfinite(self.direction_degrees) or not 0 <= self.direction_degrees < 360
|
||||
):
|
||||
errors["direction_degrees"] = "Direction must be a finite value from 0 up to, but not including, 360 degrees."
|
||||
if self.direction_accuracy_degrees is not None and (
|
||||
not math.isfinite(self.direction_accuracy_degrees) or self.direction_accuracy_degrees < 0
|
||||
):
|
||||
errors["direction_accuracy_degrees"] = "Compass accuracy must be a finite, non-negative value."
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
|
||||
|
||||
@property
|
||||
def direction_cardinal(self):
|
||||
if self.direction_degrees is None:
|
||||
return None
|
||||
directions = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
|
||||
return directions[int((self.direction_degrees + 22.5) % 360 // 45)]
|
||||
|
||||
|
||||
@property
|
||||
def direction_display(self):
|
||||
if self.direction_degrees is None:
|
||||
return "—"
|
||||
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
|
||||
|
||||
|
||||
@property
|
||||
def predictions(self):
|
||||
predictions = self.classifier_response.get("predictions", [])
|
||||
@@ -120,6 +187,16 @@ class PendingEvent(ClassifiedAudio):
|
||||
sensor=self.sensor,
|
||||
original_filename=self.original_filename,
|
||||
classifier_response=self.classifier_response,
|
||||
source_type=self.source_type,
|
||||
occurrences=self.occurrences,
|
||||
location=self.location,
|
||||
latitude=self.latitude,
|
||||
longitude=self.longitude,
|
||||
h3_cell=self.h3_cell,
|
||||
visually_confirmed=self.visually_confirmed,
|
||||
direction_degrees=self.direction_degrees,
|
||||
direction_accuracy_degrees=self.direction_accuracy_degrees,
|
||||
direction_source=self.direction_source,
|
||||
)
|
||||
self.delete()
|
||||
return event
|
||||
|
||||
@@ -1 +1,27 @@
|
||||
<h2>{{ event.original_filename }}</h2><p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · {{ result.duration_seconds|default:"—" }} seconds · {{ result.frames_analysed|default:"—" }} frames</p><h3>Top sound classes</h3>{% for prediction in predictions %}<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>{% empty %}<p class="empty">No predictions returned.</p>{% endfor %}<h3>Notable moments</h3>{% for prediction in peak_predictions %}<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>{% empty %}<p class="empty">No peak events returned.</p>{% endfor %}
|
||||
{% if event.source_type == "manual" %}
|
||||
<h2>Manual fireworks report</h2>
|
||||
<p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · Reported manually</p>
|
||||
<h3>Report details</h3>
|
||||
<div class="prediction prediction--firework"><strong>Occurrences</strong><span>{{ event.occurrences }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Location</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Captured location</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
|
||||
<div class="prediction prediction--firework"><strong>Direction</strong><span>{{ event.direction_display }}</span></div>
|
||||
{% if event.direction_accuracy_degrees is not None %}<div class="prediction prediction--firework"><strong>Compass accuracy</strong><span>±{{ event.direction_accuracy_degrees|floatformat:"-1" }}°</span></div>{% endif %}
|
||||
<div class="prediction prediction--firework"><strong>Visually confirmed</strong><span>{% if event.visually_confirmed %}Yes{% else %}No{% endif %}</span></div>
|
||||
<p class="empty">This was a manual report; there is no audio classification attached.</p>
|
||||
{% else %}
|
||||
<h2>{{ event.original_filename }}</h2>
|
||||
<p class="meta">Approved {{ event.approved_at|date:"j M Y, H:i" }} · {{ result.duration_seconds|default:"—" }} seconds · {{ result.frames_analysed|default:"—" }} frames</p>
|
||||
<h3>Top sound classes</h3>
|
||||
{% for prediction in predictions %}
|
||||
<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.score_display }}</span></div>
|
||||
{% empty %}
|
||||
<p class="empty">No predictions returned.</p>
|
||||
{% endfor %}
|
||||
<h3>Notable moments</h3>
|
||||
{% for prediction in peak_predictions %}
|
||||
<div class="prediction prediction--{{ prediction.kind }}"><strong>{{ prediction.label }}</strong><span>{{ prediction.time_seconds|default:"—" }}s · {{ prediction.score_display }}</span></div>
|
||||
{% empty %}
|
||||
<p class="empty">No peak events returned.</p>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
@@ -1 +1,18 @@
|
||||
{% if events %}{% for event in events %}<button class="event" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML"><span><strong>{{ event.primary_label }}</strong><br><small>{{ event.original_filename }} · {{ event.duration }}s</small></span><span class="badge">{{ event.primary_score }} →</span></button>{% endfor %}{% else %}<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>{% endif %}
|
||||
{% if events %}
|
||||
{% for event in events %}
|
||||
<button class="event{% if event.source_type == 'manual' %} event--manual{% endif %}" {% if event.source_type == 'manual' %}style="border-color:#e2934a;background:linear-gradient(90deg,#70401e,#15223f);"{% endif %} hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
|
||||
<span>
|
||||
{% if event.source_type == "manual" %}
|
||||
<strong>Manual fireworks report</strong><br>
|
||||
<small>{{ event.occurrences }} occurrence{{ event.occurrences|pluralize }}{% if event.location %} · {{ event.location }}{% endif %}</small>
|
||||
{% else %}
|
||||
<strong>{{ event.primary_label }}</strong><br>
|
||||
<small>{{ event.original_filename }} · {{ event.duration }}s</small>
|
||||
{% endif %}
|
||||
</span>
|
||||
<span class="badge">{% if event.source_type == "manual" %}Manual →{% else %}{{ event.primary_score }} →{% endif %}</span>
|
||||
</button>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<p class="empty">No approved events yet. Submit a classification, then approve it from the Pending page in admin.</p>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<div id="manual-submission" role="status">
|
||||
{% if error %}
|
||||
<strong>Could not report fireworks</strong><p>{{ error }}</p>
|
||||
{% else %}
|
||||
<strong>Report sent to Pending</strong><p>{{ pending.occurrences }} occurrence{{ pending.occurrences|pluralize }} reported at {{ pending.created_at|date:"H:i" }}.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
@@ -16,10 +16,10 @@
|
||||
}
|
||||
.topbar { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom:3.5rem; }.brand { display:flex; align-items:center; gap:.7rem; color:var(--ink); font-size:.9rem; font-weight:800; letter-spacing:.1em; text-decoration:none; text-transform:uppercase; }.brand-mark { display:grid; width:2.25rem; aspect-ratio:1; place-items:center; border-radius:.75rem; color:#141022; background:linear-gradient(135deg,#fcd34d,#fb7185); box-shadow:0 .5rem 1.5rem #fb718550; }.nav { display:flex; gap:.35rem; padding:.25rem; border:1px solid var(--line); border-radius:.75rem; background:#111a31a6; }.nav a { padding:.5rem .75rem; border-radius:.5rem; color:var(--muted); font-size:.86rem; font-weight:700; text-decoration:none; }.nav a[aria-current="page"] { color:var(--ink); background:#2a3b67; }
|
||||
.kicker { margin:0 0 .65rem; color:#bfdbfe; font-size:.76rem; font-weight:800; letter-spacing:.14em; text-transform:uppercase; }.headline { display:flex; align-items:end; justify-content:space-between; gap:2rem; margin-bottom:2rem; }.headline h1 { margin:0; font-size:clamp(2.3rem,5vw,4.5rem); line-height:.98; letter-spacing:-.06em; }.headline p { max-width:30rem; margin:0; color:var(--muted); line-height:1.6; }
|
||||
.filters { display:grid; grid-template-columns:1.3fr repeat(3,minmax(8rem,1fr)) auto; gap:.75rem; align-items:end; margin-bottom:1rem; padding:1rem; border:1px solid var(--line); border-radius:1.1rem; background:#121d37d9; box-shadow:0 1rem 3rem #03071466; }.filter { display:grid; gap:.35rem; }.filter label { color:#9fb1d5; font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }.filter select,.filter input { width:100%; min-height:2.65rem; border:1px solid #354a77; border-radius:.65rem; padding:0 .75rem; color:var(--ink); font:inherit; background:#0c1428; }.filter select:focus,.filter input:focus { outline:2px solid #82b5ff; outline-offset:2px; }.mock-tag { align-self:center; padding:.46rem .65rem; border:1px solid #4a5f8e; border-radius:999px; color:#c9d8f6; font-size:.75rem; font-weight:700; white-space:nowrap; background:#1d2b4e; }
|
||||
.map-panel { overflow:hidden; border:1px solid var(--line); border-radius:1.25rem; background:var(--surface); box-shadow:0 1.5rem 4rem #0206168a; }.map-header { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.2rem; border-bottom:1px solid var(--line); }.map-header strong { font-size:.95rem; }.live { display:flex; align-items:center; gap:.45rem; color:#a7f3d0; font-size:.8rem; }.live i { width:.5rem; height:.5rem; border-radius:50%; background:var(--green); box-shadow:0 0 0 .25rem #34d3992e; }.map-wrap { position:relative; }.map { height:clamp(30rem,65vh,45rem); background:#dce4cf; }.legend { position:absolute; z-index:600; right:1rem; bottom:1rem; width:min(15rem,calc(100% - 2rem)); padding:.85rem; border:1px solid #344973; border-radius:.8rem; color:#dce7fe; font-size:.78rem; background:#101a31e8; box-shadow:0 .75rem 2rem #05091480; backdrop-filter:blur(10px); }.legend h2 { margin:0 0 .6rem; font-size:.82rem; }.legend div { display:flex; align-items:center; gap:.5rem; margin-top:.4rem; }.legend-dot { width:.7rem; height:.7rem; border:2px solid #f2c56b; border-radius:50%; background:#ed8e2e88; }.legend-ring { width:.85rem; height:.85rem; border:2px solid #a98af7; border-radius:50%; background:#8b5cf633; }.legend-line { width:1.1rem; border-top:2px dashed #644b9c; }.sensor-icon { display:grid; width:2.1rem; height:2.1rem; place-items:center; border:2px solid #e6edff; border-radius:50%; color:#14203b; font-size:.72rem; font-weight:900; background:linear-gradient(135deg,#a5c8ff,#c4b5fd); box-shadow:0 .2rem .8rem #18275080; }.source-icon { display:grid; width:2.45rem; height:2.45rem; place-items:center; border:2px solid #fff3d5; border-radius:50% 50% 50% 0; color:#452000; font-size:1.15rem; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; transform:rotate(-45deg); }.source-icon span { transform:rotate(45deg); }.direction-arrow { display:block; color:#5c408d; font-size:1.5rem; font-weight:900; line-height:1; text-shadow:0 .1rem .4rem #fff8; }
|
||||
.leaflet-control-zoom a { color:#243456!important; }.leaflet-popup-content-wrapper,.leaflet-popup-tip { color:#e9f1ff; background:#14203a; }.leaflet-popup-content { margin:.75rem .9rem; font-family:inherit; }.popup-title { display:block; margin-bottom:.2rem; font-weight:800; }.popup-meta { color:#a9b9d8; font-size:.78rem; }
|
||||
@media (max-width:52rem) { .shell { width:min(100% - 1.25rem,80rem); }.topbar { margin-bottom:2.5rem; }.headline { align-items:start; flex-direction:column; gap:1rem; }.filters { grid-template-columns:1fr 1fr; }.filters .filter:first-child { grid-column:1/-1; }.mock-tag { justify-self:start; }.map { height:32rem; } }
|
||||
.filters { display:grid; grid-template-columns:repeat(5,minmax(8rem,1fr)) auto auto; gap:.75rem; align-items:end; margin-bottom:1rem; padding:1rem; border:1px solid var(--line); border-radius:1.1rem; background:#121d37d9; box-shadow:0 1rem 3rem #03071466; }.filter { display:grid; gap:.35rem; }.filter label { color:#9fb1d5; font-size:.7rem; font-weight:800; letter-spacing:.08em; text-transform:uppercase; }.filter select,.filter input { width:100%; min-height:2.65rem; border:1px solid #354a77; border-radius:.65rem; padding:0 .75rem; color:var(--ink); font:inherit; background:#0c1428; }.filter select:focus,.filter input:focus { outline:2px solid #82b5ff; outline-offset:2px; }.filter-submit { min-height:2.65rem; border:1px solid #8ab7ff; border-radius:.65rem; padding:0 1rem; color:#101a31; font:inherit; font-weight:800; background:#b9d6ff; cursor:pointer; }.map-tag { align-self:center; padding:.46rem .65rem; border:1px solid #4a5f8e; border-radius:999px; color:#c9d8f6; font-size:.75rem; font-weight:700; white-space:nowrap; background:#1d2b4e; }
|
||||
.map-panel { overflow:hidden; border:1px solid var(--line); border-radius:1.25rem; background:var(--surface); box-shadow:0 1.5rem 4rem #0206168a; }.map-header { display:flex; align-items:center; justify-content:space-between; gap:1rem; padding:1rem 1.2rem; border-bottom:1px solid var(--line); }.map-header strong { font-size:.95rem; }.live { display:flex; align-items:center; gap:.45rem; color:#a7f3d0; font-size:.8rem; }.live i { width:.5rem; height:.5rem; border-radius:50%; background:var(--green); box-shadow:0 0 0 .25rem #34d3992e; }.map-wrap { position:relative; }.map { height:clamp(30rem,65vh,45rem); background:#dce4cf; }.legend { position:absolute; z-index:600; right:1rem; bottom:1rem; width:min(15rem,calc(100% - 2rem)); padding:.85rem; border:1px solid #344973; border-radius:.8rem; color:#dce7fe; font-size:.78rem; background:#101a31e8; box-shadow:0 .75rem 2rem #05091480; backdrop-filter:blur(10px); }.legend h2 { margin:0 0 .6rem; font-size:.82rem; }.legend div { display:flex; align-items:center; gap:.5rem; margin-top:.4rem; }.legend-dot { width:.7rem; height:.7rem; border:2px solid #f2c56b; border-radius:50%; background:#ed8e2e88; }.legend-ring { width:.85rem; height:.85rem; border:2px solid #a98af7; border-radius:50%; background:#8b5cf633; }.legend-line { width:1.1rem; border-top:2px dashed #644b9c; }.report-icon { display:grid; width:2.3rem; height:2.3rem; place-items:center; border:2px solid #fff3d5; border-radius:50%; color:#452000; font-size:1rem; font-weight:900; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; }.source-icon { display:grid; width:2.45rem; height:2.45rem; place-items:center; border:2px solid #fff3d5; border-radius:50% 50% 50% 0; color:#452000; font-size:1.15rem; background:#f7a52f; box-shadow:0 .3rem 1rem #a84f2670; transform:rotate(-45deg); }.source-icon span { transform:rotate(45deg); }.direction-marker { display:grid; width:3.5rem; height:3.5rem; place-items:center; border:3px solid #fff7e6; border-radius:50%; color:#fff; background:#6d45a0; box-shadow:0 .3rem 1rem #281642b3; }.direction-marker span { display:block; font-size:2.45rem; font-weight:950; line-height:1; text-shadow:0 .1rem .25rem #1e1136; transform-origin:center; }
|
||||
.map-compass { position:relative; width:5rem; height:5rem; border:2px solid #eaf1ff; border-radius:50%; color:#f7fbff; font-size:.72rem; font-weight:900; background:#111a31e8; box-shadow:0 .5rem 1.5rem #05091480; backdrop-filter:blur(8px); }.map-compass span { position:absolute; display:grid; place-items:center; }.map-compass .compass-n { top:.35rem; left:50%; transform:translateX(-50%); color:#ffd18c; }.map-compass .compass-e { top:50%; right:.45rem; transform:translateY(-50%); }.map-compass .compass-s { bottom:.35rem; left:50%; transform:translateX(-50%); }.map-compass .compass-w { top:50%; left:.45rem; transform:translateY(-50%); }.map-compass .compass-needle { top:1.3rem; left:50%; color:#ffd18c; font-size:2rem; line-height:1; transform:translateX(-50%); text-shadow:0 .1rem .35rem #3b1b48; }.leaflet-control-zoom a { color:#243456!important; }.leaflet-popup-content-wrapper,.leaflet-popup-tip { color:#e9f1ff; background:#14203a; }.leaflet-popup-content { margin:.75rem .9rem; font-family:inherit; }.popup-title { display:block; margin-bottom:.2rem; font-weight:800; }.popup-meta { color:#a9b9d8; font-size:.78rem; }
|
||||
@media (max-width:52rem) { .shell { width:min(100% - 1.25rem,80rem); }.topbar { margin-bottom:2.5rem; }.headline { align-items:start; flex-direction:column; gap:1rem; }.filters { grid-template-columns:1fr 1fr; }.filters .filter:first-child { grid-column:1/-1; }.map { height:32rem; } }
|
||||
@media (max-width:30rem) { .nav a { padding:.5rem; }.filters { grid-template-columns:1fr; }.filters .filter:first-child { grid-column:auto; } }
|
||||
</style>
|
||||
</head>
|
||||
@@ -34,59 +34,125 @@
|
||||
</header>
|
||||
|
||||
<section class="headline" aria-labelledby="map-title">
|
||||
<div><p class="kicker">Future event intelligence</p><h1 id="map-title">Sound activity map.</h1></div>
|
||||
<p>A concept view of sensors triangulating a likely source. This uses entirely mock data for Heerenveen, ready for future incoming event records.</p>
|
||||
<div><p class="kicker">Manual report intelligence</p><h1 id="map-title">Sound activity map.</h1></div>
|
||||
<p>Reviewed manual reports with a captured location appear as their H3 cell, not their precise coordinates. Saved phone compass readings show the reported direction of the sound.</p>
|
||||
</section>
|
||||
|
||||
<section class="filters" aria-label="Mock event filters">
|
||||
<div class="filter"><label for="event-type">Event type</label><select id="event-type"><option>All sound events</option><option>Possible fireworks</option><option>Privacy-filtered speech</option></select></div>
|
||||
<div class="filter"><label for="from-date">From</label><input id="from-date" type="date" value="2026-09-19"></div>
|
||||
<div class="filter"><label for="range">Range</label><select id="range"><option>This week</option><option>Today</option><option>Last 30 days</option></select></div>
|
||||
<div class="filter"><label for="confidence">Confidence</label><select id="confidence"><option>Any confidence</option><option>High confidence</option><option>Review needed</option></select></div>
|
||||
<span class="mock-tag">Mock data</span>
|
||||
</section>
|
||||
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="Map filters">
|
||||
<div class="filter"><label for="event-source">Source</label><select id="event-source" disabled><option selected>Manual reports</option><option>Sensor events — coming soon</option></select></div>
|
||||
<div class="filter"><label for="range">Period</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>Last 7 days</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>Last 2 weeks</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>Last 30 days</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>All time</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>Custom range</option></select></div>
|
||||
<div class="filter"><label for="from-date">From</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
|
||||
<div class="filter"><label for="to-date">To</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
|
||||
<div class="filter"><label for="visual">Visual confirmation</label><select id="visual" name="visual"><option value="all" {% if map_filters.visual == "all" %}selected{% endif %}>Any report</option><option value="yes" {% if map_filters.visual == "yes" %}selected{% endif %}>Visually confirmed</option><option value="no" {% if map_filters.visual == "no" %}selected{% endif %}>Not visually confirmed</option></select></div>
|
||||
<button class="filter-submit" type="submit">Apply filters</button>
|
||||
<span class="map-tag">{{ mapped_event_count }} report{{ mapped_event_count|pluralize }}</span>
|
||||
</form>
|
||||
|
||||
<section class="map-panel" aria-label="Mock sound event map of Heerenveen">
|
||||
<div class="map-header"><strong>Heerenveen, Netherlands</strong><span class="live"><i></i> 3 sensors simulated</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" aria-label="Interactive map centered on Heerenveen"></div>
|
||||
<aside class="legend" aria-label="Map legend"><h2>Triangulation estimate</h2><div><span class="legend-dot"></span> Higher-confidence source area</div><div><span class="legend-ring"></span> Broader possible area</div><div><span class="legend-line"></span> Simulated direction of arrival</div></aside>
|
||||
<section class="map-panel" aria-label="Manual fireworks report map">
|
||||
<div class="map-header"><strong>Manual reports · privacy-preserving H3 cells</strong><span class="live"><i></i> H3 resolution {{ h3_resolution }} · sensor layer disabled</span></div>
|
||||
<div class="map-wrap"><div id="event-map" class="map" aria-label="Interactive map of manual fireworks reports"></div>
|
||||
<aside class="legend" aria-label="Map legend"><h2>Manual reports</h2><div><span class="legend-dot"></span> Report marker at H3-cell centre</div><div><span class="legend-ring"></span> H3 cell (resolution {{ h3_resolution }})</div><div><span class="legend-line"></span> Saved compass direction</div></aside>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
{{ h3_cells|json_script:"h3-cells-data" }}
|
||||
{{ map_events|json_script:"map-events-data" }}
|
||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||
<script>
|
||||
const map = L.map('event-map', { zoomControl: false, scrollWheelZoom: false }).setView([52.9512478, 5.943674], 14);
|
||||
L.control.zoom({ position: 'bottomleft' }).addTo(map);
|
||||
L.tileLayer('https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png', {
|
||||
const map = L.map("event-map", { zoomControl: false, scrollWheelZoom: false }).setView([52.1326, 5.2913], 7);
|
||||
L.control.zoom({ position: "bottomleft" }).addTo(map);
|
||||
const compassControl = L.control({ position: "topright" });
|
||||
compassControl.onAdd = () => {
|
||||
const compass = L.DomUtil.create("div", "map-compass");
|
||||
compass.setAttribute("role", "img");
|
||||
compass.setAttribute("aria-label", "Map compass: north is up");
|
||||
compass.innerHTML = "<span class=\"compass-n\">N</span><span class=\"compass-e\">E</span><span class=\"compass-s\">S</span><span class=\"compass-w\">W</span><span class=\"compass-needle\">↑</span>";
|
||||
L.DomEvent.disableClickPropagation(compass);
|
||||
return compass;
|
||||
};
|
||||
compassControl.addTo(map);
|
||||
L.tileLayer("https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png", {
|
||||
maxZoom: 18,
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
attribution: "© OpenStreetMap contributors",
|
||||
}).addTo(map);
|
||||
|
||||
const estimatedSource = [52.9501, 5.9466];
|
||||
const sensors = [
|
||||
{ name: 'Sensor 1', position: [52.9570, 5.9335], confidence: '91% direction confidence' },
|
||||
{ name: 'Sensor 2', position: [52.9586, 5.9508], confidence: '86% direction confidence' },
|
||||
{ name: 'Sensor 3', position: [52.9458, 5.9370], confidence: '78% direction confidence' },
|
||||
];
|
||||
const h3Cells = JSON.parse(document.getElementById("h3-cells-data").textContent);
|
||||
const reports = JSON.parse(document.getElementById("map-events-data").textContent);
|
||||
const bounds = L.latLngBounds([]);
|
||||
|
||||
L.circle(estimatedSource, { radius: 1020, color: '#8b5cf6', weight: 1.5, fillColor: '#8b5cf6', fillOpacity: 0.10, dashArray: '5 8' }).addTo(map);
|
||||
L.circle(estimatedSource, { radius: 370, color: '#f59e0b', weight: 2, fillColor: '#f59e0b', fillOpacity: 0.28 }).addTo(map);
|
||||
const sourceIcon = L.divIcon({ className: '', html: '<div class="source-icon"><span>✦</span></div>', iconSize: [39, 39], iconAnchor: [20, 32] });
|
||||
L.marker(estimatedSource, { icon: sourceIcon }).addTo(map).bindPopup('<span class="popup-title">Estimated sound source</span><span class="popup-meta">High-confidence area · mock event</span>');
|
||||
h3Cells.forEach((cell) => {
|
||||
const polygon = L.polygon(cell.boundary, {
|
||||
color: "#f59e0b", weight: 2, fillColor: "#f59e0b", fillOpacity: 0.25,
|
||||
}).addTo(map);
|
||||
polygon.bindPopup(
|
||||
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
|
||||
"<span class=\"popup-meta\">" + cell.reports + " reports · " + cell.occurrences +
|
||||
" occurrences · resolution {{ h3_resolution }}</span>"
|
||||
);
|
||||
bounds.extend(L.latLngBounds(cell.boundary));
|
||||
});
|
||||
|
||||
function bearing(from, to) {
|
||||
const lat = ((from[0] + to[0]) / 2) * Math.PI / 180;
|
||||
return Math.atan2((to[1] - from[1]) * Math.cos(lat), to[0] - from[0]) * 180 / Math.PI;
|
||||
function cardinalDirection(degrees) {
|
||||
const directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
|
||||
return directions[Math.floor(((degrees + 22.5) % 360) / 45)];
|
||||
}
|
||||
sensors.forEach((sensor, index) => {
|
||||
const line = L.polyline([sensor.position, estimatedSource], { color: '#60438f', weight: 2, opacity: 0.85, dashArray: '8 9' }).addTo(map);
|
||||
line.bindTooltip('Direction of arrival', { sticky: true });
|
||||
const arrowPosition = [sensor.position[0] + (estimatedSource[0] - sensor.position[0]) * 0.58, sensor.position[1] + (estimatedSource[1] - sensor.position[1]) * 0.58];
|
||||
const arrowIcon = L.divIcon({ className: '', html: `<span class="direction-arrow" style="transform:rotate(${bearing(sensor.position, estimatedSource)}deg)">↑</span>`, iconSize: [22, 22], iconAnchor: [11, 11] });
|
||||
L.marker(arrowPosition, { icon: arrowIcon, interactive: false }).addTo(map);
|
||||
const sensorIcon = L.divIcon({ className: '', html: `<div class="sensor-icon">${index + 1}</div>`, iconSize: [34, 34], iconAnchor: [17, 17] });
|
||||
L.marker(sensor.position, { icon: sensorIcon }).addTo(map).bindPopup(`<span class="popup-title">${sensor.name}</span><span class="popup-meta">${sensor.confidence}<br>Mock microphone node</span>`);
|
||||
|
||||
function destinationPoint(origin, bearingDegrees, distanceMetres) {
|
||||
const earthRadius = 6378137;
|
||||
const bearing = bearingDegrees * Math.PI / 180;
|
||||
const latitude = origin[0] * Math.PI / 180;
|
||||
const longitude = origin[1] * Math.PI / 180;
|
||||
const angularDistance = distanceMetres / earthRadius;
|
||||
const targetLatitude = Math.asin(
|
||||
Math.sin(latitude) * Math.cos(angularDistance) +
|
||||
Math.cos(latitude) * Math.sin(angularDistance) * Math.cos(bearing)
|
||||
);
|
||||
const targetLongitude = longitude + Math.atan2(
|
||||
Math.sin(bearing) * Math.sin(angularDistance) * Math.cos(latitude),
|
||||
Math.cos(angularDistance) - Math.sin(latitude) * Math.sin(targetLatitude)
|
||||
);
|
||||
return [targetLatitude * 180 / Math.PI, targetLongitude * 180 / Math.PI];
|
||||
}
|
||||
|
||||
const reportIcon = L.divIcon({
|
||||
className: "", html: "<div class=\"report-icon\">✦</div>", iconSize: [37, 37], iconAnchor: [19, 19],
|
||||
});
|
||||
reports.forEach((report) => {
|
||||
const visualStatus = report.visually_confirmed ? "Visually confirmed" : "Not visually confirmed";
|
||||
let detail = report.occurrences + " occurrence" + (report.occurrences === 1 ? "" : "s") +
|
||||
" · " + visualStatus + "<br>Reported " + report.reported_on;
|
||||
if (report.direction_degrees !== null) {
|
||||
detail += "<br>Compass direction " + Math.round(report.direction_degrees) + "° (" + cardinalDirection(report.direction_degrees) + ")";
|
||||
if (report.direction_accuracy_degrees !== null) {
|
||||
detail += " (±" + Math.round(report.direction_accuracy_degrees) + "°)";
|
||||
}
|
||||
}
|
||||
L.marker(report.center, { icon: reportIcon }).addTo(map).bindPopup(
|
||||
"<span class=\"popup-title\">Manual report · H3 " + report.cell + "</span>" +
|
||||
"<span class=\"popup-meta\">" + detail + "</span>"
|
||||
);
|
||||
|
||||
if (report.direction_degrees !== null) {
|
||||
const arrowEnd = destinationPoint(report.center, report.direction_degrees, 900);
|
||||
L.polyline([report.center, arrowEnd], { color: "#fff7e6", weight: 9, opacity: 0.8 }).addTo(map);
|
||||
L.polyline([report.center, arrowEnd], { color: "#6d45a0", weight: 5, opacity: 1 }).addTo(map);
|
||||
const arrowIcon = L.divIcon({
|
||||
className: "",
|
||||
html: "<div class=\"direction-marker\"><span style=\"transform:rotate(" + report.direction_degrees + "deg)\">↑</span></div>",
|
||||
iconSize: [56, 56], iconAnchor: [28, 28],
|
||||
});
|
||||
L.marker(arrowEnd, { icon: arrowIcon, interactive: false }).addTo(map);
|
||||
}
|
||||
});
|
||||
|
||||
if (bounds.isValid()) {
|
||||
map.fitBounds(bounds.pad(0.18));
|
||||
}
|
||||
|
||||
const range = document.getElementById("range");
|
||||
document.querySelectorAll("#from-date, #to-date").forEach((input) => {
|
||||
input.addEventListener("change", () => { range.value = "custom"; });
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
+265
-2
@@ -1,3 +1,266 @@
|
||||
from django.test import TestCase
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
# Create your tests here.
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from .h3_utils import cell_from_coordinates, h3_resolution
|
||||
from .models import ClassificationRule, Event, PendingEvent
|
||||
|
||||
|
||||
class ClassificationRuleApiTests(TestCase):
|
||||
def test_whitelist_returns_only_enabled_whitelist_entries_in_value_order(self):
|
||||
ClassificationRule.objects.create(value="Explosion", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
ClassificationRule.objects.create(value="Disabled firework", rule_type=ClassificationRule.RuleType.WHITELIST, enabled=False)
|
||||
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
|
||||
response = self.client.get(reverse("classification_rules:whitelist"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"classifications": ["Explosion", "Fireworks"]})
|
||||
|
||||
def test_blacklist_returns_only_enabled_blacklist_entries_in_value_order(self):
|
||||
ClassificationRule.objects.create(value="Speech", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
ClassificationRule.objects.create(value="Conversation", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
ClassificationRule.objects.create(value="Disabled music", rule_type=ClassificationRule.RuleType.BLACKLIST, enabled=False)
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
response = self.client.get(reverse("classification_rules:blacklist"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"classifications": ["Conversation", "Speech"]})
|
||||
|
||||
def test_classification_rule_is_unique_within_a_rule_type(self):
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
with transaction.atomic():
|
||||
with self.assertRaises(IntegrityError):
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.WHITELIST)
|
||||
|
||||
ClassificationRule.objects.create(value="Fireworks", rule_type=ClassificationRule.RuleType.BLACKLIST)
|
||||
|
||||
|
||||
class ManualPendingEventTests(TestCase):
|
||||
def test_manual_report_creates_a_timestamped_pending_event(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "4",
|
||||
"latitude": "52.1234567",
|
||||
"longitude": "5.9876543",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Report sent to Pending")
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.original_filename, "Manual fireworks report")
|
||||
self.assertEqual(pending.source_type, PendingEvent.SourceType.MANUAL)
|
||||
self.assertEqual(pending.occurrences, 4)
|
||||
self.assertEqual(pending.latitude, Decimal("52.123457"))
|
||||
self.assertEqual(pending.longitude, Decimal("5.987654"))
|
||||
self.assertEqual(pending.h3_cell, cell_from_coordinates(pending.latitude, pending.longitude))
|
||||
self.assertIsNone(pending.direction_degrees)
|
||||
self.assertIsNone(pending.direction_accuracy_degrees)
|
||||
self.assertEqual(pending.direction_source, "")
|
||||
self.assertFalse(pending.sensor)
|
||||
self.assertFalse(pending.audio_file)
|
||||
self.assertEqual(pending.classifier_response, {})
|
||||
self.assertIsNotNone(pending.created_at)
|
||||
|
||||
def test_manual_report_rejects_an_invalid_occurrence_count(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "0"})
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "Choose between 1 and 1,000 occurrences.", status_code=400)
|
||||
self.assertFalse(PendingEvent.objects.exists())
|
||||
|
||||
def test_event_details_and_source_type_are_kept_when_a_pending_event_is_approved(self):
|
||||
pending = PendingEvent.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=PendingEvent.SourceType.MANUAL,
|
||||
occurrences=3,
|
||||
location="Back garden",
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")),
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
direction_source="device_compass",
|
||||
visually_confirmed=True,
|
||||
)
|
||||
|
||||
event = pending.approve()
|
||||
|
||||
self.assertEqual(event.source_type, PendingEvent.SourceType.MANUAL)
|
||||
self.assertEqual(event.occurrences, 3)
|
||||
self.assertEqual(event.location, "Back garden")
|
||||
self.assertEqual(event.latitude, Decimal("52.123456"))
|
||||
self.assertEqual(event.longitude, Decimal("5.987654"))
|
||||
self.assertEqual(event.h3_cell, pending.h3_cell)
|
||||
self.assertEqual(event.direction_degrees, 237)
|
||||
self.assertEqual(event.direction_accuracy_degrees, 8)
|
||||
self.assertEqual(event.direction_source, "device_compass")
|
||||
self.assertTrue(event.visually_confirmed)
|
||||
|
||||
def test_existing_style_records_default_to_sensor_source_type(self):
|
||||
pending = PendingEvent.objects.create(original_filename="recording.wav", classifier_response={})
|
||||
|
||||
self.assertEqual(pending.source_type, PendingEvent.SourceType.SENSOR)
|
||||
|
||||
def test_home_page_includes_the_manual_report_form(self):
|
||||
response = self.client.get(reverse("hello"))
|
||||
|
||||
self.assertContains(response, "Report fireworks now")
|
||||
self.assertContains(response, "I heard fireworks — send to Pending")
|
||||
self.assertContains(response, "navigator.geolocation")
|
||||
self.assertContains(response, "Capture direction")
|
||||
self.assertContains(response, "DeviceOrientationEvent.requestPermission")
|
||||
self.assertContains(response, 'manual-direction-panel" hidden')
|
||||
self.assertContains(response, "DeviceOrientationEvent.requestPermission(true)")
|
||||
self.assertContains(response, 'webkitCompassHeading" in event')
|
||||
self.assertContains(response, "direction will update live")
|
||||
self.assertContains(response, "Stop direction capture")
|
||||
|
||||
self.assertContains(response, "htmx.ajax")
|
||||
def test_manual_event_appears_in_the_normal_event_list_with_its_details(self):
|
||||
event = Event.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL,
|
||||
occurrences=5,
|
||||
location="Back garden",
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
visually_confirmed=True,
|
||||
)
|
||||
|
||||
list_response = self.client.get(reverse("fireworks_detect:events_list"))
|
||||
self.assertContains(list_response, "Manual fireworks report")
|
||||
self.assertContains(list_response, "5 occurrences")
|
||||
self.assertContains(list_response, "Back garden")
|
||||
|
||||
detail_response = self.client.get(reverse("fireworks_detect:event_detail", args=[event.pk]))
|
||||
self.assertContains(detail_response, "Report details")
|
||||
self.assertContains(detail_response, "Visually confirmed")
|
||||
self.assertContains(detail_response, "Captured location")
|
||||
self.assertContains(detail_response, cell_from_coordinates(event.latitude, event.longitude))
|
||||
self.assertNotContains(detail_response, "52.123456, 5.987654")
|
||||
self.assertContains(detail_response, "237° (SW)")
|
||||
self.assertContains(detail_response, "Compass accuracy")
|
||||
|
||||
@override_settings(FIREWORKS_H3_RESOLUTION=8)
|
||||
def test_h3_resolution_is_configurable(self):
|
||||
self.assertEqual(h3_resolution(), 8)
|
||||
self.assertTrue(cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654")))
|
||||
|
||||
def test_map_uses_manual_h3_data_and_excludes_sensor_events(self):
|
||||
manual_cell = cell_from_coordinates(Decimal("52.123456"), Decimal("5.987654"))
|
||||
sensor_cell = cell_from_coordinates(Decimal("53.123456"), Decimal("5.987654"))
|
||||
Event.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL,
|
||||
occurrences=4,
|
||||
latitude=Decimal("52.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=manual_cell,
|
||||
visually_confirmed=True,
|
||||
direction_degrees=237,
|
||||
direction_accuracy_degrees=8,
|
||||
)
|
||||
Event.objects.create(
|
||||
original_filename="Sensor recording.wav",
|
||||
classifier_response={},
|
||||
source_type=Event.SourceType.SENSOR,
|
||||
occurrences=9,
|
||||
latitude=Decimal("53.123456"),
|
||||
longitude=Decimal("5.987654"),
|
||||
h3_cell=sensor_cell,
|
||||
)
|
||||
|
||||
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all"})
|
||||
|
||||
self.assertContains(response, "H3 resolution 9")
|
||||
self.assertContains(response, "map-events-data")
|
||||
self.assertContains(response, manual_cell)
|
||||
self.assertContains(response, '"direction_degrees": 237.0')
|
||||
self.assertContains(response, "cardinalDirection(report.direction_degrees)")
|
||||
self.assertContains(response, "sensor layer disabled")
|
||||
self.assertContains(response, "Map compass: north is up")
|
||||
self.assertContains(response, "Sensor events — coming soon")
|
||||
self.assertNotContains(response, sensor_cell)
|
||||
self.assertNotContains(response, "52.123456")
|
||||
self.assertNotContains(response, "H3 demo cell")
|
||||
|
||||
def test_map_date_range_filters_manual_reports(self):
|
||||
recent_cell = cell_from_coordinates(Decimal("52.400000"), Decimal("5.700000"))
|
||||
older_cell = cell_from_coordinates(Decimal("53.400000"), Decimal("5.700000"))
|
||||
Event.objects.create(
|
||||
original_filename="Recent manual report", classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL, latitude=Decimal("52.400000"),
|
||||
longitude=Decimal("5.700000"), h3_cell=recent_cell,
|
||||
)
|
||||
older = Event.objects.create(
|
||||
original_filename="Older manual report", classifier_response={},
|
||||
source_type=Event.SourceType.MANUAL, latitude=Decimal("53.400000"),
|
||||
longitude=Decimal("5.700000"), h3_cell=older_cell,
|
||||
)
|
||||
Event.objects.filter(pk=older.pk).update(created_at=timezone.now() - timedelta(days=8))
|
||||
|
||||
response = self.client.get(reverse("fireworks_detect:map"), {"range": "7"})
|
||||
|
||||
self.assertContains(response, recent_cell)
|
||||
self.assertNotContains(response, older_cell)
|
||||
self.assertContains(response, "Last 7 days")
|
||||
|
||||
|
||||
def test_manual_report_saves_a_valid_compass_direction_and_accuracy(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "2",
|
||||
"direction_degrees": "237",
|
||||
"direction_accuracy_degrees": "8",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.direction_degrees, 237)
|
||||
self.assertEqual(pending.direction_accuracy_degrees, 8)
|
||||
self.assertEqual(pending.direction_source, "device_compass")
|
||||
self.assertEqual(pending.direction_cardinal, "SW")
|
||||
|
||||
def test_zero_degree_direction_is_valid_and_accuracy_may_be_absent(self):
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "1",
|
||||
"direction_degrees": "0",
|
||||
})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
pending = PendingEvent.objects.get()
|
||||
self.assertEqual(pending.direction_degrees, 0)
|
||||
self.assertIsNone(pending.direction_accuracy_degrees)
|
||||
self.assertEqual(pending.direction_cardinal, "N")
|
||||
|
||||
def test_invalid_directions_are_rejected_by_model_validation_and_not_saved_by_manual_submission(self):
|
||||
for invalid_direction in (-1, 360):
|
||||
pending = PendingEvent(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
direction_degrees=invalid_direction,
|
||||
)
|
||||
with self.assertRaises(ValidationError):
|
||||
pending.full_clean()
|
||||
|
||||
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
|
||||
"occurrences": "1",
|
||||
"direction_degrees": str(invalid_direction),
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
saved = PendingEvent.objects.latest("created_at")
|
||||
self.assertIsNone(saved.direction_degrees)
|
||||
self.assertIsNone(saved.direction_accuracy_degrees)
|
||||
self.assertEqual(saved.direction_source, "")
|
||||
|
||||
@@ -10,6 +10,7 @@ from .views import (
|
||||
fireworks_map_view,
|
||||
fireworks_view,
|
||||
pending_audio,
|
||||
submit_manual_pending_event,
|
||||
submit_pending_event,
|
||||
sensor_heartbeat,
|
||||
)
|
||||
@@ -23,6 +24,7 @@ urlpatterns = [
|
||||
path("classify/upload/", classify_upload, name="classify_upload"),
|
||||
path("heartbeat/", sensor_heartbeat, name="sensor_heartbeat"),
|
||||
path("submit-pending/", submit_pending_event, name="submit_pending"),
|
||||
path("submit-manual-pending/", submit_manual_pending_event, name="submit_manual_pending"),
|
||||
path("events/", events_view, name="events"),
|
||||
path("events/list/", events_list, name="events_list"),
|
||||
path("admin-audio/pending/<int:event_id>/", pending_audio, name="pending_audio"),
|
||||
|
||||
+187
-2
@@ -1,3 +1,6 @@
|
||||
import math
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import mimetypes
|
||||
import uuid
|
||||
@@ -9,11 +12,14 @@ from django.contrib.admin.views.decorators import staff_member_required
|
||||
from django.http import FileResponse, Http404, JsonResponse
|
||||
from django.core import signing
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import Event, PendingEvent, Sensor
|
||||
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
|
||||
from .models import ClassificationRule, Event, PendingEvent, Sensor
|
||||
|
||||
|
||||
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
|
||||
@@ -35,9 +41,107 @@ def fireworks_view(request):
|
||||
return render(request, "fireworks_detect/home.html")
|
||||
|
||||
|
||||
MAP_DATE_RANGES = {
|
||||
"7": 7,
|
||||
"14": 14,
|
||||
"30": 30,
|
||||
"all": None,
|
||||
"custom": None,
|
||||
}
|
||||
|
||||
|
||||
def _map_filters(request):
|
||||
"""Return the selected map filters, using an inclusive date range."""
|
||||
selected_range = request.GET.get("range", "14")
|
||||
if selected_range not in MAP_DATE_RANGES:
|
||||
selected_range = "14"
|
||||
|
||||
if selected_range == "custom":
|
||||
date_from = parse_date(request.GET.get("from", ""))
|
||||
date_to = parse_date(request.GET.get("to", ""))
|
||||
elif MAP_DATE_RANGES[selected_range]:
|
||||
date_to = timezone.localdate()
|
||||
date_from = date_to - timedelta(days=MAP_DATE_RANGES[selected_range] - 1)
|
||||
else:
|
||||
date_from = date_to = None
|
||||
|
||||
visual = request.GET.get("visual", "all")
|
||||
if visual not in {"all", "yes", "no"}:
|
||||
visual = "all"
|
||||
return {
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"range": selected_range,
|
||||
"visual": visual,
|
||||
}
|
||||
|
||||
|
||||
def _events_for_map(filters):
|
||||
"""Create privacy-preserving map data for reviewed manual reports only."""
|
||||
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
|
||||
if filters["date_from"]:
|
||||
events = events.filter(created_at__date__gte=filters["date_from"])
|
||||
if filters["date_to"]:
|
||||
events = events.filter(created_at__date__lte=filters["date_to"])
|
||||
if filters["visual"] == "yes":
|
||||
events = events.filter(visually_confirmed=True)
|
||||
elif filters["visual"] == "no":
|
||||
events = events.filter(visually_confirmed=False)
|
||||
|
||||
cells = {}
|
||||
mapped_events = []
|
||||
for event in events.values(
|
||||
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
|
||||
"direction_degrees", "direction_accuracy_degrees", "created_at",
|
||||
):
|
||||
# Coordinates are used only here to derive an H3 cell; they never leave the server.
|
||||
h3_cell = event["h3_cell"] or cell_from_coordinates(event["latitude"], event["longitude"])
|
||||
center = cell_center(h3_cell) if h3_cell else None
|
||||
boundary = cell_boundary(h3_cell) if h3_cell else None
|
||||
if not center or not boundary:
|
||||
continue
|
||||
|
||||
aggregate = cells.setdefault(h3_cell, {
|
||||
"cell": h3_cell,
|
||||
"boundary": boundary,
|
||||
"center": center,
|
||||
"reports": 0,
|
||||
"occurrences": 0,
|
||||
})
|
||||
aggregate["reports"] += 1
|
||||
aggregate["occurrences"] += event["occurrences"]
|
||||
mapped_events.append({
|
||||
"cell": h3_cell,
|
||||
"center": center,
|
||||
"occurrences": event["occurrences"],
|
||||
"visually_confirmed": event["visually_confirmed"],
|
||||
# A day is sufficient for this map and avoids sharing a precise report time.
|
||||
"reported_on": event["created_at"].date().isoformat(),
|
||||
"direction_degrees": float(event["direction_degrees"]) if event["direction_degrees"] is not None else None,
|
||||
"direction_accuracy_degrees": (
|
||||
float(event["direction_accuracy_degrees"])
|
||||
if event["direction_accuracy_degrees"] is not None else None
|
||||
),
|
||||
})
|
||||
|
||||
return mapped_events, list(cells.values())
|
||||
|
||||
@never_cache
|
||||
def fireworks_map_view(request):
|
||||
return render(request, "fireworks_detect/map.html")
|
||||
filters = _map_filters(request)
|
||||
map_events, h3_cells = _events_for_map(filters)
|
||||
return render(request, "fireworks_detect/map.html", {
|
||||
"h3_resolution": h3_resolution(),
|
||||
"h3_cells": h3_cells,
|
||||
"map_events": map_events,
|
||||
"mapped_event_count": len(map_events),
|
||||
"map_filters": {
|
||||
"date_from": filters["date_from"].isoformat() if filters["date_from"] else "",
|
||||
"date_to": filters["date_to"].isoformat() if filters["date_to"] else "",
|
||||
"range": filters["range"],
|
||||
"visual": filters["visual"],
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@never_cache
|
||||
@@ -181,6 +285,68 @@ def submit_pending_event(request):
|
||||
return render(request, "fireworks_detect/pending_submission.html", {"pending": pending})
|
||||
|
||||
|
||||
def _manual_coordinates(request):
|
||||
try:
|
||||
latitude = Decimal(request.POST.get("latitude", ""))
|
||||
longitude = Decimal(request.POST.get("longitude", ""))
|
||||
if not -90 <= latitude <= 90 or not -180 <= longitude <= 180:
|
||||
return None, None
|
||||
return latitude.quantize(Decimal("0.000001")), longitude.quantize(Decimal("0.000001"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
return None, None
|
||||
|
||||
|
||||
def _manual_direction(request):
|
||||
try:
|
||||
heading = float(request.POST.get("direction_degrees", ""))
|
||||
except (TypeError, ValueError):
|
||||
return None, None
|
||||
|
||||
if not math.isfinite(heading) or not 0 <= heading < 360:
|
||||
return None, None
|
||||
|
||||
try:
|
||||
accuracy = float(request.POST.get("direction_accuracy_degrees", ""))
|
||||
except (TypeError, ValueError):
|
||||
accuracy = None
|
||||
if accuracy is not None and (not math.isfinite(accuracy) or accuracy < 0):
|
||||
accuracy = None
|
||||
return heading, accuracy
|
||||
|
||||
@require_http_methods(["POST"])
|
||||
@never_cache
|
||||
def submit_manual_pending_event(request):
|
||||
try:
|
||||
occurrences = int(request.POST.get("occurrences", ""))
|
||||
except (TypeError, ValueError):
|
||||
occurrences = 0
|
||||
|
||||
if not 1 <= occurrences <= 1000:
|
||||
return render(
|
||||
request,
|
||||
"fireworks_detect/manual_pending_submission.html",
|
||||
{"error": "Choose between 1 and 1,000 occurrences."},
|
||||
status=400,
|
||||
)
|
||||
|
||||
latitude, longitude = _manual_coordinates(request)
|
||||
h3_cell = cell_from_coordinates(latitude, longitude)
|
||||
direction_degrees, direction_accuracy_degrees = _manual_direction(request)
|
||||
|
||||
pending = PendingEvent.objects.create(
|
||||
original_filename="Manual fireworks report",
|
||||
classifier_response={},
|
||||
source_type=PendingEvent.SourceType.MANUAL,
|
||||
occurrences=occurrences,
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
h3_cell=h3_cell or "",
|
||||
direction_degrees=direction_degrees,
|
||||
direction_accuracy_degrees=direction_accuracy_degrees,
|
||||
direction_source="device_compass" if direction_degrees is not None else "",
|
||||
)
|
||||
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending})
|
||||
|
||||
@never_cache
|
||||
def events_list(request):
|
||||
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
|
||||
@@ -191,6 +357,7 @@ def event_detail(request, event_id):
|
||||
event = get_object_or_404(Event, pk=event_id)
|
||||
context = _classification_context(event.classifier_response)
|
||||
context["event"] = event
|
||||
context["event_h3_cell"] = event.h3_cell or cell_from_coordinates(event.latitude, event.longitude)
|
||||
return render(request, "fireworks_detect/event_detail.html", context)
|
||||
|
||||
|
||||
@@ -264,3 +431,21 @@ def sensor_heartbeat(request):
|
||||
return _sensor_error("A valid sensor API token is required.", 401)
|
||||
sensor.record_heartbeat()
|
||||
return JsonResponse({"ok": True, "sensor": sensor.name, "heartbeat_at": sensor.last_heartbeat.isoformat()})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def classification_whitelist(request):
|
||||
classifications = ClassificationRule.objects.filter(
|
||||
rule_type=ClassificationRule.RuleType.WHITELIST,
|
||||
enabled=True,
|
||||
).order_by("value").values_list("value", flat=True)
|
||||
return JsonResponse({"classifications": list(classifications)})
|
||||
|
||||
|
||||
@require_http_methods(["GET"])
|
||||
def classification_blacklist(request):
|
||||
classifications = ClassificationRule.objects.filter(
|
||||
rule_type=ClassificationRule.RuleType.BLACKLIST,
|
||||
enabled=True,
|
||||
).order_by("value").values_list("value", flat=True)
|
||||
return JsonResponse({"classifications": list(classifications)})
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
// Replace this optional entry point with your project's client-side code.
|
||||
Binary file not shown.
+156
-1
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Welkom · Sound Signal</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
<style>
|
||||
:root { --ink:#eef3ff; --muted:#aab9d8; --line:#2b3d68; --blue:#8abaff; --violet:#b69cff; --amber:#ffbd62; }
|
||||
* { box-sizing:border-box; }
|
||||
@@ -14,6 +15,8 @@
|
||||
.eyebrow { margin:0 0 .8rem; color:#bad3ff; font-size:.76rem; font-weight:800; letter-spacing:.14em; text-transform:uppercase; }.eyebrow::before { content:""; display:inline-block; width:.55rem; height:.55rem; margin-right:.45rem; border-radius:50%; background:var(--amber); box-shadow:0 0 0 .25rem #fbbf2430; }
|
||||
h1 { max-width:10ch; margin:0; font-size:clamp(2.8rem,8vw,5.75rem); line-height:.96; letter-spacing:-.065em; }.subject { max-width:33rem; margin:1.35rem 0 0; color:var(--muted); font-size:clamp(1rem,2vw,1.15rem); line-height:1.65; }.subject strong { color:#e8efff; }.sparkle { color:var(--violet); font-size:1.2em; }
|
||||
.actions { display:flex; align-items:center; gap:1rem; flex-wrap:wrap; margin-top:2.25rem; }
|
||||
.profile-circle { display:grid; width:3rem; height:3rem; position:fixed; top:1.25rem; right:1.25rem; place-items:center; border:1px solid #d0c0ff; border-radius:50%; z-index:2; color:#17132b; font-weight:900; text-decoration:none; background:linear-gradient(135deg,#fcd34d,#c4a5fd); box-shadow:0 .5rem 1.5rem #01030c66; }
|
||||
.profile-circle:focus-visible { outline:3px solid #a5c9ff80; outline-offset:3px; }
|
||||
.button { display:inline-flex; align-items:center; justify-content:center; gap:.6rem; min-height:2.9rem; padding:.75rem 1.05rem; border:1px solid #b3c9ff; border-radius:.8rem; color:#121a34; font:inherit; font-size:.93rem; font-weight:850; text-decoration:none; background:linear-gradient(135deg,#99c8ff,#c6adff); box-shadow:0 .65rem 1.75rem #7058dd50; transition:transform .2s ease,filter .2s ease; }
|
||||
.button:hover { transform:translateY(-2px); filter:brightness(1.08); }
|
||||
.button:focus-visible { outline:3px solid #a5c9ff80; outline-offset:3px; }.hint { color:#99add2; font-size:.82rem; }
|
||||
@@ -22,7 +25,9 @@
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="welcome-card">
|
||||
{% if user.is_authenticated %}<a class="profile-circle" href="{% url 'user_settings' %}" aria-label="Open settings for {{ user.get_username }}" title="Settings">{{ user.get_username|first|upper }}</a>{% endif %}
|
||||
<div style="width:min(100%,80rem);display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,20rem),1fr));gap:1.25rem;align-items:stretch;">
|
||||
<main class="welcome-card" style="width:100%;">
|
||||
<div class="brand"><span class="brand-mark">✦</span> Sound Signal</div>
|
||||
<p class="eyebrow">Control room</p>
|
||||
<h1>Welkom {{ naam }}</h1>
|
||||
@@ -31,8 +36,158 @@
|
||||
<a href="{% url 'fireworks_detect:fireworks' %}" class="button">Open vuurwerk detector <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:map' %}" class="button">Open kaart concept <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'member_create' %}" class="button">Open formulier <span aria-hidden="true">→</span></a>
|
||||
<a href="{% url 'fireworks_detect:events' %}" class="button">Open gebeurtenissen <span aria-hidden="true">→</span></a>
|
||||
<span class="hint">Audio analysis · Sensor map</span>
|
||||
</div>
|
||||
</main>
|
||||
<section aria-labelledby="manual-report-title" style="position:relative;overflow:hidden;padding:clamp(2rem,6vw,4.75rem);border:2px solid #a85a1e;border-radius:1.5rem;background:linear-gradient(145deg,#4a2b16e8,#171225dd);box-shadow:0 1.75rem 5rem #01030c99;">
|
||||
<p class="eyebrow">No recording needed</p>
|
||||
<h2 id="manual-report-title" style="margin:.2rem 0 .75rem;font-size:clamp(2rem,4vw,3.1rem);line-height:1;letter-spacing:-.06em;">Report fireworks now</h2>
|
||||
<p style="margin:0 0 1.5rem;color:#f3c8a3;line-height:1.55;">Choose how many times you heard fireworks, then send it straight to Pending. The report is timestamped now.</p>
|
||||
<form id="manual-report-form" action="{% url 'fireworks_detect:submit_manual_pending' %}" method="post" hx-post="{% url 'fireworks_detect:submit_manual_pending' %}" hx-target="#manual-submission" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<label for="manual-occurrences" style="display:block;margin-bottom:.5rem;font-weight:800;">Number of occurrences</label>
|
||||
<input id="manual-latitude" name="latitude" type="hidden">
|
||||
<input id="manual-longitude" name="longitude" type="hidden">
|
||||
<input id="manual-direction-degrees" name="direction_degrees" type="hidden">
|
||||
<input id="manual-direction-accuracy" name="direction_accuracy_degrees" type="hidden">
|
||||
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric" style="width:100%;min-height:3.3rem;margin-bottom:1rem;padding:.75rem .9rem;border:1px solid #e2934a;border-radius:.75rem;color:#eef3ff;font:inherit;font-weight:800;background:#151b31;">
|
||||
<div id="manual-direction-panel" hidden style="margin:0 0 1rem;padding:1rem;border:1px solid #8d5bb5;border-radius:.75rem;background:#241b38;">
|
||||
<strong style="display:block;margin-bottom:.35rem;">Direction <span style="color:#c7b5eb;font-weight:600;">(optional)</span></strong>
|
||||
<p style="margin:0 0 .75rem;color:#d4c6ef;font-size:.88rem;line-height:1.45;">Point the top of your phone toward the fireworks, then capture a single compass reading.</p>
|
||||
<button id="manual-capture-direction" type="button" style="min-height:2.75rem;padding:.65rem .9rem;border:1px solid #c3a5eb;border-radius:.65rem;color:#211234;font:inherit;font-weight:850;background:#d8c1fb;cursor:pointer;">Capture direction</button>
|
||||
<div id="manual-direction-status" style="min-height:1.4rem;margin-top:.7rem;color:#e5dcf7;font-size:.9rem;" aria-live="polite"></div>
|
||||
</div>
|
||||
<button id="manual-submit" type="button" style="width:100%;min-height:6rem;border:0;border-radius:1rem;color:#281306;font:inherit;font-size:clamp(1.1rem,2vw,1.45rem);font-weight:900;background:linear-gradient(135deg,#ffd18c,#ff8f5b);box-shadow:0 .75rem 1.8rem #d664344d;cursor:pointer;">I heard fireworks — send to Pending</button>
|
||||
</form>
|
||||
<div id="manual-submission" style="min-height:1.5rem;margin-top:1rem;color:#ffd18c;" aria-live="polite"></div>
|
||||
</section>
|
||||
</div>
|
||||
<script>
|
||||
const manualForm = document.querySelector("#manual-report-form");
|
||||
const manualSubmit = document.querySelector("#manual-submit");
|
||||
const manualStatus = document.querySelector("#manual-submission");
|
||||
const latitude = document.querySelector("#manual-latitude");
|
||||
const longitude = document.querySelector("#manual-longitude");
|
||||
const directionDegrees = document.querySelector("#manual-direction-degrees");
|
||||
const directionAccuracy = document.querySelector("#manual-direction-accuracy");
|
||||
const captureDirectionButton = document.querySelector("#manual-capture-direction");
|
||||
const directionStatus = document.querySelector("#manual-direction-status");
|
||||
const directionPanel = document.querySelector("#manual-direction-panel");
|
||||
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;
|
||||
|
||||
const isUsableNumber = (value) => Number.isFinite(value);
|
||||
const cardinalDirection = (heading) => ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][Math.floor(((heading + 22.5) % 360) / 45)];
|
||||
const displayDegrees = (value) => Number(value.toFixed(1)).toString();
|
||||
|
||||
const stopCompassReading = () => {
|
||||
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
orientationListener = null;
|
||||
compassUnavailableTimeout = null;
|
||||
};
|
||||
|
||||
const showCapturedDirection = (heading, accuracy) => {
|
||||
const accuracyText = accuracy === null ? "Accuracy unavailable" : "Accuracy: ±" + displayDegrees(accuracy) + "°";
|
||||
directionStatus.innerHTML = "<strong>" + displayDegrees(heading) + "° · " + cardinalDirection(heading) + "</strong><br>" + accuracyText;
|
||||
captureDirectionButton.textContent = "Stop direction capture";
|
||||
};
|
||||
|
||||
const listenForCompassReading = () => {
|
||||
stopCompassReading();
|
||||
directionStatus.textContent = "Point the top of your phone toward the sound — direction will update live.";
|
||||
orientationListener = (event) => {
|
||||
const isWebKitCompass = "webkitCompassHeading" in event;
|
||||
const heading = isUsableNumber(event.webkitCompassHeading)
|
||||
? event.webkitCompassHeading
|
||||
: !isWebKitCompass && event.absolute && isUsableNumber(event.alpha)
|
||||
? (360 - event.alpha) % 360
|
||||
: null;
|
||||
if (heading === null || heading < 0 || heading >= 360) return;
|
||||
|
||||
const accuracy = isUsableNumber(event.webkitCompassAccuracy) && event.webkitCompassAccuracy >= 0
|
||||
? event.webkitCompassAccuracy
|
||||
: null;
|
||||
directionDegrees.value = heading;
|
||||
directionAccuracy.value = accuracy === null ? "" : accuracy;
|
||||
showCapturedDirection(heading, accuracy);
|
||||
window.clearTimeout(compassUnavailableTimeout);
|
||||
};
|
||||
window.addEventListener("deviceorientation", orientationListener);
|
||||
compassUnavailableTimeout = window.setTimeout(() => {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = "Capture direction";
|
||||
directionStatus.textContent = "Compass unavailable on this device.";
|
||||
}, 15000);
|
||||
};
|
||||
|
||||
const captureDirection = async () => {
|
||||
if (orientationListener) {
|
||||
stopCompassReading();
|
||||
captureDirectionButton.textContent = "Capture again";
|
||||
return;
|
||||
}
|
||||
if (!window.isSecureContext) {
|
||||
directionStatus.textContent = "Compass capture requires a secure HTTPS connection.";
|
||||
return;
|
||||
}
|
||||
if (typeof window.DeviceOrientationEvent === "undefined") {
|
||||
directionStatus.textContent = "Compass unavailable on this device.";
|
||||
return;
|
||||
}
|
||||
if (typeof DeviceOrientationEvent.requestPermission === "function") {
|
||||
directionStatus.textContent = "Requesting compass permission…";
|
||||
try {
|
||||
if (await DeviceOrientationEvent.requestPermission(true) !== "granted") {
|
||||
directionStatus.textContent = "Compass permission denied.";
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
directionStatus.textContent = "Compass permission denied.";
|
||||
return;
|
||||
}
|
||||
}
|
||||
listenForCompassReading();
|
||||
};
|
||||
|
||||
const submitManualReport = () => {
|
||||
stopCompassReading();
|
||||
manualSubmit.disabled = true;
|
||||
if (window.htmx) {
|
||||
htmx.ajax("POST", manualForm.action, {
|
||||
source: manualForm,
|
||||
target: "#manual-submission",
|
||||
swap: "outerHTML",
|
||||
});
|
||||
} else {
|
||||
manualForm.submit();
|
||||
}
|
||||
};
|
||||
|
||||
captureDirectionButton.addEventListener("click", captureDirection);
|
||||
manualSubmit.addEventListener("click", () => {
|
||||
if (!navigator.geolocation) {
|
||||
submitManualReport();
|
||||
return;
|
||||
}
|
||||
manualStatus.textContent = "Requesting your optional location…";
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
latitude.value = position.coords.latitude;
|
||||
longitude.value = position.coords.longitude;
|
||||
submitManualReport();
|
||||
},
|
||||
() => submitManualReport(),
|
||||
{ enableHighAccuracy: false, maximumAge: 300000, timeout: 10000 },
|
||||
);
|
||||
});
|
||||
document.body.addEventListener("htmx:afterRequest", (event) => {
|
||||
if (event.detail.elt === manualForm) manualSubmit.disabled = false;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+13
-1
@@ -1,8 +1,20 @@
|
||||
from django import forms
|
||||
from .models import Member
|
||||
from .models import Member, UserSettings
|
||||
|
||||
class MemberForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Member
|
||||
fields = ["first_name", "last_name", "phone"]
|
||||
|
||||
|
||||
|
||||
class UserSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ["ntfy_url", "ntfy_enabled"]
|
||||
widgets = {
|
||||
"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"}),
|
||||
}
|
||||
|
||||
def clean_ntfy_url(self):
|
||||
return self.cleaned_data["ntfy_url"].strip()
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 07:38
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('members', '0001_initial'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('ntfy_url', models.URLField(blank=True)),
|
||||
('ntfy_enabled', models.BooleanField(default=False)),
|
||||
('ntfy_last_tested_at', models.DateTimeField(blank=True, null=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='notification_settings', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'User settings',
|
||||
'verbose_name_plural': 'User settings',
|
||||
},
|
||||
),
|
||||
]
|
||||
Binary file not shown.
@@ -1,3 +1,4 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
# Create your models here.
|
||||
@@ -9,3 +10,18 @@ class Member(models.Model):
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.first_name} {self.last_name}"
|
||||
|
||||
class UserSettings(models.Model):
|
||||
"""Per-user configuration for optional notification providers."""
|
||||
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_settings")
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = "User settings"
|
||||
verbose_name_plural = "User settings"
|
||||
|
||||
def __str__(self):
|
||||
return f"Notification settings for {self.user}"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("", views.user_settings, name="user_settings"),
|
||||
path("notifications/ntfy/test/", views.test_ntfy_notification, name="ntfy_test_notification"),
|
||||
]
|
||||
@@ -0,0 +1,29 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Sign in · Sound Signal</title>
|
||||
<style>body{min-width:320px;min-height:100vh;display:grid;place-items:center;margin:0;padding:1.5rem;color:#eef3ff;font-family:Inter,system-ui,sans-serif;background:radial-gradient(circle at 8% 0,#263a76,transparent 31rem),#090e1d}.card{width:min(100%,27rem);padding:2rem;border:1px solid #2b3d68;border-radius:1.25rem;background:#172443;box-shadow:0 1.75rem 5rem #01030c99}h1{margin:.5rem 0}.intro{color:#aab9d8;line-height:1.5}.error{margin:1rem 0;padding:.75rem;border-radius:.6rem;color:#fee2e2;background:#7f1d1d}label{display:block;margin:1rem 0 .35rem;font-weight:700}input{width:100%;min-height:2.8rem;padding:.65rem;border:1px solid #526b9f;border-radius:.55rem;color:#eef3ff;font:inherit;background:#0a1123}button{width:100%;min-height:2.9rem;margin-top:1.5rem;border:0;border-radius:.65rem;color:#17132b;font:inherit;font-weight:850;background:linear-gradient(135deg,#99c8ff,#c6adff);cursor:pointer}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<p>✦ Sound Signal</p>
|
||||
<h1>Sign in</h1>
|
||||
<p class="intro">Sign in to manage your notification settings.</p>
|
||||
{% if form.errors %}
|
||||
<div class="error">Your username and password did not match. Please try again.</div>
|
||||
{% endif %}
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<label for="{{ form.username.id_for_label }}">Username</label>
|
||||
{{ form.username }}
|
||||
<label for="{{ form.password.id_for_label }}">Password</label>
|
||||
{{ form.password }}
|
||||
{% if next %}<input type="hidden" name="next" value="{{ next }}">{% endif %}
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
<p class="intro">You will return to the page you requested.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
|
||||
@@ -0,0 +1,32 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Settings · Sound Signal</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>
|
||||
<style>body{min-width:320px;margin:0;padding:2rem;color:#eef3ff;font-family:Inter,system-ui,sans-serif;background:#090e1d}.card{width:min(100%,42rem);margin:auto;padding:2rem;border:1px solid #2b3d68;border-radius:1rem;background:#172443}h1{margin-top:0}h2{margin:0}.intro,.help{color:#aab9d8;line-height:1.5}.section{margin-top:2rem;padding-top:1.5rem;border-top:1px solid #2b3d68}label{display:block;margin:.9rem 0 .35rem;font-weight:700}input[type=url]{width:100%;min-height:2.8rem;padding:.65rem;border:1px solid #526b9f;border-radius:.55rem;color:#eef3ff;font:inherit;background:#0a1123}.check{display:flex;gap:.6rem;align-items:center}.check label{margin:0}.button{min-height:2.8rem;margin-top:1rem;padding:.6rem 1rem;border:0;border-radius:.55rem;color:#17132b;font:inherit;font-weight:800;background:#a6ccff;cursor:pointer}.button--secondary{margin-right:.7rem;background:#d8c1fb}.alert,.errorlist{margin-top:1rem;padding:.75rem;border-radius:.55rem}.alert--success{color:#d1fae5;background:#14532d}.alert--error,.errorlist{color:#fee2e2;background:#7f1d1d}.messages{padding:0;list-style:none}@media(max-width:32rem){body{padding:1rem}.card{padding:1.4rem}}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="card">
|
||||
<h1>Settings</h1>
|
||||
<p class="intro">Manage personal notification preferences.</p>
|
||||
{% if messages %}<ul class="messages">{% for message in messages %}<li class="alert alert--success">{{ message }}</li>{% endfor %}</ul>{% endif %}
|
||||
<form method="post" action="{% url 'user_settings' %}">
|
||||
{% csrf_token %}
|
||||
<section class="section" aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p class="help">Use a topic URL from your ntfy server. Test the current URL before saving it.</p>
|
||||
<label for="ntfy-url">Topic URL</label>
|
||||
{{ form.ntfy_url }}
|
||||
{{ form.ntfy_url.errors }}
|
||||
<div class="check">{{ form.ntfy_enabled }}<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label></div>
|
||||
<button class="button button--secondary" type="button" hx-post="{% url 'ntfy_test_notification' %}" hx-include="#ntfy-url, [name='csrfmiddlewaretoken']" hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
|
||||
<div id="ntfy-test-result" aria-live="polite"></div>
|
||||
</section>
|
||||
<button class="button" type="submit">Save settings</button>
|
||||
</form>
|
||||
</main>
|
||||
<script>document.querySelector("#ntfy-url").addEventListener("input", () => { document.querySelector("#ntfy-test-result").replaceChildren(); });</script>
|
||||
</body>
|
||||
</html>
|
||||
+163
-2
@@ -1,3 +1,164 @@
|
||||
from django.test import TestCase
|
||||
from socket import timeout as SocketTimeout
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
# Create your tests here.
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from notifications.services import NotificationError, send_notification, send_ntfy_notification
|
||||
|
||||
from .models import UserSettings
|
||||
|
||||
|
||||
|
||||
class NtfyNotificationServiceTests(SimpleTestCase):
|
||||
@patch("notifications.services.urlopen")
|
||||
def test_posts_a_title_and_message_to_the_topic_url(self, mock_urlopen):
|
||||
response = MagicMock()
|
||||
response.getcode.return_value = 200
|
||||
mock_urlopen.return_value = response
|
||||
|
||||
self.assertTrue(send_ntfy_notification("https://ntfy.example.com/private-topic", "Fireworks Detector", "Test message"))
|
||||
|
||||
request = mock_urlopen.call_args.args[0]
|
||||
self.assertEqual(request.get_method(), "POST")
|
||||
self.assertEqual(request.data, b"Test message")
|
||||
self.assertEqual(request.get_header("Title"), "Fireworks Detector")
|
||||
|
||||
@patch("notifications.services.urlopen", side_effect=HTTPError("https://ntfy.example.com/topic", 503, "Unavailable", None, None))
|
||||
def test_non_success_http_response_is_a_safe_failure(self, mock_urlopen):
|
||||
with self.assertRaisesMessage(NotificationError, "HTTP 503"):
|
||||
send_ntfy_notification("https://ntfy.example.com/topic", "Title", "Message")
|
||||
|
||||
@patch("notifications.services.urlopen", side_effect=URLError(SocketTimeout()))
|
||||
def test_timeout_is_a_safe_failure(self, mock_urlopen):
|
||||
with self.assertRaisesMessage(NotificationError, "timed out"):
|
||||
send_ntfy_notification("https://ntfy.example.com/topic", "Title", "Message")
|
||||
|
||||
|
||||
class UserSettingsNtfyTests(TestCase):
|
||||
url = "https://ntfy.example.com/private-topic"
|
||||
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="first-user", password="secret")
|
||||
self.other_user = get_user_model().objects.create_user(username="other-user", password="secret")
|
||||
self.client.force_login(self.user)
|
||||
|
||||
def test_test_endpoint_requires_login(self):
|
||||
self.client.logout()
|
||||
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 302)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_invalid_url_is_rejected_without_sending(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": "not a URL"})
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertContains(response, "valid HTTP or HTTPS", status_code=400)
|
||||
mock_send.assert_not_called()
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_successful_test_returns_inline_success_and_marks_current_url_in_session(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test notification sent successfully")
|
||||
mock_send.assert_called_once_with(
|
||||
self.url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
)
|
||||
|
||||
@patch("members.views.send_ntfy_notification", side_effect=NotificationError("Connection to the ntfy server timed out."))
|
||||
def test_delivery_failure_returns_an_inline_safe_error(self, mock_send):
|
||||
response = self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
self.assertEqual(response.status_code, 502)
|
||||
self.assertContains(response, "timed out", status_code=502)
|
||||
|
||||
def test_user_cannot_save_an_untested_url(self):
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
settings = UserSettings.objects.get(user=self.user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
self.assertEqual(settings.ntfy_url, "")
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_successfully_tested_url_can_be_saved(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertRedirects(response, reverse("user_settings"))
|
||||
settings = UserSettings.objects.get(user=self.user)
|
||||
self.assertEqual(settings.ntfy_url, self.url)
|
||||
self.assertTrue(settings.ntfy_enabled)
|
||||
self.assertIsNotNone(settings.ntfy_last_tested_at)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_changing_the_url_requires_another_successful_test(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
changed_url = "https://ntfy.example.com/another-topic"
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": changed_url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
self.assertEqual(UserSettings.objects.get(user=self.user).ntfy_url, self.url)
|
||||
|
||||
@patch("members.views.send_ntfy_notification")
|
||||
def test_one_users_successful_test_cannot_authorize_another_users_settings(self, mock_send):
|
||||
self.client.post(reverse("ntfy_test_notification"), {"ntfy_url": self.url})
|
||||
self.client.force_login(self.other_user)
|
||||
|
||||
response = self.client.post(reverse("user_settings"), {"ntfy_url": self.url, "ntfy_enabled": "on"})
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Test this URL successfully")
|
||||
settings = UserSettings.objects.get(user=self.other_user)
|
||||
self.assertFalse(settings.ntfy_enabled)
|
||||
|
||||
@patch("notifications.services.send_ntfy_notification")
|
||||
def test_reusable_sender_only_delivers_for_enabled_user_settings(self, mock_send):
|
||||
self.assertFalse(send_notification(self.user, "Title", "Message"))
|
||||
UserSettings.objects.create(user=self.user, ntfy_url=self.url, ntfy_enabled=True)
|
||||
|
||||
self.assertTrue(send_notification(self.user, "Title", "Message"))
|
||||
mock_send.assert_called_once_with(self.url, "Title", "Message")
|
||||
|
||||
|
||||
class FrontendAuthenticationTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username="profile-user", password="secret")
|
||||
|
||||
def test_frontend_login_page_is_available(self):
|
||||
response = self.client.get(reverse("login"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "Sign in")
|
||||
self.assertContains(response, "csrfmiddlewaretoken")
|
||||
|
||||
def test_frontend_login_authenticates_and_returns_home(self):
|
||||
response = self.client.post(reverse("login"), {"username": "profile-user", "password": "secret"})
|
||||
|
||||
self.assertRedirects(response, "/")
|
||||
|
||||
def test_protected_settings_redirects_to_frontend_login(self):
|
||||
response = self.client.get(reverse("user_settings"))
|
||||
|
||||
self.assertRedirects(response, "/login/?next=/settings/")
|
||||
|
||||
def test_profile_circle_is_visible_only_for_authenticated_users(self):
|
||||
anonymous_response = self.client.get(reverse("hello"))
|
||||
self.assertNotContains(anonymous_response, "class=\"profile-circle\"")
|
||||
|
||||
self.client.force_login(self.user)
|
||||
authenticated_response = self.client.get(reverse("hello"))
|
||||
self.assertContains(authenticated_response, "class=\"profile-circle\"")
|
||||
self.assertContains(authenticated_response, reverse("user_settings"))
|
||||
|
||||
+84
-2
@@ -1,6 +1,16 @@
|
||||
from hashlib import sha256
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.shortcuts import render, redirect
|
||||
from .forms import MemberForm
|
||||
from .models import Member
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from notifications.services import NotificationError, send_ntfy_notification
|
||||
from .forms import MemberForm, UserSettingsForm
|
||||
from .models import Member, UserSettings
|
||||
|
||||
def member_create(request):
|
||||
if request.method == "POST":
|
||||
@@ -33,3 +43,75 @@ def hello_form(request):
|
||||
message = "Please enter your name."
|
||||
|
||||
return render(request, "hello-form.html", {"message": message})
|
||||
|
||||
NTFY_TEST_SESSION_PREFIX = "ntfy_tested_url_fingerprint"
|
||||
|
||||
|
||||
def _validated_ntfy_url(value):
|
||||
url = value.strip()
|
||||
if not url:
|
||||
raise ValidationError("Enter an ntfy topic URL.")
|
||||
URLValidator(schemes=["http", "https"])(url)
|
||||
return url
|
||||
|
||||
|
||||
def _ntfy_test_session_key(user):
|
||||
return f"{NTFY_TEST_SESSION_PREFIX}:{user.pk}"
|
||||
|
||||
|
||||
def _url_fingerprint(url):
|
||||
return sha256(url.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@login_required
|
||||
def user_settings(request):
|
||||
settings, _ = UserSettings.objects.get_or_create(user=request.user)
|
||||
saved_ntfy_url = settings.ntfy_url
|
||||
if request.method == "POST":
|
||||
form = UserSettingsForm(request.POST, instance=settings)
|
||||
if form.is_valid():
|
||||
url = form.cleaned_data["ntfy_url"]
|
||||
tested_fingerprint = request.session.get(_ntfy_test_session_key(request.user))
|
||||
was_previously_tested = saved_ntfy_url == url and settings.ntfy_last_tested_at is not None
|
||||
if url and tested_fingerprint != _url_fingerprint(url) and not was_previously_tested:
|
||||
form.add_error("ntfy_url", "Test this URL successfully before saving notification settings.")
|
||||
else:
|
||||
settings = form.save(commit=False)
|
||||
if not url:
|
||||
settings.ntfy_enabled = False
|
||||
settings.ntfy_last_tested_at = None
|
||||
elif tested_fingerprint == _url_fingerprint(url):
|
||||
settings.ntfy_last_tested_at = timezone.now()
|
||||
settings.save()
|
||||
request.session.pop(_ntfy_test_session_key(request.user), None)
|
||||
messages.success(request, "Notification settings saved.")
|
||||
return redirect("user_settings")
|
||||
else:
|
||||
form = UserSettingsForm(instance=settings)
|
||||
return render(request, "members/user_settings.html", {"form": form})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def test_ntfy_notification(request):
|
||||
try:
|
||||
url = _validated_ntfy_url(request.POST.get("ntfy_url", ""))
|
||||
except ValidationError:
|
||||
return render(
|
||||
request,
|
||||
"members/ntfy_test_result.html",
|
||||
{"error": "Enter a valid HTTP or HTTPS ntfy topic URL."},
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
send_ntfy_notification(
|
||||
url,
|
||||
title="Fireworks Detector",
|
||||
message="ntfy notifications are configured correctly.",
|
||||
)
|
||||
except NotificationError as error:
|
||||
return render(request, "members/ntfy_test_result.html", {"error": str(error)}, status=502)
|
||||
|
||||
request.session[_ntfy_test_session_key(request.user)] = _url_fingerprint(url)
|
||||
return render(request, "members/ntfy_test_result.html", {"success": True})
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -32,6 +32,8 @@ ALLOWED_HOSTS = ["django.jorendegraaf.eu", "100.91.62.59"]
|
||||
CSRF_TRUSTED_ORIGINS = ["https://django.jorendegraaf.eu"]
|
||||
# Caddy supplies this header for proxied HTTPS requests.
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
LOGIN_URL = "/login/"
|
||||
LOGIN_REDIRECT_URL = "/"
|
||||
|
||||
|
||||
# Application definition
|
||||
@@ -43,6 +45,7 @@ INSTALLED_APPS = [
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'vite_integration',
|
||||
'hello',
|
||||
'fireworks_detect',
|
||||
'members'
|
||||
@@ -124,6 +127,9 @@ USE_TZ = True
|
||||
# https://docs.djangoproject.com/en/6.1/howto/static-files/
|
||||
|
||||
STATICFILES_DIRS = [BASE_DIR / 'project_admin' / 'static']
|
||||
|
||||
# H3 resolution for new coordinate-bearing fireworks records (0–15).
|
||||
FIREWORKS_H3_RESOLUTION = 9
|
||||
STATIC_URL = 'static/'
|
||||
STATIC_ROOT = BASE_DIR / 'staticfiles'
|
||||
MEDIA_URL = 'media/'
|
||||
|
||||
@@ -15,12 +15,16 @@ Including another URLconf
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.conf import settings
|
||||
from django.urls import path, include, re_path
|
||||
from django.views.static import serve
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('login/', auth_views.LoginView.as_view(template_name='members/login.html'), name='login'),
|
||||
path('classifications/', include('fireworks_detect.classification_urls')),
|
||||
path('settings/', include('members.settings_urls')),
|
||||
path('', include('hello.urls')),
|
||||
path('fireworks/', include('fireworks_detect.urls')),
|
||||
path('members/', include('members.urls'))
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .services import NotificationError, send_notification, send_ntfy_notification
|
||||
|
||||
__all__ = ["NotificationError", "send_notification", "send_ntfy_notification"]
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,52 @@
|
||||
"""Small reusable notification helpers for project notification providers."""
|
||||
|
||||
import socket
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
class NotificationError(Exception):
|
||||
"""A safe, user-displayable notification delivery failure."""
|
||||
|
||||
|
||||
def send_ntfy_notification(url, title, message, timeout=10):
|
||||
"""Publish a plain-text notification to an ntfy topic URL."""
|
||||
request = Request(
|
||||
url,
|
||||
data=message.encode("utf-8"),
|
||||
headers={"Content-Type": "text/plain; charset=utf-8", "Title": title},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
response = urlopen(request, timeout=timeout)
|
||||
status_code = response.getcode()
|
||||
response.close()
|
||||
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:
|
||||
if isinstance(error.reason, (TimeoutError, socket.timeout)):
|
||||
raise NotificationError("Connection to the ntfy server timed out.") from 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_code < 300:
|
||||
raise NotificationError(f"ntfy server responded with HTTP {status_code}.")
|
||||
return True
|
||||
|
||||
|
||||
def send_notification(user, title, message):
|
||||
"""Send through the user's enabled provider, or safely do nothing."""
|
||||
from members.models import UserSettings
|
||||
|
||||
try:
|
||||
settings = UserSettings.objects.get(user=user)
|
||||
except UserSettings.DoesNotExist:
|
||||
return False
|
||||
|
||||
if not settings.ntfy_enabled or not settings.ntfy_url:
|
||||
return False
|
||||
send_ntfy_notification(settings.ntfy_url, title, message)
|
||||
return True
|
||||
Generated
+1435
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "django-vite-integration",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"concurrently": "^9.1.2",
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Django==6.1.1
|
||||
h3>=4.1,<5
|
||||
@@ -0,0 +1,13 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const host = process.env.DJANGO_HOST ?? "0.0.0.0";
|
||||
const port = process.env.DJANGO_PORT ?? "8000";
|
||||
const command = process.env.DJANGO_DEV_COMMAND ?? `python manage.py runserver ${host}:${port}`;
|
||||
const child = spawn(command, { shell: true, stdio: "inherit" });
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -1 +1 @@
|
||||
{% extends "admin/fireworks_detect/classification_change_form.html" %}{% block after_field_sets %}{{ block.super }}{% if original %}<section class="audio-preview"><style>.audio-preview{display:flex;align-items:center;gap:12px;margin:18px 0;padding:14px;border:1px solid #2b3d68;border-radius:10px;background:#14203a}.audio-play{display:inline-flex;align-items:center;gap:9px;border:0;border-radius:999px;padding:10px 15px!important;color:#121a34;font-weight:850;background:linear-gradient(135deg,#99c8ff,#c6adff);cursor:pointer}.audio-play__icon{display:grid;width:22px;height:22px;place-items:center;border-radius:50%;color:#fff;background:#172443}.audio-play.is-loading .audio-play__icon{color:transparent;border:2px solid #263a76;border-top-color:#fff;animation:audio-spin .7s linear infinite}.audio-status{color:#aab9d8;font-size:.85rem}@keyframes audio-spin{to{transform:rotate(360deg)}}</style><button class="audio-play" type="button" data-audio-url="{% url original.admin_audio_route original.pk %}"><span class="audio-play__icon">▶</span><span class="audio-play__label">Play recording</span></button><span class="audio-status" aria-live="polite">Loads only when played</span><audio preload="none"></audio></section><script>document.querySelectorAll('.audio-preview').forEach(function(box){var button=box.querySelector('.audio-play'),audio=box.querySelector('audio'),label=box.querySelector('.audio-play__label'),status=box.querySelector('.audio-status');button.addEventListener('click',function(){if(!audio.src){audio.src=button.dataset.audioUrl;button.classList.add('is-loading');status.textContent='Loading recording…';}if(audio.paused){audio.play().catch(function(){button.classList.remove('is-loading');status.textContent='Could not play this recording.';});}else{audio.pause();}});audio.addEventListener('playing',function(){button.classList.remove('is-loading');label.textContent='Pause recording';status.textContent='Playing now';});audio.addEventListener('pause',function(){if(!audio.ended){label.textContent='Resume recording';status.textContent='Paused';}});audio.addEventListener('ended',function(){label.textContent='Replay recording';status.textContent='Finished';});audio.addEventListener('waiting',function(){button.classList.add('is-loading');status.textContent='Buffering…';});audio.addEventListener('canplay',function(){button.classList.remove('is-loading');});audio.addEventListener('error',function(){button.classList.remove('is-loading');status.textContent='Could not load this recording.';});});</script>{% endif %}{% endblock %}
|
||||
{% extends "admin/fireworks_detect/classification_change_form.html" %}{% block after_field_sets %}{{ block.super }}{% if original.audio_file %}<section class="audio-preview"><style>.audio-preview{display:flex;align-items:center;gap:12px;margin:18px 0;padding:14px;border:1px solid #2b3d68;border-radius:10px;background:#14203a}.audio-play{display:inline-flex;align-items:center;gap:9px;border:0;border-radius:999px;padding:10px 15px!important;color:#121a34;font-weight:850;background:linear-gradient(135deg,#99c8ff,#c6adff);cursor:pointer}.audio-play__icon{display:grid;width:22px;height:22px;place-items:center;border-radius:50%;color:#fff;background:#172443}.audio-play.is-loading .audio-play__icon{color:transparent;border:2px solid #263a76;border-top-color:#fff;animation:audio-spin .7s linear infinite}.audio-status{color:#aab9d8;font-size:.85rem}@keyframes audio-spin{to{transform:rotate(360deg)}}</style><button class="audio-play" type="button" data-audio-url="{% url original.admin_audio_route original.pk %}"><span class="audio-play__icon">▶</span><span class="audio-play__label">Play recording</span></button><span class="audio-status" aria-live="polite">Loads only when played</span><audio preload="none"></audio></section><script>document.querySelectorAll('.audio-preview').forEach(function(box){var button=box.querySelector('.audio-play'),audio=box.querySelector('audio'),label=box.querySelector('.audio-play__label'),status=box.querySelector('.audio-status');button.addEventListener('click',function(){if(!audio.src){audio.src=button.dataset.audioUrl;button.classList.add('is-loading');status.textContent='Loading recording…';}if(audio.paused){audio.play().catch(function(){button.classList.remove('is-loading');status.textContent='Could not play this recording.';});}else{audio.pause();}});audio.addEventListener('playing',function(){button.classList.remove('is-loading');label.textContent='Pause recording';status.textContent='Playing now';});audio.addEventListener('pause',function(){if(!audio.ended){label.textContent='Resume recording';status.textContent='Paused';}});audio.addEventListener('ended',function(){label.textContent='Replay recording';status.textContent='Finished';});audio.addEventListener('waiting',function(){button.classList.add('is-loading');status.textContent='Buffering…';});audio.addEventListener('canplay',function(){button.classList.remove('is-loading');});audio.addEventListener('error',function(){button.classList.remove('is-loading');status.textContent='Could not load this recording.';});});</script>{% endif %}{% endblock %}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { resolve } from "node:path";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
const root = process.cwd();
|
||||
const environment = process.env;
|
||||
const entrypoint = environment.VITE_ENTRY ?? "frontend/src/main.js";
|
||||
const outputDirectory = environment.VITE_OUT_DIR ?? "vite_integration/static/vite";
|
||||
|
||||
export default defineConfig({
|
||||
base: environment.VITE_BASE_URL ?? "/static/vite/",
|
||||
server: {
|
||||
host: environment.VITE_HOST ?? "127.0.0.1",
|
||||
port: Number(environment.VITE_PORT ?? 5173),
|
||||
strictPort: true,
|
||||
cors: true,
|
||||
},
|
||||
build: {
|
||||
outDir: resolve(root, outputDirectory),
|
||||
emptyOutDir: true,
|
||||
manifest: ".vite/manifest.json",
|
||||
rollupOptions: {
|
||||
input: resolve(root, entrypoint),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
"""Portable Django template tags for Vite assets."""
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ViteIntegrationConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "vite_integration"
|
||||
@@ -0,0 +1,3 @@
|
||||
{% load vite %}
|
||||
{# Add this once inside a base template's <head> or just before </body>. #}
|
||||
{% vite_asset "frontend/src/main.js" %}
|
||||
@@ -0,0 +1 @@
|
||||
"""Template-tag package for the portable Vite integration."""
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,106 @@
|
||||
"""Django template tags that select Vite HMR or manifest-backed assets."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from django import template
|
||||
from django.conf import settings
|
||||
from django.contrib.staticfiles import finders
|
||||
from django.template import TemplateSyntaxError
|
||||
from django.templatetags.static import static
|
||||
from django.utils.safestring import mark_safe
|
||||
from django.utils.html import format_html
|
||||
|
||||
register = template.Library()
|
||||
|
||||
|
||||
def _setting(name, default=None):
|
||||
value = getattr(settings, name, None)
|
||||
return value if value is not None else os.environ.get(name, default)
|
||||
|
||||
|
||||
def _as_bool(value):
|
||||
return str(value).lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _use_dev_server():
|
||||
return _as_bool(_setting("VITE_USE_DEV_SERVER", False))
|
||||
|
||||
|
||||
def _static_prefix():
|
||||
return str(_setting("VITE_STATIC_PREFIX", "vite")).strip("/")
|
||||
|
||||
|
||||
def _manifest_path():
|
||||
configured_path = _setting("VITE_MANIFEST_PATH")
|
||||
if configured_path:
|
||||
return Path(configured_path)
|
||||
found_path = finders.find(f"{_static_prefix()}/.vite/manifest.json")
|
||||
if found_path:
|
||||
return Path(found_path)
|
||||
raise TemplateSyntaxError(
|
||||
"Vite manifest not found. Run `npm run build`, then `python manage.py collectstatic`."
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(maxsize=8)
|
||||
def _read_manifest(path, modified_time):
|
||||
with Path(path).open(encoding="utf-8") as manifest_file:
|
||||
manifest = json.load(manifest_file)
|
||||
if not isinstance(manifest, dict):
|
||||
raise TemplateSyntaxError("Vite manifest must contain a JSON object.")
|
||||
return manifest
|
||||
|
||||
|
||||
def _manifest():
|
||||
path = _manifest_path()
|
||||
try:
|
||||
modified_time = path.stat().st_mtime_ns
|
||||
except OSError as error:
|
||||
raise TemplateSyntaxError("Vite manifest could not be read.") from error
|
||||
return _read_manifest(str(path), modified_time)
|
||||
|
||||
|
||||
def _production_tags(entrypoint):
|
||||
manifest = _manifest()
|
||||
try:
|
||||
entry = manifest[entrypoint]
|
||||
except KeyError as error:
|
||||
raise TemplateSyntaxError(f"Vite entry point `{entrypoint}` is missing from the manifest.") from error
|
||||
|
||||
css_files = []
|
||||
visited = set()
|
||||
|
||||
def visit(chunk_name):
|
||||
if chunk_name in visited:
|
||||
return
|
||||
visited.add(chunk_name)
|
||||
chunk = manifest.get(chunk_name, {})
|
||||
for imported_chunk in chunk.get("imports", []):
|
||||
visit(imported_chunk)
|
||||
for css_file in chunk.get("css", []):
|
||||
if css_file not in css_files:
|
||||
css_files.append(css_file)
|
||||
|
||||
visit(entrypoint)
|
||||
tags = [format_html('<link rel="stylesheet" href="{}">', static(f"{_static_prefix()}/{css_file}")) for css_file in css_files]
|
||||
tags.append(format_html('<script type="module" src="{}"></script>', static(f"{_static_prefix()}/{entry['file']}")))
|
||||
return mark_safe("\n".join(tags))
|
||||
|
||||
|
||||
@register.simple_tag
|
||||
def vite_asset(entrypoint):
|
||||
"""Render one entry point from Vite's dev server or production manifest."""
|
||||
if _use_dev_server():
|
||||
dev_server_url = _setting("VITE_DEV_SERVER_URL", "http://127.0.0.1:5173/").rstrip("/") + "/"
|
||||
hmr_client_url = urljoin(dev_server_url, "@vite/client")
|
||||
entry_url = urljoin(dev_server_url, entrypoint.lstrip("/"))
|
||||
return format_html(
|
||||
'<script type="module" src="{}"></script>\n<script type="module" src="{}"></script>',
|
||||
hmr_client_url,
|
||||
entry_url,
|
||||
)
|
||||
return _production_tags(entrypoint)
|
||||
@@ -0,0 +1,31 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from django.template import Context, Template
|
||||
from django.test import SimpleTestCase, override_settings
|
||||
|
||||
from .templatetags.vite import _read_manifest
|
||||
|
||||
|
||||
class ViteAssetTemplateTagTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
_read_manifest.cache_clear()
|
||||
|
||||
def render_asset(self):
|
||||
return Template('{% load vite %}{% vite_asset "frontend/src/main.js" %}').render(Context())
|
||||
|
||||
@override_settings(VITE_USE_DEV_SERVER=True, VITE_DEV_SERVER_URL="http://vite.test:4173/")
|
||||
def test_development_renders_hmr_client_and_entrypoint(self):
|
||||
rendered = self.render_asset()
|
||||
|
||||
self.assertIn("http://vite.test:4173/@vite/client", rendered)
|
||||
self.assertIn("http://vite.test:4173/frontend/src/main.js", rendered)
|
||||
|
||||
def test_production_resolves_css_and_script_from_manifest(self):
|
||||
with TemporaryDirectory() as temporary_directory:
|
||||
manifest_path = Path(temporary_directory) / "manifest.json"
|
||||
manifest_path.write_text(json.dumps({"frontend/src/main.js": {"file": "assets/main-hash.js", "css": ["assets/main-hash.css"]}}), encoding="utf-8")
|
||||
with override_settings(VITE_USE_DEV_SERVER=False, VITE_MANIFEST_PATH=manifest_path, VITE_STATIC_PREFIX="vite", STATIC_URL="/static/"):
|
||||
rendered = self.render_asset()
|
||||
|
||||
Reference in New Issue
Block a user