10 Commits
Author SHA1 Message Date
Joren de Graaf bca523be8a Ignore ZIP archives 2026-10-23 14:45:47 +02:00
Joren de Graaf 54f69077c1 Ignore local database and uploaded media 2026-10-23 14:36:20 +02:00
Joren de Graaf 206f5f2466 latest changes 2026-10-23 14:32:24 +02:00
Joren de Graaf 712af2839d latest changes incl grocery list 2026-10-22 10:27:11 +02:00
Joren de Graaf aadadff69e latest changes 2026-10-15 20:36:40 +02:00
Joren de Graaf ad78913bd5 latest changes 2026-10-15 12:50:21 +02:00
Joren de Graaf 4aa13de925 fix now card width 2026-10-14 18:17:27 +02:00
Joren de Graaf 314eb6b4ec added scheduling 2026-10-10 16:03:14 +02:00
Joren de Graaf 7559b61399 added Arduino firmware concept files 2026-10-09 15:17:53 +02:00
Joren de Graaf c45810762a progressing with scss conversion 2026-10-07 13:03:22 +02:00
244 changed files with 10733 additions and 2170 deletions
+11
View File
@@ -0,0 +1,11 @@
# Burst Events
A report with at least three `occurrences` is a Burst Event. `event_kind`, `is_burst`, `bangs_per_15_minutes`, and `burst_intensity` are derived properties on both PendingEvent and Event; they are never stored separately. One or two occurrences are ordinary reports.
`captured_at` is the reported occurrence time for a manual report. PendingEvent `created_at` is its actual submission time; approval copies that value into Event `submitted_at`, while Event `approved_at` remains the approval time. Older Events have an unknown `submitted_at` because their original submission time cannot be reconstructed. `occurrence_time_approximate` records uncertainty about the reported time. No individual bang times are inferred from an aggregate report.
`observation_duration_minutes` holds a window only when the reporter explicitly accepts an estimate, or when a future source provides a measured window. `observation_duration_kind` distinguishes `estimated` from `measured`; a blank kind or duration means intensity is unavailable. The quick form suggests 15 minutes and asks the reporter to accept that estimate. Existing records migrate with an unknown duration, preserving their counts without inventing an intensity.
The normalised rate is `occurrences × 15 / observation_duration_minutes`. Provisional presentation bands live in `fireworks_detect/bursts.py`: light below 5, moderate from 5 to below 10, intense from 10 per 15 minutes. This describes **frequency, not loudness**. The map event JSON exposes the count, event kind, duration, duration kind, rate, intensity, and approximate-time flag for future timeline work. No timeline is rendered in this pass.
Quick reports remain Pending until moderated. The browser can enhance the form, while the POST endpoint also accepts an ordinary server-rendered form submission with no microphone, classifier, or JavaScript. A reporter can correct the count and estimated duration before moderation through a session-scoped receipt form; each correction creates a ManualReportRevision. Corrections do not change the original occurrence or submission time.
+28
View File
@@ -0,0 +1,28 @@
# Burst Listening iPhone PWA field test
This feature is a foreground experiment. An installed PWA, Guided Access, or a
screen wake lock cannot guarantee microphone continuity after screen lock,
backgrounding, an incoming call, or iOS memory pressure. Keep the screen on
and watch the visible stream state. Do not count time after an interruption as
covered listening time.
For each run, record the iPhone model, iOS version, browser/PWA mode, network,
selected test setup, start/end time, and battery levels. Export the diagnostic
JSON before closing the review page. Compare its last client audio frame,
last server heartbeat, server timeout detection, and first resumed observation.
The interval between them is uncertain; neither timestamp proves when the mic
stopped. A server timeout proves only that HTTP heartbeats stopped arriving.
| Duration | Setup | Stimulus and checks |
| --- | --- | --- |
| 10 min | Foreground, screen on | Four spaced bangs; verify four playable clips, quiet interval, stop/review/submit. |
| 15 min | Installed Home Screen PWA, Guided Access with Display Auto-Lock Never | Four spaced bangs and two close bangs; check clip grouping, waveform, timer, battery, memory and server timeline. |
| 20 min | Foreground with optional Wake Lock | Verify auto-stop, bounded clips, upload retries, cleanup and server expiry. |
| Short runs | Manual lock, natural auto-lock, background/foreground, incoming call, low battery, network loss/reconnect | Confirm visible interruption, no automatic restart, recovered clips and uncertainty interval. |
The shared server watchdog must be running for the independent 15-second
heartbeat-lost diagnostic. Start the provided systemd user service or run
`python manage.py watch_burst_sessions --interval 5` under the same environment
as Django. The 10/15/20-minute physical iPhone scenarios remain unverified
until tested on a device. Local browser tests cannot emulate iOS suspension or
microphone access under Guided Access.
+105
View File
@@ -0,0 +1,105 @@
# Field notes: specification review and implementation
## Review decisions
The requested separation between recorded evidence and human context fits the
application. Inspection found these differences from the illustrative spec:
1. **Bursts are Event/PendingEvent records with occurrences >= 3**, not separate
incidents. The live browser listener has no server-side event until submission.
`FieldNoteContext` is a small, author-owned association record, with no incident
timestamps, count, audio or classification of its own. It holds a draft UUID and
later references the existing PendingEvent or Event. Multiple notes attach once
to that report rather than being copied across individual bangs.
2. **Pending manual ownership was session-based.** Note contexts preserve author
attribution across sessions without inventing ownership for old reports. New
draft tokens are signed, author-bound and expire after seven days. A submitted
token cannot be reused for another report; the UI rotates it on success. Late
note saves still follow the original report through moderation.
3. **The frontend uses custom SCSS, HTMX and existing theme tokens**, not Bootstrap.
These conventions are reused; no second CSS framework is introduced.
4. **There was no incident export pipeline or event merge UI.** Added CSV/JSON
note exports through one permission-filtered service. PDF export and event
regrouping interfaces remain outside this pass. A tested regrouping service
preserves note provenance for future merge operations.
5. **Corrections are new notes.** No edit/delete route or editable admin form is
provided. This keeps original text and entry timestamps unchanged. Verification
labels describe the author's stated assessment, not automated validation.
6. **Timezone follows Django's active timezone**, currently Europe/Amsterdam;
there is no per-user timezone setting. Datetimes are stored timezone-aware,
with the timezone shown beside entry/observation times. Adding a user timezone
preference later can use the same fields.
## Privacy and permissions
- Notes default to private, unknown source and unverified. Only content is required.
- An authenticated author can read/create their own notes. Reportable notes are
still not public and do not become verified.
- Approved events are already public; authenticated users may add their own notes
to them. Pending targets require existing session ownership, sensor ownership,
a note context owned by that user, or staff `view_pendingevent` permission.
- `view_all_fieldnotes` explicitly allows reading other authors' private notes.
Staff status alone does not. Django superusers have this permission.
- `export_reportable_fieldnotes` explicitly allows exporting other authors'
reportable notes. Without it, exports contain only the caller's reportable notes.
**Private notes are excluded even for superusers.** Read-all permission does not
imply export-all permission.
- Every export starts with `field_notes.reportable_notes(user)`. Future PDF/API
reporting must use this service, rather than `visible_to()` or raw relations.
- CSV escapes formula-like user values; HTML renders escaped plain text and keeps
line breaks. Public event/map responses do not serialize note data.
- Link operations are author-only, POST/CSRF-protected, and only accept an existing
approved event. Existing linked notes cannot be silently reparented through the
user endpoint. Each standalone observation context can hold several live notes;
linking it moves that observation's notes together.
- Admin is read-only and uses the same visibility boundary. Association history
is similarly scoped. ORM `save()` rejects note/history edits; direct SQL or
`QuerySet.update()` is not an application editing interface and must not be used
to bypass this policy.
## Lifecycle and interfaces
- The dashboard's Add field note form is adjacent to quick reporting and updates
only its own HTMX region, leaving listener/audio controls mounted and running.
- Submission binds the draft context to Pending Review. Approval atomically moves
contexts to the approved Event and records the moderator (or system/null actor
for non-request approvals). Notes retain their original entry timestamps.
- Denial/deletion clears the foreign key but preserves the note and its historical
target ID. The observation remains available in My field notes.
- `regroup_event_notes(actor, source, target)` requires staff, `change_event` and
`view_all_fieldnotes`. Existing or future merge code must call it inside its
transaction before deleting the source. It moves associations without copying
notes and records previous/current event IDs. No automatic grouping is added.
- Historical event details show only visible notes and counts. Direct event pages
and the archive now have normal links for no-JavaScript access.
- `/fireworks/notes/` creates standalone observations and lists accessible notes;
event/pending filters provide contextual forms. `/fireworks/notes/export/json/`
and `/fireworks/notes/export/csv/` export authorised reportable notes, optionally
filtered by approved event ID.
- Standard POST forms redirect after saving. HTMX forms return their own updated
region; validation responses intentionally use HTTP 200 so HTMX renders errors.
- Occurrence and entry dates are displayed separately. New information is appended
chronologically; author-supplied observed time does not reorder entry history.
## Validation and deployment
Migration `0014` adds three tables, constraints and an author/time index. It does
not rewrite existing event data. Apply with `python manage.py migrate` after
updating the application; build assets with the existing `npm run build` command.
No firmware changes or version bump are needed for this Django-only feature.
Automated tests cover defaults, escaping, anonymous/cross-user access, explicit
staff permissions, private export exclusion (including superuser), source and
uncertainty preservation, observed/entry timestamps, append-only saves, invalid
forms, active draft binding, approval, late saves, stale-token rejection,
standalone linking, regrouping and denied-report retention.
Browser verification uses the actual Django application with an isolated SQLite
DB under `/tmp`. It covers HTMX note saves during a **synthetic browser audio
stream**, listener continuity, report binding/token rotation, historical notes,
mobile/desktop layouts, dark/light appearance, accessibility labels, exports and
standard form submission in a JavaScript-disabled browser context. This is not a
microphone/hardware validation and does not claim classification accuracy.
Out of scope: attachments, CCTV files, witness identity management, PDF generation,
new incident/merge interfaces, full timeline redesign, or changing detection logic.
+11
View File
@@ -150,3 +150,14 @@ The service runs `/home/jorenmartijn/python/.venv-notifications/bin/python` with
project as its working directory. To keep the user timer running after logout,
run `sudo loginctl enable-linger jorenmartijn` once on the laptop. Check a run
with `journalctl --user -u send-pending-notifications.service -n 30`.
### Burst Listening watchdog
Run one shared `watch_burst_sessions` process alongside Django so a suspended PWA is
marked heartbeat-lost independently of browser JavaScript. A systemd user service
is provided at `deploy/systemd/watch-burst-sessions.service`; enable it for the
same user and Python environment as Django. `--once` is available for tests and
manual checks. A one-minute cron job cannot meet the 15-second timeout target.
For a user service: copy the unit to `~/.config/systemd/user/`, run
`systemctl --user daemon-reload`, then
`systemctl --user enable --now watch-burst-sessions.service`.
+32
View File
@@ -0,0 +1,32 @@
# Waveshare V2 firmware integration status
The owner has confirmed a non-touch Waveshare ESP32-S3-ePaper-1.54 V2 board. The firmware now lives at `../arduino/BoomCast_Waveshare_Arduino/`; that folder is currently **outside** the Django Git worktree (`django/`). Its sketch, build guide, source, pinned preparation script, local-config example, ignore rules, and hardware/API/checklist documents are there.
The official Waveshare support was inspected at commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`. The Arduino audio `board_cfg.h` and explicitly V2 ESP-IDF audio example agree on ES8311 I2S pins. The official Arduino SD example uses CLK/D0/CMD 39/40/41. The firmware uses those pins. Waveshare documents V2 as 8 MB flash and 8 MB PSRAM and says V1/V2 examples are not interchangeable.
## Implemented in source
- Audio reads now check the codec return code, clear input buffers first, discard failed blocks, abort a capture after a read error, select one fixed microphone slot, and count read/recording errors. Capture duration uses the available pre-roll plus the requested post-roll; UTC capture-start and trigger timestamps are retained when time is valid.
- SD commits use checked WAV and sidecar writes, flush/fsync/close, WAV length/header validation, final renames, interrupted-commit recovery, a queue commit marker, oldest-first selection across the directory, an event-count cap, and a free-space reserve. Incomplete files are excluded from upload.
- Uploads stream file contents through `WiFiClientSecure` with a trusted CA, require HTTPS, send the actual `/api/pending/` fields, parse JSON receipts, verify the echoed event ID and submission ID, and retain files after ambiguous responses. Automatic retries use bounded exponential backoff and jitter. Source-embedded token placeholders were replaced with an ignored local header and optional NVS token; shared setup and management passwords were replaced with per-device NVS passwords.
- ePaper owner status reflects listening, recording, queue/offline, uploading, successful submission, retry failure, and audio error counters.
- Django now returns `event_id` in first and duplicate receipts and accepts an explicit `time_state=unknown` when the device clock was not synchronized. The same Pending Review and classifier pipeline remains in use.
## Verification performed
- Official Waveshare pin/support comparison at the pinned commit.
- The pinned `prepare_from_waveshare.sh` completed successfully against a checkout at that commit.
- Arduino CLI 1.5.1 compiled the sketch for ESP32-S3 with ESP32 core 3.3.0, 8 MB flash, OPI PSRAM, and the 8 MB partition scheme. The only emitted warnings were in copied Waveshare support and Espressif touch APIs.
- The `fireworks_detect` Django suite passed: 39 tests. Firmware-shaped unknown-time and receipt fields have focused backend tests.
- Firmware `.gitignore` patterns were checked for local credentials, copied support, and build artifacts.
## Still open
- **Firmware compile passed; no flash was performed.** Arduino CLI 1.5.1 compiled the sketch with ESP32 core 3.3.0, Waveshare support at the pinned commit, LVGL 8.4.0, ArduinoJson 7.4.3, 8 MB flash, and OPI PSRAM. The build reports 1,350,599 bytes of program storage (40%) and 99,368 bytes of global dynamic memory (30%). Device runtime RAM use is unmeasured.
- **No physical V2 test was performed.** The fixed microphone slot, actual audio fidelity, short successful codec reads, ePaper refresh, SD power-cut behavior, TLS handshake, and offline recovery need the real board.
- Waveshare's codec API reports read success/failure but not a byte count; a successful short read cannot be detected through the current wrapper.
- FAT does not provide an atomic transaction spanning WAV and sidecar. Valid interrupted commits are recovered; incomplete/orphan files remain on SD for manual inspection rather than being uploaded or overwritten.
- The uploader currently runs synchronously in the main loop. During a slow HTTPS attempt, the local web UI and display update may pause. Verify this on hardware and move upload to a worker task if it affects usability or watchdog health.
- Arduino source is not tracked by the current Django Git repository. Decide on a project-wide repository or a dedicated firmware repository before relying on source control for deployment.
See `../arduino/BoomCast_Waveshare_Arduino/docs/validation-checklist.md` for the pending physical acceptance checks. Do not treat this source review or the Django tests as hardware validation.
+11
View File
@@ -0,0 +1,11 @@
# Sensor submission contract (v1)
`POST /api/pending/` accepts `multipart/form-data` from an active, registered sensor. Send `Authorization: Bearer <sensor token>`. The token determines the sensor and owner; send the sensor's database ID in `sensor_id` as an assertion, never as authority.
Required parts: `file` (16-bit PCM mono WAV), `sensor_id`, `event_id` (1–100 ASCII letters, digits, `_` or `-`), `captured_at` (UTC ISO 8601 timestamp with offset or Unix seconds, or omit it with `time_state=unknown` when the device clock was not synchronized), `duration_seconds` (positive number matching the WAV within 0.1 seconds), and `firmware_version` (1–64 printable characters). Optional: `trigger_type` (short label), `signal_rms`, `signal_peak` (finite nonnegative numbers), and `latitude`/`longitude` (untrusted device claims, retained only as metadata). No client location is promoted to the trusted event location.
WAV data must be PCM, mono, 16-bit, at 16 kHz, at most 25 MiB, and 0.1–30 seconds long. A successful first submission returns HTTP 201 with `event_id`, `submission_id`, `status: pending`, and classifier results. A repeat of the same `(sensor, event_id)` returns HTTP 200 with the same `event_id`, `submission_id`, and `duplicate: true`; a different body with the same ID returns HTTP 409. Errors have `code` and `detail` fields. HTTP 429 means retry after the `Retry-After` interval. HTTP 502 means classification failed and the device should retain the queued clip.
The existing `/fireworks/classify/` route remains available for older clients. New firmware should use this contract. Pending audio stays behind the staff-only playback route and follows the existing accept/reject workflow and storage lifetime.
`captured_at` means the start of the actual recorded WAV. Optional `capture_started_at`, `triggered_at`, and `queued_at` are UTC ISO 8601 timestamps; `time_state=unknown` leaves the database capture time null. A missing timestamp without that explicit state is invalid.
@@ -0,0 +1,13 @@
[Unit]
Description=BoomCast Burst Listening heartbeat watchdog
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/jorenmartijn/python/django
ExecStart=/home/jorenmartijn/python/.venv/bin/python /home/jorenmartijn/python/django/manage.py watch_burst_sessions --interval 5
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
+25
View File
@@ -0,0 +1,25 @@
# BoomCast read-only MCP
The stateless Streamable HTTP endpoint is `POST /mcp/` on the **existing Django web server**. The normal local development command uses `127.0.0.1:8000`; MCP needs no second port or process. Use the public HTTPS Django origin for a remote client. Do not expose the local HTTP listener directly.
Run migrations, then issue a separate credential for an active user who has both `fireworks_detect.view_event` and `fireworks_detect.view_pendingevent` permissions:
```sh
python manage.py migrate
python manage.py create_mcp_token USERNAME --name "My MCP client"
```
The command prints the token once. Configure the MCP client with a Streamable HTTP URL such as `https://django.jorendegraaf.eu/mcp/` and header `Authorization: Bearer bmcp_...`. Refresh the client's MCP tools after configuring it. A sensor `ss_...` Bearer token, browser login cookie, or anonymous request cannot access the endpoint. To revoke a credential, set its `McpAccessToken.revoked_at` in Django admin/shell (or delete the record). Removing either Django view permission or deactivating the user also denies access. MCP uses the same Django user permission backend as admin; no write permissions are needed.
Available tools: `submissions_list`, `submissions_get`, `submissions_stats`, and `pending_summary`. Date filters use `YYYY-MM-DD` and apply to review date. A query covers at most 366 days; if omitted, the default is the most recent 366 days. List pages are capped at 100 items and offset 10,000. The endpoint is limited to 120 requests per minute per user. It accepts JSON responses for MCP initialize, tool discovery and tool calls. It supports no write methods or server state changes.
Only approved `Event` rows are individually available. The existing review workflow **deletes denied `PendingEvent` rows**, so historical denial statistics and manually confirmed sound classes do not exist in the current data model. MCP reports `review_outcome: approved`, `confirmed_classification: null`, and `confirmed_classification_available: false` rather than treating a YAMNet prediction as a human confirmation. Pending results contain counts only. The only location field is the existing H3 cell or a cell calculated using the configured H3 resolution; exact coordinates, audio, filenames, free-text locations, notes, sensor identity, and raw classifier responses are omitted.
For a quick protocol check after client setup:
```sh
curl -sS https://django.jorendegraaf.eu/mcp/ \
-H "Authorization: Bearer $BOOMCAST_MCP_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+95 -7
View File
@@ -7,13 +7,23 @@ from django.core.exceptions import PermissionDenied
from django.http import HttpResponseNotAllowed
from django.shortcuts import get_object_or_404, redirect
from django.urls import path, reverse
from django.utils.html import format_html
from django.utils.html import format_html, format_html_join
from django.utils.translation import gettext as _, gettext_lazy, ngettext
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
from .models import BrowserProcessingSettings, BurstCapture, BurstSession, ClassificationRule, Event, ManualReportRevision, McpAccessToken, PendingEvent, Sensor
from . import views as classifier_views
@admin.register(McpAccessToken)
class McpAccessTokenAdmin(admin.ModelAdmin):
list_display = ("user", "name", "created_at", "revoked_at")
readonly_fields = ("user", "name", "token_hash", "created_at")
fields = ("user", "name", "created_at", "revoked_at")
def has_add_permission(self, request):
return False
@admin.register(ClassificationRule)
class ClassificationRuleAdmin(admin.ModelAdmin):
list_display = ("value", "rule_type", "enabled")
@@ -49,11 +59,11 @@ class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "source_type", "sensor", "occurrences", "location", "visually_confirmed", "primary_label", "primary_score", "duration", "created_at")
list_display = ("original_filename", "source_type", "sensor", "occurrences", "event_kind", "observation_duration_minutes", "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", "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")
fields = ("audio_file", "sensor", "source_type", "occurrences", "observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate", "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=gettext_lazy("Direction"))
@@ -68,6 +78,25 @@ class ClassificationAdmin(admin.ModelAdmin):
@admin.register(PendingEvent)
class PendingEventAdmin(ClassificationAdmin):
actions = ("approve_selected", "deny_selected")
list_display = ("original_filename", "source_type", "sensor", "sensor_owner", "captured_at", "created_at", "primary_label", "primary_score", "duration")
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata")
fields = ClassificationAdmin.fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures", "pretty_classifier_response")
readonly_fields = ClassificationAdmin.readonly_fields + ("sensor_owner", "captured_at", "firmware_version", "device_metadata", "burst_captures")
@admin.display(description=gettext_lazy("Burst captures"))
def burst_captures(self, obj):
if not hasattr(obj, "burst_session"):
return "—"
parts = []
for capture in obj.burst_session.captures.all():
url = reverse("fireworks_detect:burst_capture_audio", args=[capture.pk])
parts.append(format_html('<details><summary>{} · {}s{}</summary><audio controls preload="none" src="{}"></audio></details>', capture.captured_at, f"{capture.duration_seconds:.1f}", " · primary" if capture.is_primary else "", url))
return format_html("<div>{}</div>", format_html_join("", "{}", ((part,) for part in parts)))
@admin.display(description=gettext_lazy("Sensor owner"))
def sensor_owner(self, obj):
return obj.sensor.owner if obj.sensor and obj.sensor.owner_id else "—"
change_form_template = "admin/fireworks_detect/pending_change_form.html"
def get_urls(self):
@@ -126,7 +155,7 @@ class PendingEventAdmin(ClassificationAdmin):
def approve_selected(self, request, queryset):
approved = 0
for pending in queryset:
pending.approve()
pending.approve(actor=request.user)
approved += 1
self.message_user(request, ngettext("%(count)d sample approved and moved to Events.", "%(count)d samples approved and moved to Events.", approved) % {"count": approved}, messages.SUCCESS)
@@ -141,13 +170,28 @@ class PendingEventAdmin(ClassificationAdmin):
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
fields = ClassificationAdmin.fields + ("approved_at",)
readonly_fields = ClassificationAdmin.readonly_fields + ("submitted_at", "approved_at")
fields = ClassificationAdmin.fields + ("submitted_at", "approved_at")
def has_add_permission(self, request):
return False
@admin.register(ManualReportRevision)
class ManualReportRevisionAdmin(admin.ModelAdmin):
list_display = ("original_pending_id", "previous_occurrences", "new_occurrences", "previous_duration_minutes", "new_duration_minutes", "changed_at")
readonly_fields = list_display
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(Sensor)
class SensorAdmin(admin.ModelAdmin):
list_display = ("name", "owner", "is_active", "heartbeat_light", "last_heartbeat", "last_submission", "token_prefix", "archived_at")
@@ -175,3 +219,47 @@ class SensorAdmin(admin.ModelAdmin):
sensor = queryset.get()
token = sensor.issue_token()
self.message_user(request, format_html(_("Copy this token now; it is not stored and will not be shown again: <code>{}</code>"), token), messages.WARNING)
from .models import FieldNote, FieldNoteAssociation
@admin.register(FieldNote)
class FieldNoteAdmin(admin.ModelAdmin):
list_display = ("id", "author", "category", "source_type", "verification_status", "visibility", "created_at")
list_filter = ("visibility", "category", "source_type", "verification_status")
readonly_fields = tuple(f.name for f in FieldNote._meta.fields)
search_fields = ("content",)
def get_queryset(self, request):
return super().get_queryset(request).visible_to(request.user).select_related("author", "context")
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(FieldNoteAssociation)
class FieldNoteAssociationAdmin(admin.ModelAdmin):
list_display = ("context", "actor", "reason", "created_at")
readonly_fields = tuple(f.name for f in FieldNoteAssociation._meta.fields)
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.has_perm("fireworks_detect.view_all_fieldnotes"):
return qs
return qs.filter(context__author=request.user)
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
+25
View File
@@ -0,0 +1,25 @@
"""Derived burst presentation rules; rates describe frequency, not loudness."""
from decimal import Decimal
BURST_MIN_BANGS = 3
DEFAULT_ESTIMATED_DURATION_MINUTES = 15
MODERATE_RATE_PER_15_MINUTES = Decimal("5")
INTENSE_RATE_PER_15_MINUTES = Decimal("10")
def burst_rate(bang_count, duration_minutes):
if bang_count < BURST_MIN_BANGS or not duration_minutes or duration_minutes <= 0:
return None
return Decimal(bang_count) * 15 / Decimal(duration_minutes)
def burst_intensity(bang_count, duration_minutes):
rate = burst_rate(bang_count, duration_minutes)
if rate is None:
return None
if rate >= INTENSE_RATE_PER_15_MINUTES:
return "intense"
if rate >= MODERATE_RATE_PER_15_MINUTES:
return "moderate"
return "light"
+100
View File
@@ -0,0 +1,100 @@
"""Central access checks and association/reporting services for field notes."""
import uuid
from django.contrib.auth import get_user_model
from django.core import signing
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.db.models import Q
from django.http import Http404
from .models import Event, PendingEvent, FieldNote, FieldNoteContext, FieldNoteAssociation
def draft_token(user):
if not user.is_authenticated:
return ""
return signing.dumps({"author": user.pk, "id": str(uuid.uuid4())}, salt="field-notes")
def token_id(user, token):
try:
data = signing.loads(token, salt="field-notes", max_age=7 * 86400)
if data["author"] != user.pk:
raise ValueError
return uuid.UUID(data["id"])
except (signing.BadSignature, ValueError, KeyError, TypeError):
raise PermissionDenied("Invalid or expired note context. Reload the reporting page.")
def accessible_pending(user, session_ids=()):
if not user.is_authenticated:
return PendingEvent.objects.none()
if user.is_staff and user.has_perm("fireworks_detect.view_pendingevent"):
return PendingEvent.objects.all()
return PendingEvent.objects.filter(Q(note_contexts__author=user) | Q(sensor__owner=user) | Q(pk__in=session_ids)).distinct()
def target_snapshot(context):
if context.event_id:
return {"kind": "event", "id": context.event_id}
if context.pending_event_id:
return {"kind": "pending", "id": context.pending_event_id}
return {}
def associate(context, *, event=None, pending=None, actor=None, reason):
previous = target_snapshot(context)
context.event = event
context.pending_event = pending
context.full_clean()
context.save(update_fields=["event", "pending_event"])
FieldNoteAssociation.objects.create(context=context, actor=actor, previous=previous,
target=target_snapshot(context), reason=reason)
@transaction.atomic
def context_for_token(user, token):
# Serialize draft-note creation and report binding for the same author.
get_user_model().objects.select_for_update().get(pk=user.pk)
context, _ = FieldNoteContext.objects.get_or_create(id=token_id(user, token), defaults={"author": user})
if context.author_id != user.pk:
raise PermissionDenied
return context
@transaction.atomic
def bind_report(user, token, pending):
if not user.is_authenticated or not token:
return
context = context_for_token(user, token)
if context.event_id or context.pending_event_id:
raise PermissionDenied("This note context already belongs to a report. Reload before reporting again.")
associate(context, pending=pending, actor=user, reason="submission")
@transaction.atomic
def link_standalone(user, context_id, event):
# Approved events are publicly accessible in the existing application.
context = FieldNoteContext.objects.select_for_update().filter(pk=context_id, author=user).first()
if not context or context.event_id or context.pending_event_id:
raise Http404
associate(context, event=event, actor=user, reason="linked")
return context
@transaction.atomic
def regroup_event_notes(user, source, target):
"""Hook for future event-merging code; does not modify detection records."""
if not (user.is_staff and user.has_perm("fireworks_detect.change_event") and
user.has_perm("fireworks_detect.view_all_fieldnotes")):
raise PermissionDenied
if source.pk == target.pk:
return
for context in FieldNoteContext.objects.select_for_update().filter(event=source):
associate(context, event=target, actor=user, reason="regrouped")
def reportable_notes(user):
"""All exports, including future PDF reports, must start with this queryset."""
return FieldNote.objects.reportable_to(user).select_related("author", "context")
+33
View File
@@ -0,0 +1,33 @@
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import FieldNote
class FieldNoteForm(forms.ModelForm):
class Meta:
model = FieldNote
fields = ["content", "category", "source_type", "verification_status", "visibility", "observed_at"]
widgets = {
"content": forms.Textarea(attrs={"rows": 3, "placeholder": _("What did you observe or learn?")}),
"observed_at": forms.DateTimeInput(format="%Y-%m-%dT%H:%M", attrs={"type": "datetime-local"}),
}
labels = {"content": _("Note"), "observed_at": _("Observed at (optional)"),
"category": _("Category"), "source_type": _("Source"),
"verification_status": _("Verification status"), "visibility": _("Visibility")}
help_texts = {
"visibility": _("Private by default. Reportable permits authorised export; it does not mean verified or public."),
"observed_at": _("Local time (Europe/Amsterdam). The entry time is recorded separately."),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name in self.fields:
if name != "content":
self.fields[name].required = False
def clean(self):
data = super().clean()
for name in ("category", "source_type", "verification_status", "visibility"):
if not data.get(name):
data[name] = FieldNote._meta.get_field(name).get_default()
return data
@@ -0,0 +1,25 @@
"""Issue a separate, revocable read-only MCP credential."""
import hashlib
import secrets
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from fireworks_detect.models import McpAccessToken
class Command(BaseCommand):
help = "Issue a BoomCast MCP token for an existing user with both review view permissions."
def add_arguments(self, parser):
parser.add_argument("username")
parser.add_argument("--name", default="MCP client")
def handle(self, *args, **options):
user = get_user_model().objects.filter(username=options["username"], is_active=True).first()
if user is None or not (user.has_perm("fireworks_detect.view_event") and user.has_perm("fireworks_detect.view_pendingevent")):
raise CommandError("Active user with view_event and view_pendingevent permissions required")
token = "bmcp_" + secrets.token_urlsafe(36)
McpAccessToken.objects.create(user=user, name=options["name"], token_hash=hashlib.sha256(token.encode()).hexdigest())
self.stdout.write("Store this token securely; it is shown only once:")
self.stdout.write(token)
@@ -0,0 +1,40 @@
import time
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from fireworks_detect.models import BurstSession
class Command(BaseCommand):
help = "Check every active Burst Listening session independently for lost HTTP heartbeats."
def add_arguments(self, parser):
parser.add_argument("--once", action="store_true")
parser.add_argument("--interval", type=float, default=5)
def handle(self, *args, **options):
while True:
now = timezone.now()
BurstSession.objects.filter(ended_at__lt=now - timedelta(days=7)).exclude(diagnostic_events=[]).update(diagnostic_events=[])
for session in BurstSession.objects.filter(ended_at__isnull=True).exclude(status="expired").iterator():
if now > session.started_at + timedelta(minutes=21):
session.status = "expired"
session.ended_at = now
kind = "watchdog_expired"
elif now > (session.last_seen_at or session.started_at) + timedelta(seconds=15) and session.timeout_at is None:
session.status = "heartbeat_lost"
session.timeout_at = now
kind = "heartbeat_lost"
else:
continue
events = session.diagnostic_events
if len(events) >= 200:
events = events[:20] + events[-179:]
events.append({"kind": kind, "server_at": now.isoformat(), "last_seen_at": session.last_seen_at.isoformat() if session.last_seen_at else None})
session.diagnostic_events = events
session.save(update_fields=["status", "ended_at", "timeout_at", "diagnostic_events"])
if options["once"]:
break
time.sleep(max(1, options["interval"]))
+225
View File
@@ -0,0 +1,225 @@
"""Stateless, read-only MCP endpoint for reviewed BoomCast metadata."""
import hashlib
import json
from datetime import timedelta
from urllib.parse import urlsplit
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.db.models import Count
from django.db.models.functions import TruncDate
from django.http import JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date
from django.views.decorators.csrf import csrf_exempt
from .h3_utils import cell_from_coordinates
from .models import Event, PendingEvent
PROTOCOL_VERSION = "2025-06-18"
TOOLS = [
{"name": "submissions_list", "description": "Page through reviewed submissions only. Review outcome is approved; denied records are deleted by the review workflow.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}, "limit": {"type": "integer", "minimum": 1, "maximum": 100}, "offset": {"type": "integer", "minimum": 0, "maximum": 10000}}, "additionalProperties": False}},
{"name": "submissions_get", "description": "Get one reviewed submission by Event ID; pending IDs are inaccessible.", "inputSchema": {"type": "object", "properties": {"id": {"type": "integer", "minimum": 1}}, "required": ["id"], "additionalProperties": False}},
{"name": "submissions_stats", "description": "Reviewed submission counts by day, predicted class, and confirmed review outcome.", "inputSchema": {"type": "object", "properties": {"date_from": {"type": "string", "format": "date"}, "date_to": {"type": "string", "format": "date"}, "classification": {"type": "string"}, "review_outcome": {"type": "string", "enum": ["approved"]}}, "additionalProperties": False}},
{"name": "pending_summary", "description": "Only aggregate count and counts by predicted class for pending review; no individual records.", "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
]
def _error(code, message, request_id=None):
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
def _reply(request_id, result):
return {"jsonrpc": "2.0", "id": request_id, "result": result}
def _prediction(record):
payload = record.classifier_response if isinstance(record.classifier_response, dict) else {}
predictions = payload.get("predictions", [])
if not isinstance(predictions, list):
return []
clean = []
for item in predictions[:10]:
if not isinstance(item, dict):
continue
label, score = item.get("class"), item.get("score")
if isinstance(label, str) and len(label) <= 255 and isinstance(score, (int, float)) and not isinstance(score, bool) and 0 <= score <= 1:
clean.append({"class": label, "score": score})
return clean
def _label(record):
prediction = _prediction(record)
return prediction[0]["class"] if prediction else "unclassified"
def _summary(event):
return {"id": event.pk, "occurrence_at": event.captured_at.isoformat() if event.captured_at else None,
"submitted_at": event.submitted_at.isoformat() if event.submitted_at else None,
"reviewed_at": event.approved_at.isoformat(), "source_type": event.source_type,
"predicted_classification": _label(event), "review_outcome": "approved",
"confirmed_classification": None}
def _detail(event):
result = _summary(event)
result.update({"predictions": _prediction(event), "occurrences": event.occurrences,
"occurrence_time_approximate": event.occurrence_time_approximate,
"generalized_location_h3": event.h3_cell or cell_from_coordinates(event.latitude, event.longitude) or None})
return result
def _filters(args):
start, end = args.get("date_from"), args.get("date_to")
if start is not None:
if not isinstance(start, str) or not parse_date(start) or parse_date(start).isoformat() != start:
raise ValueError("date_from must be YYYY-MM-DD")
start = parse_date(start)
if end is not None:
if not isinstance(end, str) or not parse_date(end) or parse_date(end).isoformat() != end:
raise ValueError("date_to must be YYYY-MM-DD")
end = parse_date(end)
if start and end and (end < start or end - start > timedelta(days=366)):
raise ValueError("date range must be ordered and at most 366 days")
if not end:
end = min(timezone.localdate(), start + timedelta(days=366)) if start else timezone.localdate()
if not start:
start = end - timedelta(days=366)
outcome = args.get("review_outcome")
if outcome is not None and outcome != "approved":
raise ValueError("review_outcome must be approved")
classification = args.get("classification")
if classification is not None and (not isinstance(classification, str) or not 1 <= len(classification) <= 255):
raise ValueError("classification must be a nonempty label")
queryset = Event.objects.all()
if start:
queryset = queryset.filter(approved_at__date__gte=start)
if end:
queryset = queryset.filter(approved_at__date__lte=end)
if classification:
queryset = queryset.filter(classifier_response__predictions__0__class=classification)
return queryset
def _validate(name, args):
schema = next((item["inputSchema"] for item in TOOLS if item["name"] == name), None)
if schema is None:
raise ValueError("Unknown tool")
if not isinstance(args, dict) or set(args) - set(schema["properties"]) or set(schema.get("required", [])) - set(args):
raise ValueError("Invalid tool arguments")
for key in ("limit", "offset", "id"):
if key in args and (type(args[key]) is not int or args[key] < (1 if key != "offset" else 0) or args[key] > (100 if key == "limit" else 10000 if key == "offset" else 2147483647)):
raise ValueError(f"Invalid {key}")
def _call(name, args):
_validate(name, args)
if name == "pending_summary":
counts = {}
for pending in PendingEvent.objects.only("classifier_response").iterator(chunk_size=500):
label = _label(pending)
counts[label] = counts.get(label, 0) + 1
return {"total": sum(counts.values()), "by_predicted_classification": counts}
if name == "submissions_get":
event = Event.objects.filter(pk=args["id"]).first()
if event is None:
raise LookupError("Reviewed submission not found")
return _detail(event)
queryset = _filters(args)
if name == "submissions_list":
limit, offset = args.get("limit", 25), args.get("offset", 0)
return {"total": queryset.count(), "limit": limit, "offset": offset,
"items": [_summary(item) for item in queryset.order_by("-approved_at", "-pk")[offset:offset + limit]]}
if name == "submissions_stats":
days = list(queryset.annotate(day=TruncDate("approved_at")).values("day").annotate(count=Count("pk")).order_by("day")[:367])
classes = {}
for event in queryset.only("classifier_response").iterator(chunk_size=500):
label = _label(event)
classes[label] = classes.get(label, 0) + 1
return {"total": sum(classes.values()), "by_day": [{"date": row["day"].isoformat(), "count": row["count"]} for row in days],
"by_predicted_classification": classes, "by_review_outcome": {"approved": sum(classes.values())},
"confirmed_classification_available": False}
raise ValueError("Unknown tool")
def _principal(request):
header = request.headers.get("Authorization", "")
if not header.startswith("Bearer "):
return None
token = header[7:].strip()
if not token.startswith("bmcp_") or len(token) > 120:
return None
from .models import McpAccessToken
digest = hashlib.sha256(token.encode()).hexdigest()
credential = McpAccessToken.objects.select_related("user").filter(token_hash=digest, revoked_at__isnull=True).first()
if not credential or not credential.user.is_active:
return None
return credential.user
@csrf_exempt
def mcp_endpoint(request):
if request.method != "POST":
response = JsonResponse({"detail": "POST only"}, status=405)
response["Allow"] = "POST"
return response
origin = request.headers.get("Origin")
if origin:
parsed = urlsplit(origin)
if parsed.scheme not in ("http", "https") or parsed.netloc != request.get_host():
return JsonResponse({"detail": "Origin not allowed"}, status=403)
user = _principal(request)
if user is None:
response = JsonResponse({"detail": "MCP Bearer token required"}, status=401)
response["WWW-Authenticate"] = 'Bearer realm="BoomCast MCP"'
return response
if not user.has_perm("fireworks_detect.view_event") or not user.has_perm("fireworks_detect.view_pendingevent"):
return JsonResponse({"detail": "Review read permissions required"}, status=403)
key = f"boomcast-mcp:{user.pk}"
if not cache.add(key, 1, 60):
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, 60)
count = 1
if count > 120:
response = JsonResponse({"detail": "Rate limit exceeded"}, status=429)
response["Retry-After"] = "60"
return response
if (request.META.get("CONTENT_LENGTH") or "").isdigit() and int(request.META["CONTENT_LENGTH"]) > 65536:
return JsonResponse(_error(-32600, "Request too large"), status=413)
if len(request.body) > 65536:
return JsonResponse(_error(-32600, "Request too large"), status=413)
try:
message = json.loads(request.body)
except (ValueError, UnicodeDecodeError):
return JsonResponse(_error(-32700, "Invalid JSON"), status=400)
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
return JsonResponse(_error(-32600, "Invalid request"), status=400)
request_id, method = message.get("id"), message["method"]
if method == "notifications/initialized" and "id" not in message:
from django.http import HttpResponse
return HttpResponse(status=202)
if "id" not in message or not (isinstance(request_id, (str, int)) and not isinstance(request_id, bool)):
return JsonResponse(_error(-32600, "Request ID required"), status=400)
if method == "initialize":
result = {"protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}}, "serverInfo": {"name": "boomcast-readonly", "version": "1.0.0"}}
elif method == "tools/list":
result = {"tools": TOOLS}
elif method == "tools/call":
params = message.get("params")
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
return JsonResponse(_error(-32602, "Invalid tool call", request_id))
try:
output = _call(params["name"], params.get("arguments", {}))
except ValueError as error:
result = {"content": [{"type": "text", "text": str(error)}], "isError": True}
except LookupError:
result = {"content": [{"type": "text", "text": "Reviewed submission not found"}], "isError": True}
else:
result = {"content": [{"type": "text", "text": json.dumps(output, ensure_ascii=False)}], "structuredContent": output}
else:
return JsonResponse(_error(-32601, "Method not found", request_id))
response = JsonResponse(_reply(request_id, result))
response["Cache-Control"] = "no-store"
return response
@@ -0,0 +1,60 @@
# Generated by Django 6.1.1 on 2026-10-09 13:05
import django.db.models.deletion
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0010_create_browser_processing_settings'),
]
operations = [
migrations.AddField(
model_name='event',
name='captured_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='device_metadata',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='event',
name='firmware_version',
field=models.CharField(blank=True, max_length=64),
),
migrations.AddField(
model_name='pendingevent',
name='captured_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='device_metadata',
field=models.JSONField(blank=True, default=dict),
),
migrations.AddField(
model_name='pendingevent',
name='firmware_version',
field=models.CharField(blank=True, max_length=64),
),
migrations.CreateModel(
name='SensorSubmission',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('event_id', models.CharField(max_length=100)),
('audio_sha256', models.CharField(max_length=64)),
('submission_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
('sensor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submissions', to='fireworks_detect.sensor')),
],
options={
'constraints': [models.UniqueConstraint(fields=('sensor', 'event_id'), name='unique_sensor_event_id')],
},
),
]
@@ -0,0 +1,57 @@
# Generated by Django 6.1.1 on 2026-10-09 23:43
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0011_event_captured_at_event_device_metadata_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='event',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_kind',
field=models.CharField(blank=True, choices=[('estimated', 'Estimated'), ('measured', 'Measured')], max_length=10),
),
migrations.AddField(
model_name='pendingevent',
name='observation_duration_minutes',
field=models.PositiveSmallIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='occurrence_time_approximate',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='ManualReportRevision',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('original_pending_id', models.PositiveBigIntegerField()),
('previous_occurrences', models.PositiveIntegerField()),
('new_occurrences', models.PositiveIntegerField()),
('previous_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('new_duration_minutes', models.PositiveSmallIntegerField(blank=True, null=True)),
('changed_at', models.DateTimeField(auto_now_add=True)),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='fireworks_detect.pendingevent')),
],
),
]
@@ -0,0 +1,18 @@
# Generated by Django 6.1.1 on 2026-10-09 23:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0012_event_observation_duration_kind_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='submitted_at',
field=models.DateTimeField(blank=True, null=True),
),
]
@@ -0,0 +1,86 @@
# Generated by Django 6.1.1 on 2026-10-13 07:57
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0013_event_submitted_at'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FieldNoteContext',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
('event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='note_contexts', to='fireworks_detect.event')),
('pending_event', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='note_contexts', to='fireworks_detect.pendingevent')),
],
),
migrations.CreateModel(
name='FieldNoteAssociation',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('previous', models.JSONField(default=dict)),
('target', models.JSONField(default=dict)),
('reason', models.CharField(max_length=32)),
('created_at', models.DateTimeField(auto_now_add=True)),
('actor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('context', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='associations', to='fireworks_detect.fieldnotecontext')),
],
options={
'ordering': ['created_at', 'pk'],
},
),
migrations.CreateModel(
name='FieldNote',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField(max_length=10000)),
('category', models.CharField(choices=[('general', 'General'), ('witness', 'Witness'), ('people_vehicles', 'People / vehicles'), ('cctv', 'CCTV'), ('location_direction', 'Location / direction'), ('follow_up', 'Follow-up'), ('other', 'Other')], default='general', max_length=32)),
('source_type', models.CharField(choices=[('first_hand', 'First-hand'), ('second_hand', 'Second-hand'), ('unknown', 'Other / unknown')], default='unknown', max_length=24)),
('verification_status', models.CharField(choices=[('unverified', 'Unverified'), ('corroborated', 'Corroborated'), ('disputed', 'Disputed')], default='unverified', max_length=24)),
('visibility', models.CharField(choices=[('private', 'Private'), ('reportable', 'Reportable')], default='private', max_length=16)),
('observed_at', models.DateTimeField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='field_notes', to=settings.AUTH_USER_MODEL)),
('context', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='notes', to='fireworks_detect.fieldnotecontext')),
],
options={
'ordering': ['created_at', 'pk'],
'permissions': [('view_all_fieldnotes', 'Read all private field notes'), ('export_reportable_fieldnotes', 'Export reportable field notes from all authors')],
},
),
migrations.AddConstraint(
model_name='fieldnotecontext',
constraint=models.CheckConstraint(condition=models.Q(('event__isnull', False), ('pending_event__isnull', False), _negated=True), name='note_context_one_target'),
),
migrations.AddIndex(
model_name='fieldnote',
index=models.Index(fields=['author', 'created_at'], name='fieldnote_author_time'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('content', ''), _negated=True), name='fieldnote_nonempty'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('visibility__in', ['private', 'reportable'])), name='fieldnote_visibility'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('source_type__in', ['first_hand', 'second_hand', 'unknown'])), name='fieldnote_source'),
),
migrations.AddConstraint(
model_name='fieldnote',
constraint=models.CheckConstraint(condition=models.Q(('verification_status__in', ['unverified', 'corroborated', 'disputed'])), name='fieldnote_verification'),
),
]
@@ -0,0 +1,51 @@
# Generated by Django 6.1.1 on 2026-10-15 10:53
import django.db.models.deletion
import django.utils.timezone
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0014_fieldnotecontext_fieldnoteassociation_fieldnote_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BurstSession',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('started_at', models.DateTimeField(default=django.utils.timezone.now)),
('ended_at', models.DateTimeField(blank=True, null=True)),
('maximum_minutes', models.PositiveSmallIntegerField(default=15)),
('status', models.CharField(default='listening', max_length=24)),
('last_seen_at', models.DateTimeField(blank=True, null=True)),
('last_audio_at', models.DateTimeField(blank=True, null=True)),
('last_audio_frame', models.PositiveBigIntegerField(default=0)),
('last_sequence', models.PositiveIntegerField(default=0)),
('timeout_at', models.DateTimeField(blank=True, null=True)),
('diagnostic_events', models.JSONField(default=list)),
('event', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='burst_session', to='fireworks_detect.event')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='burst_sessions', to=settings.AUTH_USER_MODEL)),
('pending_event', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='burst_session', to='fireworks_detect.pendingevent')),
],
),
migrations.CreateModel(
name='BurstCapture',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('captured_at', models.DateTimeField()),
('duration_seconds', models.FloatField()),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('is_primary', models.BooleanField(default=False)),
('session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='captures', to='fireworks_detect.burstsession')),
],
options={
'ordering': ['captured_at', 'pk'],
},
),
]
@@ -0,0 +1,27 @@
# Generated by Django 6.1.1 on 2026-10-16 15:29
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0015_burstsession_burstcapture'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='McpAccessToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('token_hash', models.CharField(max_length=64, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('revoked_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='boomcast_mcp_tokens', to=settings.AUTH_USER_MODEL)),
],
),
]
+245 -1
View File
@@ -1,5 +1,6 @@
import math
import secrets
import uuid
from django.conf import settings
from django.contrib.auth.hashers import check_password, make_password
@@ -116,12 +117,19 @@ class ClassifiedAudio(models.Model):
SENSOR = "sensor", _("Sensor")
MANUAL = "manual", _("Manual report")
class DurationKind(models.TextChoices):
ESTIMATED = "estimated", _("Estimated")
MEASURED = "measured", _("Measured")
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)
observation_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
observation_duration_kind = models.CharField(max_length=10, choices=DurationKind.choices, blank=True)
occurrence_time_approximate = models.BooleanField(default=False)
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)
@@ -131,6 +139,9 @@ class ClassifiedAudio(models.Model):
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)
captured_at = models.DateTimeField(null=True, blank=True)
firmware_version = models.CharField(max_length=64, blank=True)
device_metadata = models.JSONField(default=dict, blank=True)
class Meta:
abstract = True
@@ -150,6 +161,10 @@ class ClassifiedAudio(models.Model):
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 self.observation_duration_minutes is not None and not 1 <= self.observation_duration_minutes <= 1440:
errors["observation_duration_minutes"] = _("Observation duration must be between 1 and 1,440 minutes.")
if bool(self.observation_duration_minutes) != bool(self.observation_duration_kind):
errors["observation_duration_kind"] = _("A duration needs an estimated or measured source.")
if errors:
raise ValidationError(errors)
@@ -168,6 +183,33 @@ class ClassifiedAudio(models.Model):
return "—"
return f"{self.direction_degrees:g}° ({self.direction_cardinal})"
@property
def is_burst(self):
from .bursts import BURST_MIN_BANGS
return self.occurrences >= BURST_MIN_BANGS
@property
def event_kind(self):
return "burst" if self.is_burst else "ordinary"
@property
def bangs_per_15_minutes(self):
from .bursts import burst_rate
if not self.observation_duration_kind:
return None
return burst_rate(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity(self):
from .bursts import burst_intensity
if not self.observation_duration_kind:
return None
return burst_intensity(self.occurrences, self.observation_duration_minutes)
@property
def burst_intensity_display(self):
return {"light": _("Light"), "moderate": _("Moderate"), "intense": _("Intense")}.get(self.burst_intensity)
@property
def predictions(self):
@@ -223,14 +265,21 @@ class PendingEvent(ClassifiedAudio):
verbose_name_plural = _("Pending")
@transaction.atomic
def approve(self):
def approve(self, actor=None):
event = Event.objects.create(
submitted_at=self.created_at,
audio_file=self.audio_file.name,
sensor=self.sensor,
captured_at=self.captured_at,
firmware_version=self.firmware_version,
device_metadata=self.device_metadata,
original_filename=self.original_filename,
classifier_response=self.classifier_response,
source_type=self.source_type,
occurrences=self.occurrences,
observation_duration_minutes=self.observation_duration_minutes,
observation_duration_kind=self.observation_duration_kind,
occurrence_time_approximate=self.occurrence_time_approximate,
location=self.location,
latitude=self.latitude,
longitude=self.longitude,
@@ -240,11 +289,24 @@ class PendingEvent(ClassifiedAudio):
direction_accuracy_degrees=self.direction_accuracy_degrees,
direction_source=self.direction_source,
)
from .field_notes import associate
if hasattr(self, "burst_session"):
session = self.burst_session
session.pending_event = None
session.event = event
session.save(update_fields=["pending_event", "event"])
for context in self.note_contexts.select_for_update():
associate(context, event=event, actor=actor, reason="approved")
self.delete()
return event
def deny(self):
file_name = self.audio_file.name
if hasattr(self, "burst_session"):
for capture in self.burst_session.captures.all():
if capture.audio_file.name and capture.audio_file.name != file_name:
default_storage.delete(capture.audio_file.name)
self.burst_session.captures.all().delete()
self.delete()
if file_name:
default_storage.delete(file_name)
@@ -254,7 +316,189 @@ class Event(ClassifiedAudio):
"""A reviewed classification that is safe to appear in the event feed."""
approved_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
class Meta(ClassifiedAudio.Meta):
verbose_name = _("Event")
verbose_name_plural = _("Events")
class BurstSession(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="burst_sessions")
pending_event = models.OneToOneField(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL, related_name="burst_session")
event = models.OneToOneField(Event, null=True, blank=True, on_delete=models.SET_NULL, related_name="burst_session")
started_at = models.DateTimeField(default=timezone.now)
ended_at = models.DateTimeField(null=True, blank=True)
maximum_minutes = models.PositiveSmallIntegerField(default=15)
status = models.CharField(max_length=24, default="listening")
last_seen_at = models.DateTimeField(null=True, blank=True)
last_audio_at = models.DateTimeField(null=True, blank=True)
last_audio_frame = models.PositiveBigIntegerField(default=0)
last_sequence = models.PositiveIntegerField(default=0)
timeout_at = models.DateTimeField(null=True, blank=True)
diagnostic_events = models.JSONField(default=list)
class BurstCapture(models.Model):
session = models.ForeignKey(BurstSession, on_delete=models.CASCADE, related_name="captures")
captured_at = models.DateTimeField()
duration_seconds = models.FloatField()
audio_file = models.FileField(upload_to="fireworks_audio/%Y/%m/%d")
is_primary = models.BooleanField(default=False)
class Meta:
ordering = ["captured_at", "pk"]
class ManualReportRevision(models.Model):
"""Record edits to a session-owned manual Pending report."""
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
original_pending_id = models.PositiveBigIntegerField()
previous_occurrences = models.PositiveIntegerField()
new_occurrences = models.PositiveIntegerField()
previous_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
new_duration_minutes = models.PositiveSmallIntegerField(null=True, blank=True)
changed_at = models.DateTimeField(auto_now_add=True)
class SensorSubmission(models.Model):
"""Durable idempotency receipt, retained after moderation."""
sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE, related_name="submissions")
event_id = models.CharField(max_length=100)
audio_sha256 = models.CharField(max_length=64)
submission_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=["sensor", "event_id"], name="unique_sensor_event_id")]
class FieldNoteContext(models.Model):
"""An author's note association, including drafts before a report exists.
This stores no detection/incident data; Event/PendingEvent remain canonical.
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
event = models.ForeignKey(Event, null=True, blank=True, on_delete=models.SET_NULL, related_name="note_contexts")
pending_event = models.ForeignKey(PendingEvent, null=True, blank=True, on_delete=models.SET_NULL, related_name="note_contexts")
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.CheckConstraint(condition=~(models.Q(event__isnull=False) & models.Q(pending_event__isnull=False)), name="note_context_one_target")]
class FieldNoteQuerySet(models.QuerySet):
def visible_to(self, user):
if not user.is_authenticated or not user.is_active:
return self.none()
if user.is_active and user.has_perm("fireworks_detect.view_all_fieldnotes"):
return self
return self.filter(author=user)
def reportable_to(self, user):
if not user.is_authenticated or not user.is_active:
return self.none()
notes = self.filter(visibility="reportable")
if user.is_active and user.has_perm("fireworks_detect.export_reportable_fieldnotes"):
return notes
return notes.filter(author=user)
class FieldNote(models.Model):
class Category(models.TextChoices):
GENERAL = "general", _("General")
WITNESS = "witness", _("Witness")
PEOPLE = "people_vehicles", _("People / vehicles")
CCTV = "cctv", _("CCTV")
LOCATION = "location_direction", _("Location / direction")
FOLLOW_UP = "follow_up", _("Follow-up")
OTHER = "other", _("Other")
class Source(models.TextChoices):
FIRST_HAND = "first_hand", _("First-hand")
SECOND_HAND = "second_hand", _("Second-hand")
UNKNOWN = "unknown", _("Other / unknown")
class Verification(models.TextChoices):
UNVERIFIED = "unverified", _("Unverified")
CORROBORATED = "corroborated", _("Corroborated")
DISPUTED = "disputed", _("Disputed")
class Visibility(models.TextChoices):
PRIVATE = "private", _("Private")
REPORTABLE = "reportable", _("Reportable")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="field_notes")
context = models.ForeignKey(FieldNoteContext, on_delete=models.PROTECT, related_name="notes")
content = models.TextField(max_length=10000)
category = models.CharField(max_length=32, choices=Category.choices, default=Category.GENERAL)
source_type = models.CharField(max_length=24, choices=Source.choices, default=Source.UNKNOWN)
verification_status = models.CharField(max_length=24, choices=Verification.choices, default=Verification.UNVERIFIED)
visibility = models.CharField(max_length=16, choices=Visibility.choices, default=Visibility.PRIVATE)
observed_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = FieldNoteQuerySet.as_manager()
class Meta:
ordering = ["created_at", "pk"]
indexes = [models.Index(fields=["author", "created_at"], name="fieldnote_author_time")]
permissions = [
("view_all_fieldnotes", "Read all private field notes"),
("export_reportable_fieldnotes", "Export reportable field notes from all authors"),
]
constraints = [
models.CheckConstraint(condition=~models.Q(content=""), name="fieldnote_nonempty"),
models.CheckConstraint(condition=models.Q(visibility__in=["private", "reportable"]), name="fieldnote_visibility"),
models.CheckConstraint(condition=models.Q(source_type__in=["first_hand", "second_hand", "unknown"]), name="fieldnote_source"),
models.CheckConstraint(condition=models.Q(verification_status__in=["unverified", "corroborated", "disputed"]), name="fieldnote_verification"),
]
def clean(self):
super().clean()
if not self.content.strip():
raise ValidationError({"content": _("Enter a note.")})
if self.context_id and self.author_id != self.context.author_id:
raise ValidationError(_("The note and its context must have the same author."))
def save(self, *args, **kwargs):
if not self._state.adding:
raise ValidationError(_("Field notes are append-only. Add a follow-up to correct an earlier note."))
self.full_clean()
return super().save(*args, **kwargs)
class FieldNoteAssociation(models.Model):
"""Immutable provenance retained even when the original event is deleted."""
context = models.ForeignKey(FieldNoteContext, on_delete=models.PROTECT, related_name="associations")
actor = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)
previous = models.JSONField(default=dict)
target = models.JSONField(default=dict)
reason = models.CharField(max_length=32)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["created_at", "pk"]
def save(self, *args, **kwargs):
if not self._state.adding:
raise ValidationError("Association history is append-only.")
return super().save(*args, **kwargs)
class McpAccessToken(models.Model):
"""Revocable credential for read-only MCP access; never stores the raw token."""
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="boomcast_mcp_tokens")
name = models.CharField(max_length=100)
token_hash = models.CharField(max_length=64, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
revoked_at = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"{self.user}: {self.name}"
+126
View File
@@ -0,0 +1,126 @@
import csv
import json
from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from .field_notes import accessible_pending, associate, context_for_token, link_standalone, reportable_notes, token_id
from .forms import FieldNoteForm
from .models import Event, FieldNote, FieldNoteContext
def panel_context(request, params=None):
params = params if params is not None else request.GET
selected = [(k, params.get(k)) for k in ("event", "pending", "token") if params.get(k)]
if len(selected) > 1:
raise Http404
notes = FieldNote.objects.visible_to(request.user).select_related("author", "context__event", "context__pending_event").prefetch_related("context__associations")
target = None
kind, value = selected[0] if selected else ("", "")
try:
if kind == "event":
target = get_object_or_404(Event, pk=int(value))
notes = notes.filter(context__event=target)
elif kind == "pending":
target = get_object_or_404(accessible_pending(request.user, request.session.get("manual_pending_ids", [])), pk=int(value))
notes = notes.filter(context__pending_event=target)
elif kind == "token":
key = token_id(request.user, value)
notes = notes.filter(context_id=key)
except (ValueError, TypeError):
raise Http404
return {"field_notes": notes, "note_count": notes.count(), "note_form": FieldNoteForm(),
"note_kind": kind, "note_value": value, "note_target": target,
"note_panel_id": "live-field-notes" if kind == "token" else "field-notes",
"note_query": urlencode({kind: value}) if kind else "",
"note_events": Event.objects.all() if not kind else (),
"note_token": value if kind == "token" else ""}
@login_required
@never_cache
@require_http_methods(["GET", "POST"])
def notes(request):
params = request.POST if request.method == "POST" else request.GET
context = panel_context(request, params)
if request.method == "POST":
form = FieldNoteForm(request.POST)
if form.is_valid():
with transaction.atomic():
kind = context["note_kind"]
if kind == "token":
owner_context = context_for_token(request.user, context["note_value"])
else:
owner_context = FieldNoteContext.objects.create(author=request.user)
if kind:
associate(owner_context, event=context["note_target"] if kind == "event" else None,
pending=context["note_target"] if kind == "pending" else None,
actor=request.user, reason="created")
note = form.save(commit=False)
note.author = request.user
note.context = owner_context
note.save()
if request.headers.get("HX-Request") != "true":
return redirect(reverse("fireworks_detect:field_notes") + ("?" + context["note_query"] if context["note_query"] else ""))
context = panel_context(request, params)
context["note_saved"] = True
else:
context["note_form"] = form
# Invalid HTMX forms deliberately return 200 so HTMX renders field errors.
template = "fireworks_detect/notes/panel.html" if request.headers.get("HX-Request") == "true" else "fireworks_detect/notes/page.html"
return render(request, template, context)
@login_required
@never_cache
@require_http_methods(["POST"])
def link_note(request, context_id):
try:
event = get_object_or_404(Event, pk=int(request.POST.get("event", "")))
except (ValueError, TypeError):
raise Http404
link_standalone(request.user, context_id, event)
return redirect("fireworks_detect:field_notes")
@login_required
@never_cache
@require_http_methods(["GET"])
def export_notes(request, format):
notes = reportable_notes(request.user).prefetch_related("context__associations")
if request.GET.get("event"):
try:
event = get_object_or_404(Event, pk=int(request.GET["event"]))
except (ValueError, TypeError):
raise Http404
notes = notes.filter(context__event=event)
rows = [{"id": n.pk, "author": n.author.get_username(), "event_id": n.context.event_id,
"pending_event_id": n.context.pending_event_id, "content": n.content,
"category": n.category, "source_type": n.source_type,
"verification_status": n.verification_status, "visibility": n.visibility,
"observed_at": n.observed_at.isoformat() if n.observed_at else None,
"created_at": n.created_at.isoformat(), "updated_at": n.updated_at.isoformat(),
"association_history": [{"previous": a.previous, "target": a.target, "reason": a.reason,
"created_at": a.created_at.isoformat()} for a in n.context.associations.all()]}
for n in notes]
if format == "json":
response = JsonResponse({"notes": rows})
elif format == "csv":
response = HttpResponse(content_type="text/csv; charset=utf-8")
fields = ["id", "author", "event_id", "pending_event_id", "content", "category", "source_type", "verification_status", "visibility", "observed_at", "created_at", "updated_at", "association_history"]
writer = csv.DictWriter(response, fieldnames=fields)
writer.writeheader()
for row in rows:
row["association_history"] = json.dumps(row["association_history"])
# Prevent spreadsheet formula execution from user-authored text.
writer.writerow({k: "'" + v if isinstance(v, str) and v.lstrip().startswith(("=", "+", "-", "@")) else v for k, v in row.items()})
else:
raise Http404
response["Content-Disposition"] = f'attachment; filename="boomcast-field-notes.{format}"'
return response
@@ -24,7 +24,14 @@
<section class="dashboard-section" aria-label="{% trans "Quick fireworks report" %}">
<div class="dashboard-report">
<button id="field-notes-toggle" class="field-notes-trigger" type="button" aria-label="{% trans 'Field notes' %}" aria-haspopup="dialog" aria-controls="field-notes-dialog" title="{% trans 'Field notes' %}">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 4.5h8l3 3V19a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V5.5a1 1 0 0 1 1-1h2Z"/><path d="M15.5 4.5V8H19M8.5 12h7M8.5 15.5h5"/></svg>
</button>
{% include "fireworks_detect/includes/manual_report_form.html" %}
<dialog id="field-notes-dialog" class="field-notes-dialog" aria-label="{% trans 'Field notes' %}">
<div class="field-notes-dialog__toolbar"><button id="field-notes-close" type="button" aria-label="{% trans 'Close field notes' %}">×</button></div>
{% if user.is_authenticated %}{% include "fireworks_detect/notes/panel.html" %}{% else %}<div class="field-notes-dialog__signin"><h2>{% trans "Field notes" %}</h2><p><a href="{% url 'login' %}?next=/">{% trans "Sign in to add private field notes" %}</a></p></div>{% endif %}
</dialog>
</div>
</section>
@@ -1,9 +1,13 @@
{% load i18n %}
{% if event.source_type == "manual" %}
<h2>{% trans "Manual fireworks report" %}</h2>
<h2>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</h2>
<p class="meta">{% blocktrans with date=event.approved_at|date:"j M Y, H:i" %}Approved {{ date }} · Reported manually{% endblocktrans %}</p>
<h3>{% trans "Report details" %}</h3>
<div class="prediction prediction--firework"><strong>{% trans "Occurrences" %}</strong><span>{{ event.occurrences }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Occurred" %}</strong><span>{% if event.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ event.captured_at|date:"j M Y, H:i"|default:"Unknown" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Submitted" %}</strong><span>{% if event.submitted_at %}{{ event.submitted_at|date:"j M Y, H:i" }}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
{% if event.is_burst %}<div class="prediction prediction--firework"><strong>{% trans "Duration" %}</strong><span>{% if event.observation_duration_minutes %}{{ event.observation_duration_minutes }} {% if event.observation_duration_kind == "estimated" %}{% trans "minutes (estimated)" %}{% else %}{% trans "minutes (measured)" %}{% endif %}{% else %}{% trans "Unknown" %}{% endif %}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Intensity" %}</strong><span>{% if event.burst_intensity %}{{ event.burst_intensity_display }} · {{ event.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}{% else %}{% trans "Not rated" %}{% endif %}</span></div>{% endif %}
<div class="prediction prediction--firework"><strong>{% trans "Location" %}</strong><span>{{ event.location|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Captured location" %}</strong><span>{{ event_h3_cell|default:"Not recorded" }}</span></div>
<div class="prediction prediction--firework"><strong>{% trans "Direction" %}</strong><span>{{ event.direction_display }}</span></div>
@@ -26,3 +30,5 @@
<p class="empty">{% trans "No peak events returned." %}</p>
{% endfor %}
{% endif %}
{% if request.user.is_authenticated %}{% include "fireworks_detect/notes/panel.html" %}{% else %}<p><a href="{% url 'login' %}?next={{ request.path|urlencode }}">{% trans "Sign in to add private field notes" %}</a></p>{% endif %}
@@ -0,0 +1,2 @@
{% load i18n vite %}
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Event · BoomCast" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" %}<section class="panel">{% include "fireworks_detect/event_detail.html" %}</section></main></body></html>
@@ -1,2 +1,2 @@
{% load i18n vite %}
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Events · Sound Signal" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}{% include "js_translations.html" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" with active_page="events" %}<p class="eyebrow">{% trans "Reviewed signal archive" %}</p><h1>{% trans "Approved events." %}</h1><p class="lede">{% trans "This feed refreshes automatically every three seconds after a pending sample is approved in admin." %}</p><div class="grid"><section class="panel"><h2>{% trans "Latest events" %}</h2><div id="events-feed" hx-get="{% url 'fireworks_detect:events_list' %}" hx-trigger="load, every 3s" hx-swap="innerHTML"><p class="empty">{% trans "Loading events…" %}</p></div></section><section class="panel detail" id="event-detail"><h2>{% trans "Select an event" %}</h2><p class="empty">{% trans "Choose an approved event to inspect its classification details." %}</p></section></div></main></body></html>
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Events · Sound Signal" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}{% include "js_translations.html" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" with active_page="events" %}<p class="eyebrow">{% trans "Reviewed signal archive" %}</p><h1>{% trans "Approved events." %}</h1><p class="lede">{% trans "This feed refreshes automatically every three seconds after a pending sample is approved in admin." %}</p><div class="grid"><section class="panel"><h2>{% trans "Latest events" %}</h2><div id="events-feed" hx-get="{% url 'fireworks_detect:events_list' %}" hx-trigger="load, every 3s" hx-swap="innerHTML">{% include "fireworks_detect/events_list.html" %}</div></section><section class="panel detail" id="event-detail"><h2>{% trans "Select an event" %}</h2><p class="empty">{% trans "Choose an approved event to inspect its classification details." %}</p></section></div></main></body></html>
@@ -1,11 +1,11 @@
{% load i18n %}
{% if events %}
{% for event in events %}
<button class="event {% if event.source_type == "manual" %}event--manual{% else %}event--sensor{% endif %}" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
<a href="{% url 'fireworks_detect:event_detail' event.id %}" class="event {% if event.source_type == "manual" %}event--manual{% else %}event--sensor{% endif %}" hx-get="{% url 'fireworks_detect:event_detail' event.id %}" hx-target="#event-detail" hx-swap="innerHTML">
<span class="event__content">
{% if event.source_type == "manual" %}
<span class="event__source">{% trans "Manual report" %}</span>
<strong>{% trans "Manual fireworks report" %}</strong><br>
<strong>{% if event.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Manual fireworks report" %}{% endif %}</strong><br>
<small>{% blocktrans count count=event.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}{% if event.location %} · {{ event.location }}{% endif %}</small>
{% else %}
<span class="event__source">{% trans "Sensor classification" %}</span>
@@ -14,7 +14,7 @@
{% endif %}
</span>
<span class="badge">{% if event.source_type == "manual" %}{% trans "Manual" %} →{% else %}{{ event.primary_score }} →{% endif %}</span>
</button>
</a>
{% endfor %}
{% else %}
<p class="empty">{% trans "No approved events yet. Submit a classification, then approve it from the Pending page in admin." %}</p>
@@ -10,16 +10,32 @@
<time id="manual-report-time" class="report-clock__time" aria-label="{% trans 'Now' %}">
<span id="report-clock-hours" aria-hidden="true">--</span><span class="report-clock__colon" aria-hidden="true">:</span><span id="report-clock-minutes" aria-hidden="true">--</span>
</time>
<span class="report-clock__now" aria-hidden="true"><span class="report-clock__dot"></span>{% trans "Now" %}</span>
<div class="report-clock__controls">
<span id="report-clock-mode" class="report-clock__now"><span class="report-clock__dot" aria-hidden="true"></span><span id="report-clock-mode-label">{% trans "Now" %}</span></span>
<button id="report-clock-edit" class="report-clock__edit" type="button" aria-label="{% trans 'Edit report time' %}" aria-controls="report-clock-editor" aria-expanded="false" title="{% trans 'Edit report time' %}"><span aria-hidden="true">✎</span></button>
</div>
</div>
<span id="report-clock-date" class="report-clock__date" hidden></span>
<button id="report-clock-reset" class="report-clock__reset" type="button" hidden>{% trans "Use now" %}</button>
<div id="report-clock-editor" class="report-clock__editor" hidden>
<div class="report-clock__fields">
<div><label for="report-clock-draft-date">{% trans "Date" %}</label><input id="report-clock-draft-date" type="date" aria-describedby="report-clock-error"></div>
<div><label for="report-clock-draft-time">{% trans "Time (24-hour)" %}</label><input id="report-clock-draft-time" type="text" inputmode="numeric" autocomplete="off" placeholder="14:30" maxlength="5" aria-describedby="report-clock-error"></div>
</div>
<p id="report-clock-error" class="report-clock__error" role="alert" hidden></p>
<label class="manual-report__check"><input id="manual-time-approximate" name="time_approximate" type="checkbox" form="manual-report-form" disabled> {% trans "Time is approximate" %}</label>
<div class="report-clock__actions"><button id="report-clock-apply" type="button">{% trans "Apply" %}</button><button id="report-clock-cancel" type="button">{% trans "Cancel" %}</button></div>
</div>
</div>
</header>
<form id="manual-report-form" action="{% url "fireworks_detect:submit_manual_pending" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if note_token %}<input type="hidden" name="field_note_context" id="manual-note-context" value="{{ note_token }}">{% endif %}
<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-occurred-at" name="occurred_at" type="hidden">
<div class="manual-report__primary">
<div class="manual-report__quantity">
<label class="manual-report__label" for="manual-occurrences">{% trans "How many times did you hear it?" %}</label>
@@ -28,8 +44,16 @@
<input id="manual-occurrences" name="occurrences" type="number" min="1" max="1000" value="1" required inputmode="numeric">
<button id="manual-increase" type="button" aria-label="{% trans 'Increase occurrences' %}">+</button>
</div>
<p id="manual-burst-status" class="manual-report__burst-status" role="status">{% trans "Ordinary report" %}</p>
</div>
<div id="manual-burst-duration" class="manual-report__duration">
<label class="manual-report__label" for="manual-duration-minutes">{% trans "Estimated observation window (minutes, for 3+ bangs)" %}</label>
<input id="manual-duration-minutes" name="duration_minutes" type="number" min="1" max="1440" value="15" inputmode="numeric">
<label class="manual-report__check"><input id="manual-duration-confirmed" name="duration_confirmed" type="checkbox"> {% trans "Use this estimated window for burst intensity" %}</label>
<small>{% trans "Optional. Without an accepted window, BoomCast reports the count without an intensity rating." %}</small>
</div>
{% include "fireworks_detect/includes/manual_direction_panel.html" %}
<label class="manual-report__check" for="manual-visually-confirmed"><input id="manual-visually-confirmed" name="visually_confirmed" type="checkbox"> {% trans "Visually confirmed" %}</label>
</div>
<section class="manual-report__supporting" data-state="off" aria-labelledby="manual-listening-title">
<div class="manual-report__supporting-header">
@@ -40,11 +64,24 @@
</div>
</div>
<div class="burst-listener" data-state="off">
<label class="manual-report__check"><input id="burst-mode" type="checkbox"> {% trans "Burst Listening experiment" %}</label>
<div id="burst-options" class="burst-listener__options" hidden>
{% if not request.user.is_authenticated %}<p>{% trans "Sign in before starting a Burst Listening session." %} <a href="{% url 'login' %}">{% trans "Sign in" %}</a></p>{% endif %}
<label for="burst-maximum">{% trans "Maximum listening time" %}</label>
<select id="burst-maximum"><option value="10">10 {% trans "minutes" %}</option><option value="15" selected>15 {% trans "minutes" %}</option><option value="20">20 {% trans "minutes" %}</option></select>
<label for="burst-test-mode">{% trans "Test setup" %}</label>
<select id="burst-test-mode"><option value="standard">Standard</option><option value="guided_access">Guided Access</option><option value="wake_lock">Wake Lock</option></select>
</div>
<button id="burst-start" class="burst-listener__button" type="button">{% trans "Start listening" %}</button>
<div id="burst-panel" class="burst-listener__panel" hidden>
<strong id="burst-heading" aria-live="polite"></strong>
<canvas id="burst-waveform" width="600" height="90" aria-label="{% trans 'Live microphone waveform' %}"></canvas>
<p id="burst-detail"></p>
<p id="burst-diagnostics" role="status" hidden></p>
<button id="burst-manual-capture" type="button" hidden>{% trans "Capture now" %}</button>
<button id="burst-export" type="button" hidden>{% trans "Export diagnostics" %}</button>
<details id="burst-timeline" hidden><summary>{% trans "Diagnostic timeline" %}</summary><ol id="burst-timeline-list"></ol></details>
<div id="burst-review" hidden><h4>{% trans "Review burst captures" %}</h4><p id="burst-upload-error" role="alert" hidden></p><ol id="burst-capture-list"></ol></div>
<audio id="burst-preview" controls hidden></audio>
<div class="burst-listener__actions">
<button id="burst-resume" type="button" hidden>{% trans "Resume listening" %}</button>
@@ -55,7 +92,7 @@
<p id="burst-error" role="alert" hidden></p>
</div>
</section>
<button id="manual-submit" class="manual-report__submit" type="button"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
<button id="manual-submit" class="manual-report__submit" type="submit"><span aria-hidden="true">🔥</span> <span id="manual-submit-label">{% trans "I heard fireworks" %}</span></button>
</form>
<div id="manual-submission" class="manual-report__submission" aria-live="polite"></div>
<div id="manual-compass-home">
@@ -1,8 +1,8 @@
{% load i18n %}
<section class="map-panel" aria-label="{% trans "Manual fireworks report map" %}">
<div class="map-header"><strong>{% trans "Manual reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }} · sensor layer disabled{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of manual fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Manual reports" %}</h2><div><span class="legend-dot"></span> {% trans "Report marker at H3-cell centre" %}</div><div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div><div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div></aside>
<section class="map-panel" aria-label="{% trans "Reviewed fireworks report map" %}">
<div class="map-header"><strong>{% trans "Reviewed reports · privacy-preserving H3 cells" %}</strong><span class="live"><i></i> {% blocktrans with resolution=h3_resolution %}H3 resolution {{ resolution }}{% endblocktrans %}</span></div>
<div class="map-wrap"><div id="event-map" class="map" data-h3-resolution="{{ h3_resolution }}" aria-label="{% trans "Interactive map of reviewed fireworks reports" %}"></div>
<aside class="legend" aria-label="{% trans "Map legend" %}"><h2>{% trans "Map legend" %}</h2>{% if map_source != "sensor" %}<div><span class="legend-dot"></span> {% trans "Manual report" %}</div>{% endif %}{% if map_source == "sensor" or map_source == "all" %}<div><span class="legend-sensor"></span> {% trans "Sensor event" %}</div>{% endif %}<div><span class="legend-ring"></span> {% blocktrans with resolution=h3_resolution %}H3 cell (resolution {{ resolution }}){% endblocktrans %}</div>{% if map_source != "sensor" %}<div><span class="legend-line"></span> {% trans "Saved compass direction" %}</div>{% endif %}</aside>
</div>
</section>
{{ h3_cells|json_script:"h3-cells-data" }}
@@ -8,6 +8,7 @@
<a href="{% url "fireworks_detect:map" %}"{% if active_page == "map" %} aria-current="page"{% endif %}>{% trans "Map" %}</a>
<a href="{% url "fireworks_detect:events" %}"{% if active_page == "events" %} aria-current="page"{% endif %}>{% trans "Events" %}</a>
{% if request.user.is_authenticated %}
<a href="{% url 'fireworks_detect:field_notes' %}">{% trans "Field notes" %}</a>
<form action="{% url 'logout' %}" method="post">
{% csrf_token %}
<button type="submit">{% trans "Sign out" %}</button>
@@ -1,17 +1,31 @@
{% load i18n %}
<div id="manual-submission" class="manual-submission{% if error %} manual-submission--error{% else %} manual-submission--success{% endif %}" role="status" data-result="{% if error %}error{% else %}success{% endif %}">
<div id="manual-submission" class="manual-submission{% if error %} manual-submission--error{% else %} manual-submission--success{% endif %}" role="status" data-next-note-token="{{ next_note_token }}" data-result="{% if error %}error{% else %}success{% endif %}">
{% if error %}
<span class="manual-submission__icon" aria-hidden="true">!</span>
<strong>{% trans "Could not report fireworks" %}</strong>
<p>{{ error }}</p>
{% else %}
<span class="manual-submission__icon" aria-hidden="true">✓</span>
<strong>{% trans "Report received!" %}</strong>
<strong>{% if updated %}{% trans "Report updated!" %}{% else %}{% trans "Report received!" %}{% endif %}</strong>
<p>{% trans "Thank you. Your report helps map fireworks nearby." %}</p>
<p class="manual-submission__summary">
{{ pending.created_at|date:"H:i" }} ·
{% if pending.occurrence_time_approximate %}{% trans "Approximately" %} {% endif %}{{ pending.captured_at|date:"j M Y, H:i" }} ·
{% blocktrans count count=pending.occurrences %}{{ count }} occurrence{% plural %}{{ count }} occurrences{% endblocktrans %}
{% if direction_label %} · {{ direction_label }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
{% if pending.direction_degrees is not None %} · {{ direction_label|default:pending.direction_cardinal }} {{ pending.direction_degrees|floatformat:0 }}°{% endif %}
</p>
<p>{% if pending.is_burst %}{% trans "Burst Event" %}{% else %}{% trans "Ordinary report" %}{% endif %} · {% trans "Submitted" %} {{ pending.created_at|date:"j M Y, H:i" }}</p>
{% if pending.is_burst %}<p>{% trans "Duration" %}: {% if pending.observation_duration_minutes %}{{ pending.observation_duration_minutes }} {% trans "minutes (estimated)" %}{% else %}{% trans "Unknown" %}{% endif %}</p>
<p>{% trans "Intensity" %}: {% if pending.burst_intensity %}{{ pending.burst_intensity_display }} ({{ pending.bangs_per_15_minutes|floatformat:1 }} {% trans "bangs per 15 minutes" %}){% else %}{% trans "Not rated" %}{% endif %}</p>{% endif %}
<p>{% trans "Visually confirmed" %}: {% if pending.visually_confirmed %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}</p>
{% if request.user.is_authenticated %}<p><a href="{% url 'fireworks_detect:field_notes' %}?pending={{ pending.pk }}">{% trans "Add or review field notes for this report" %}</a></p>{% endif %}
{% if editable %}<form class="manual-submission__edit" method="post" action="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-post="{% url 'fireworks_detect:update_manual_pending' pending.pk %}" hx-target="#manual-submission" hx-swap="outerHTML">
{% csrf_token %}
<label for="manual-edit-count">{% trans "Correct bang count" %}</label>
<input id="manual-edit-count" name="occurrences" type="number" min="1" max="1000" value="{{ pending.occurrences }}" required>
<label for="manual-edit-duration">{% trans "Estimated minutes for a burst" %}</label>
<input id="manual-edit-duration" name="duration_minutes" type="number" min="1" max="1440" value="{{ pending.observation_duration_minutes|default:15 }}">
<label><input name="duration_confirmed" type="checkbox" {% if pending.observation_duration_kind %}checked{% endif %}> {% trans "Use this estimated window" %}</label>
<button type="submit">{% trans "Update report" %}</button>
</form>{% endif %}
{% endif %}
</div>
@@ -14,12 +14,12 @@
{% include "fireworks_detect/includes/navigation.html" with active_page="map" %}
<section class="headline" aria-labelledby="map-title">
<div><p class="kicker">{% trans "Manual report intelligence" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "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>
<div><p class="kicker">{% trans "Reviewed sound reports" %}</p><h1 id="map-title">{% trans "Sound activity map." %}</h1></div>
<p>{% trans "Reviewed reports with a stored location appear at their H3 cell centre, not their precise coordinates. Sensor events use only saved event locations; device-reported coordinates are not trusted for this map." %}</p>
</section>
<form class="filters" method="get" action="{% url 'fireworks_detect:map' %}" aria-label="{% trans "Map filters" %}">
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" disabled><option selected>{% trans "Manual reports" %}</option><option>{% trans "Sensor events — coming soon" %}</option></select></div>
<div class="filter"><label for="event-source">{% trans "Source" %}</label><select id="event-source" name="source"><option value="manual" {% if map_filters.source == "manual" %}selected{% endif %}>{% trans "Manual reports" %}</option><option value="sensor" {% if map_filters.source == "sensor" %}selected{% endif %}>{% trans "Sensor events" %}</option><option value="all" {% if map_filters.source == "all" %}selected{% endif %}>{% trans "Both sources" %}</option></select></div>
<div class="filter"><label for="range">{% trans "Period" %}</label><select id="range" name="range"><option value="7" {% if map_filters.range == "7" %}selected{% endif %}>{% trans "Last 7 days" %}</option><option value="14" {% if map_filters.range == "14" %}selected{% endif %}>{% trans "Last 2 weeks" %}</option><option value="30" {% if map_filters.range == "30" %}selected{% endif %}>{% trans "Last 30 days" %}</option><option value="all" {% if map_filters.range == "all" %}selected{% endif %}>{% trans "All time" %}</option><option value="custom" {% if map_filters.range == "custom" %}selected{% endif %}>{% trans "Custom range" %}</option></select></div>
<div class="filter"><label for="from-date">{% trans "From" %}</label><input id="from-date" name="from" type="date" value="{{ map_filters.date_from }}"></div>
<div class="filter"><label for="to-date">{% trans "To" %}</label><input id="to-date" name="to" type="date" value="{{ map_filters.date_to }}"></div>
@@ -0,0 +1,2 @@
{% load i18n vite %}
<!doctype html><html lang="{{ request.LANGUAGE_CODE|default:'en' }}" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{% trans "Field notes · BoomCast" %}</title><script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.4/dist/htmx.min.js"></script>{% vite_asset "frontend/src/entries/events.js" %}</head><body><main class="shell">{% include "fireworks_detect/includes/navigation.html" %}<section class="panel">{% include "fireworks_detect/notes/panel.html" %}<p>{% trans "Exports include only reportable notes you are authorised to export. Private notes are always excluded." %}</p><a href="{% url 'fireworks_detect:export_field_notes' 'json' %}">JSON</a> · <a href="{% url 'fireworks_detect:export_field_notes' 'csv' %}">CSV</a></section></main></body></html>
@@ -0,0 +1,38 @@
{% load i18n tz %}
<section class="field-notes" id="{{ note_panel_id|default:'live-field-notes' }}" aria-label="{% trans 'Field notes' %}">
<h2>{% trans "Field notes" %} <span class="field-notes__count">({{ note_count|default:0 }})</span></h2>
<p>{% trans "Human context, separate from detection evidence. Notes are private by default. Add a follow-up to correct an earlier entry." %}</p>
{% if note_target %}<p>{% trans "Report" %} #{{ note_target.pk }} · {{ note_target.occurrences }} {% trans "bangs" %}</p>{% endif %}
{% if note_saved %}<p role="status">{% trans "Field note saved." %}</p>{% endif %}
<details {% if note_form.errors %}open{% endif %}>
<summary>{% trans "Add field note" %}</summary>
<form method="post" action="{% url 'fireworks_detect:field_notes' %}" hx-post="{% url 'fireworks_detect:field_notes' %}" hx-target="closest .field-notes" hx-swap="outerHTML">
{% csrf_token %}
{% if note_token %}<input type="hidden" name="token" value="{{ note_token }}">{% elif note_kind %}<input type="hidden" name="{{ note_kind }}" value="{{ note_value }}">{% endif %}
{{ note_form.non_field_errors }}
<div class="field-notes__field">{{ note_form.content.label_tag }}{{ note_form.content }}{{ note_form.content.errors }}</div>
<details {% if note_form.errors %}open{% endif %}><summary>{% trans "Optional details" %}</summary>
<div class="field-notes__fields">
{% for field in note_form %}{% if field.name != 'content' %}<div class="field-notes__field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small id="{{ field.auto_id }}_helptext">{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}
</div>
</details>
<button type="submit">{% trans "Save field note" %}</button>
</form>
</details>
<ol class="field-notes__timeline">
{% for note in field_notes %}
<li>
<p class="field-notes__meta">{{ note.get_category_display }} · {{ note.author.get_username }} · {{ note.get_visibility_display }}</p>
<p class="field-notes__meta">{{ note.get_source_type_display }} · {{ note.get_verification_status_display }}</p>
<p class="field-notes__content">{{ note.content }}</p>
<p class="field-notes__meta">{% trans "Entered" %}: <time datetime="{{ note.created_at|date:'c' }}">{{ note.created_at|localtime|date:"j M Y, H:i T" }}</time>{% if note.observed_at %}<br>{% trans "Observed" %}: <time datetime="{{ note.observed_at|date:'c' }}">{{ note.observed_at|localtime|date:"j M Y, H:i T" }}</time>{% endif %}</p>
{% if note.context.event_id %}<a href="{% url 'fireworks_detect:event_detail' note.context.event_id %}">{% trans "Event" %} #{{ note.context.event_id }}</a>{% elif note.context.pending_event_id %}<a href="{% url 'fireworks_detect:field_notes' %}?pending={{ note.context.pending_event_id }}">{% trans "Pending report" %} #{{ note.context.pending_event_id }}</a>{% else %}<span>{% if note_token %}{% trans "Current observation — not yet submitted" %}{% else %}{% trans "Standalone observation" %}{% endif %}</span>{% endif %}
{% if note.context.associations.all %}<details><summary>{% trans "Association history" %}</summary><ul>{% for change in note.context.associations.all %}<li>{{ change.created_at|localtime|date:"j M Y, H:i" }} · {{ change.reason }} · {{ change.previous.kind|default:"standalone" }} {{ change.previous.id|default:"" }} → {{ change.target.kind }} {{ change.target.id }}</li>{% endfor %}</ul></details>{% endif %}
{% if not note_kind and not note.context.event_id and not note.context.pending_event_id and note.author_id == request.user.pk %}
<form method="post" action="{% url 'fireworks_detect:link_field_note' note.context_id %}">{% csrf_token %}<label for="link-{{ note.pk }}">{% trans "Link to an approved event" %}</label><select name="event" id="link-{{ note.pk }}" required><option value="">{% trans "Choose an event" %}</option>{% for item in note_events %}<option value="{{ item.pk }}">#{{ item.pk }} · {{ item.captured_at|default:item.created_at|date:"j M Y, H:i" }} · {{ item.occurrences }} {% trans "bangs" %}</option>{% endfor %}</select><button type="submit">{% trans "Link observation" %}</button></form>
{% endif %}
</li>
{% empty %}<li>{% trans "No field notes visible to you yet." %}</li>{% endfor %}
</ol>
<p><a href="{% url 'fireworks_detect:field_notes' %}">{% trans "My field notes" %}</a></p>
</section>
+89
View File
@@ -0,0 +1,89 @@
import json
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .models import BurstSession
class BurstHeartbeatTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username="burst-a", password="test-password")
self.other = get_user_model().objects.create_user(username="burst-b", password="test-password")
self.client.force_login(self.user)
def start(self):
response = self.client.post(reverse("fireworks_detect:burst_start"), {"maximum_minutes": "15"})
self.assertEqual(response.status_code, 200)
return BurstSession.objects.get(pk=response.json()["id"])
def heartbeat(self, session, sequence=1, frames=100):
return self.client.post(reverse("fireworks_detect:burst_detail", args=[session.pk]), data=json.dumps({
"sequence": sequence, "audio_frames": frames, "elapsed_ms": 5000,
"wall_at": timezone.now().isoformat(), "track_state": "live", "visibility": "visible",
}), content_type="application/json")
def test_sessions_time_out_independently_and_recover(self):
lost = self.start()
active = self.start()
old = timezone.now() - timedelta(seconds=20)
BurstSession.objects.filter(pk=lost.pk).update(started_at=old, last_seen_at=old)
self.assertEqual(self.heartbeat(active).status_code, 200)
call_command("watch_burst_sessions", once=True)
lost.refresh_from_db()
active.refresh_from_db()
self.assertEqual(lost.status, "heartbeat_lost")
self.assertIsNotNone(lost.timeout_at)
self.assertEqual(active.status, "listening")
self.assertIsNone(active.timeout_at)
self.assertEqual(self.heartbeat(lost).status_code, 200)
lost.refresh_from_db()
self.assertEqual(lost.status, "listening")
self.assertTrue(any(item["kind"] == "heartbeat_recovered" for item in lost.diagnostic_events))
def test_replay_and_foreign_session_rejected(self):
session = self.start()
self.assertEqual(self.heartbeat(session).status_code, 200)
self.assertEqual(self.heartbeat(session).status_code, 400)
self.client.force_login(self.other)
self.assertEqual(self.heartbeat(session, sequence=2).status_code, 404)
self.assertEqual(self.client.get(reverse("fireworks_detect:burst_detail", args=[session.pk])).status_code, 404)
class BurstSubmissionTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username="burst-submit", password="test-password")
self.client.force_login(self.user)
self.client.cookies["django_language"] = "en"
def test_grouped_submission_creates_one_pending_with_two_clips(self):
from django.core.files.uploadedfile import SimpleUploadedFile
from .models import BurstCapture, PendingEvent
session = BurstSession.objects.create(owner=self.user, status="review", ended_at=timezone.now())
wav = b"RIFF" + b"\x00" * 4 + b"WAVEfmt " + b"\x00" * 40
clips = [SimpleUploadedFile(f"clip-{index}.wav", wav, content_type="audio/wav") for index in range(2)]
metadata = [{"captured_at": timezone.now().isoformat(), "duration_seconds": 2.0} for _ in clips]
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"burst_session_id": str(session.pk), "burst_audio": clips,
"burst_captures": json.dumps(metadata), "burst_primary": "1", "occurrences": "2",
"burst_predictions": json.dumps([{"class": "Fireworks", "score": 0.8}]),
})
self.assertEqual(response.status_code, 200)
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(BurstCapture.objects.filter(session=session).count(), 2)
self.assertEqual(PendingEvent.objects.get().classifier_response["classification_source"], "browser_yamnet_advisory")
self.assertEqual(BurstCapture.objects.get(session=session, is_primary=True).audio_file.name, PendingEvent.objects.get().audio_file.name)
from django.contrib import admin
self.assertIn("<audio", str(admin.site._registry[PendingEvent].burst_captures(PendingEvent.objects.get())))
self.assertEqual(self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"burst_session_id": str(session.pk), "burst_audio": clips,
"burst_captures": json.dumps(metadata), "burst_primary": "1", "occurrences": "2",
"burst_predictions": json.dumps([{"class": "Fireworks", "score": 0.8}]),
}).status_code, 409)
PendingEvent.objects.get().approve(actor=self.user)
session.refresh_from_db()
self.assertIsNotNone(session.event_id)
self.assertEqual(session.captures.count(), 2)
+182
View File
@@ -0,0 +1,182 @@
from datetime import timedelta
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.exceptions import PermissionDenied, ValidationError
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .field_notes import draft_token, regroup_event_notes, reportable_notes
from .models import Event, FieldNote, FieldNoteContext, FieldNoteAssociation, PendingEvent
class FieldNotesTests(TestCase):
def setUp(self):
User = get_user_model()
self.alice = User.objects.create_user('alice', password='test-password')
self.bob = User.objects.create_user('bob', password='test-password')
self.event = Event.objects.create(original_filename='Burst', classifier_response={}, source_type='manual', occurrences=15)
self.url = reverse('fireworks_detect:field_notes')
self.client.force_login(self.alice)
def note(self, user=None, visibility='private', **kwargs):
user = user or self.alice
context = FieldNoteContext.objects.create(author=user, event=self.event)
return FieldNote.objects.create(author=user, context=context, content='A private observation', visibility=visibility, **kwargs)
def test_only_content_required_private_defaults_plain_text(self):
response = self.client.post(self.url, {'content': '<script>alert(1)</script>\nSecond line'})
self.assertEqual(response.status_code, 302)
note = FieldNote.objects.get()
self.assertEqual(note.visibility, 'private')
self.assertEqual(note.source_type, 'unknown')
self.assertEqual(note.verification_status, 'unverified')
response = self.client.get(self.url)
self.assertContains(response, '&lt;script&gt;')
self.assertNotContains(response, '<script>alert(1)</script>')
def test_cross_user_read_create_link_and_export_are_scoped(self):
note = self.note()
self.client.force_login(self.bob)
self.assertNotContains(self.client.get(self.url), note.content)
self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), note.content)
response = self.client.post(self.url, {'content':'forged', 'token':draft_token(self.alice)})
self.assertEqual(response.status_code, 403)
self.assertEqual(self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event': self.event.pk}).status_code, 404)
self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes'], [])
def test_anonymous_cannot_create_read_or_export_notes(self):
self.note()
self.client.logout()
self.assertEqual(self.client.post(self.url, {'content':'no'}).status_code, 302)
self.assertEqual(self.client.get(self.url).status_code, 302)
self.assertNotContains(self.client.get(reverse('fireworks_detect:event_detail', args=[self.event.pk])), 'A private observation')
self.assertEqual(self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).status_code, 302)
def test_export_always_excludes_private_even_for_superuser(self):
self.note()
public = self.note(visibility='reportable', source_type='second_hand')
self.note(self.bob, visibility='reportable')
self.assertEqual(list(reportable_notes(self.alice)), [public])
self.alice.is_superuser = self.alice.is_staff = True
self.alice.save()
for format in ['json','csv']:
response = self.client.get(reverse('fireworks_detect:export_field_notes', args=[format]))
self.assertEqual(response.status_code, 200)
self.assertNotIn('"visibility": "private"', response.content.decode())
rows = self.client.get(reverse('fireworks_detect:export_field_notes', args=['json'])).json()['notes']
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0]['source_type'], 'second_hand')
self.assertEqual(rows[0]['verification_status'], 'unverified')
def test_reportable_does_not_grant_other_users_read_access(self):
note = self.note(visibility='reportable')
self.client.force_login(self.bob)
self.assertNotContains(self.client.get(self.url), note.content)
def test_observed_time_entry_time_and_append_only(self):
self.client.post(self.url, {'content':'Later information', 'observed_at':'2026-10-09T14:00'})
note = FieldNote.objects.get()
self.assertTrue(timezone.is_aware(note.observed_at))
self.assertLess(note.observed_at, note.created_at)
entered = note.created_at
note.content = 'rewrite'
with self.assertRaises(ValidationError): note.save()
note.refresh_from_db()
self.assertEqual(note.content, 'Later information')
self.assertEqual(note.created_at, entered)
def test_invalid_forms_render_with_and_without_htmx(self):
for headers in [{}, {'HTTP_HX_REQUEST':'true'}]:
response = self.client.post(self.url, {'content':' ', 'visibility':'public'}, **headers)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'errorlist')
self.assertFalse(FieldNote.objects.exists())
def test_live_notes_bind_to_report_and_survive_approval(self):
token = draft_token(self.alice)
self.client.post(self.url, {'token':token, 'content':'Heard during listening'}, HTTP_HX_REQUEST='true')
note = FieldNote.objects.get()
original_time = note.created_at
response = self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'15', 'field_note_context':token})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
note.context.refresh_from_db()
self.assertEqual(note.context.pending_event_id, pending.pk)
event = pending.approve(actor=self.alice)
note.context.refresh_from_db()
self.assertEqual(note.context.event_id, event.pk)
self.assertIsNone(note.context.pending_event_id)
note.refresh_from_db()
self.assertEqual(note.created_at, original_time)
self.assertEqual(note.context.associations.count(), 2)
self.assertEqual(note.context.associations.last().actor_id, self.alice.pk)
# A note submitted from an already-open form follows the approved report.
self.client.post(self.url, {'token':token, 'content':'Late save'})
self.assertEqual(FieldNote.objects.get(content='Late save').context.event_id, event.pk)
# Reusing a report token cannot reparent existing notes or create a report.
self.assertEqual(self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'1', 'field_note_context':token}).status_code, 403)
self.assertFalse(PendingEvent.objects.exists())
def test_pending_access_checked_and_historical_append(self):
pending = PendingEvent.objects.create(original_filename='secret', classifier_response={})
self.assertEqual(self.client.get(self.url, {'pending':pending.pk}).status_code, 404)
self.assertEqual(self.client.post(self.url, {'pending':pending.pk,'content':'no'}).status_code, 404)
self.assertEqual(self.client.post(self.url, {'event':self.event.pk,'content':'Historical follow-up'}).status_code, 302)
self.assertEqual(FieldNote.objects.get().context.event_id, self.event.pk)
def test_standalone_link_and_regroup_preserve_provenance(self):
self.client.post(self.url, {'content':'Possible camera lead'})
note = FieldNote.objects.get()
response = self.client.post(reverse('fireworks_detect:link_field_note', args=[note.context_id]), {'event':self.event.pk})
self.assertEqual(response.status_code, 302)
target = Event.objects.create(original_filename='Grouped burst', classifier_response={}, occurrences=20)
with self.assertRaises(PermissionDenied): regroup_event_notes(self.alice, self.event, target)
self.alice.is_superuser = self.alice.is_staff = True; self.alice.save()
regroup_event_notes(self.alice, self.event, target)
self.event.delete()
note.context.refresh_from_db()
self.assertEqual(note.context.event_id, target.pk)
self.assertEqual(note.context.associations.count(), 2)
self.assertEqual(note.context.associations.last().previous['id'], self.event.pk or note.context.associations.first().target['id'])
self.assertEqual(FieldNote.objects.count(), 1)
def test_denied_report_retains_notes_and_original_reference(self):
token = draft_token(self.alice)
self.client.post(self.url, {'token':token,'content':'Retain observation'})
self.client.post(reverse('fireworks_detect:submit_manual_pending'), {'occurrences':'3','field_note_context':token})
pending = PendingEvent.objects.get(); old_id = pending.pk; pending.deny()
note = FieldNote.objects.get()
self.assertIsNone(note.context.pending_event_id)
self.assertEqual(note.context.associations.get().target, {'kind':'pending','id':old_id})
def test_staff_needs_explicit_permission_for_private_notes(self):
self.note()
self.bob.is_staff = True; self.bob.save()
self.assertFalse(FieldNote.objects.visible_to(self.bob).exists())
self.bob.user_permissions.add(Permission.objects.get(codename='view_all_fieldnotes'))
bob = get_user_model().objects.get(pk=self.bob.pk)
self.assertEqual(FieldNote.objects.visible_to(bob).count(), 1)
self.assertFalse(reportable_notes(bob).exists())
def test_csv_formula_is_escaped(self):
ctx = FieldNoteContext.objects.create(author=self.alice)
FieldNote.objects.create(author=self.alice, context=ctx, content='=1+1', visibility='reportable')
self.assertContains(self.client.get(reverse('fireworks_detect:export_field_notes', args=['csv'])), "'=1+1")
def test_note_posts_require_csrf(self):
from django.test import Client
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.alice)
self.assertEqual(browser.post(self.url, {"content":"forged"}).status_code, 403)
self.assertFalse(FieldNote.objects.exists())
def test_history_orders_by_entry_not_backdated_observation(self):
first = self.note(observed_at=timezone.now())
second = self.note(observed_at=timezone.now()-timedelta(days=7))
self.assertEqual(list(FieldNote.objects.values_list("pk", flat=True)), [first.pk, second.pk])
self.client.force_login(self.bob)
self.bob.user_permissions.add(Permission.objects.get(codename="export_reportable_fieldnotes"))
# Export permission does not grant read access to private history.
self.assertNotContains(self.client.get(self.url), first.content)
+85
View File
@@ -0,0 +1,85 @@
import hashlib
import json
from django.contrib.auth.models import Permission, User
from django.test import TestCase, override_settings
from django.urls import reverse
from .models import Event, McpAccessToken, PendingEvent, Sensor
@override_settings(ALLOWED_HOSTS=["testserver"])
class McpTests(TestCase):
def setUp(self):
self.url = reverse("boomcast_mcp")
self.user = User.objects.create_user("review_reader", password="unused")
self.user.user_permissions.add(*Permission.objects.filter(codename__in=["view_event", "view_pendingevent"], content_type__app_label="fireworks_detect"))
self.token = "bmcp_test_read_only"
McpAccessToken.objects.create(user=self.user, name="test", token_hash=hashlib.sha256(self.token.encode()).hexdigest())
self.pending = PendingEvent.objects.create(original_filename="private.wav", classifier_response={"predictions": [{"class": "Fireworks", "score": 0.9}]}, latitude="52.123456", longitude="5.123456")
self.event = Event.objects.create(original_filename="reviewed.wav", classifier_response={"predictions": [{"class": "Fireworks", "score": 0.8}]}, latitude="52.123456", longitude="5.123456")
def call(self, method, params=None, token=None):
return self.client.post(self.url, data=json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}), content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {token or self.token}")
def result(self, name, args=None):
return self.call("tools/call", {"name": name, "arguments": args or {}}).json()["result"]
def test_discovery_and_reviewed_only(self):
self.assertEqual(self.call("initialize").json()["result"]["serverInfo"]["name"], "boomcast-readonly")
self.assertEqual(len(self.call("tools/list").json()["result"]["tools"]), 4)
listing = self.result("submissions_list")["structuredContent"]
self.assertEqual(listing["total"], 1)
self.assertEqual(listing["items"][0]["id"], self.event.pk)
self.assertNotIn("private.wav", json.dumps(listing))
other_pending = PendingEvent.objects.create(original_filename="another-private.wav", classifier_response={})
self.assertTrue(self.result("submissions_get", {"id": other_pending.pk})["isError"])
def test_pending_is_aggregate_only(self):
result = self.result("pending_summary")["structuredContent"]
self.assertEqual(result, {"total": 1, "by_predicted_classification": {"Fireworks": 1}})
self.assertNotIn("private.wav", json.dumps(result))
def test_details_are_privacy_limited(self):
result = self.result("submissions_get", {"id": self.event.pk})["structuredContent"]
self.assertEqual(result["predictions"][0]["score"], 0.8)
for key in ("latitude", "longitude", "audio_file", "original_filename", "sensor", "location", "device_metadata"):
self.assertNotIn(key, result)
self.assertIsNotNone(result["generalized_location_h3"])
def test_pagination_filter_and_stats(self):
Event.objects.create(original_filename="other.wav", classifier_response={"predictions": [{"class": "Thunder", "score": 0.7}]})
self.assertEqual(self.result("submissions_list", {"limit": 1, "offset": 1})["structuredContent"]["total"], 2)
filtered = self.result("submissions_list", {"classification": "Thunder"})["structuredContent"]
self.assertEqual(filtered["total"], 1)
stats = self.result("submissions_stats")["structuredContent"]
self.assertEqual(stats["by_predicted_classification"], {"Fireworks": 1, "Thunder": 1})
self.assertEqual(stats["by_review_outcome"], {"approved": 2})
self.assertTrue(self.result("submissions_list", {"limit": 101})["isError"])
self.assertTrue(self.result("submissions_stats", {"date_from": "2020-01-01", "date_to": "2026-01-01"})["isError"])
def test_auth_permissions_and_no_mutations(self):
self.assertEqual(self.client.post(self.url, data="{}", content_type="application/json").status_code, 401)
sensor = Sensor.objects.create(name="test sensor")
self.assertEqual(self.call("tools/list", token=sensor.issue_token()).status_code, 401)
self.user.user_permissions.clear()
self.assertEqual(self.call("tools/list").status_code, 403)
self.user.is_superuser = True
self.user.save(update_fields=["is_superuser"])
self.assertEqual(self.call("tools/call", {"name": "approve", "arguments": {}}).json()["result"]["isError"], True)
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(self.client.get(self.url, HTTP_AUTHORIZATION=f"Bearer {self.token}").status_code, 405)
def test_revocation_inactive_user_and_origin(self):
self.assertEqual(self.call("tools/list", token="bmcp_wrong").status_code, 401)
self.assertEqual(self.client.post(self.url, data='{"jsonrpc":"2.0","id":1,"method":"tools/list"}', content_type="application/json", HTTP_AUTHORIZATION=f"Bearer {self.token}", HTTP_ORIGIN="https://evil.example").status_code, 403)
self.user.is_active = False
self.user.save(update_fields=["is_active"])
self.assertEqual(self.call("tools/list").status_code, 401)
self.user.is_active = True
self.user.save(update_fields=["is_active"])
credential = McpAccessToken.objects.get(user=self.user)
from django.utils import timezone
credential.revoked_at = timezone.now()
credential.save(update_fields=["revoked_at"])
self.assertEqual(self.call("tools/list").status_code, 401)
+107
View File
@@ -0,0 +1,107 @@
import io
import json
import struct
import wave
from tempfile import TemporaryDirectory
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings
from django.urls import reverse
from .models import PendingEvent, Sensor, SensorSubmission
def wav_bytes():
stream = io.BytesIO()
with wave.open(stream, "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(16000)
wav.writeframes(struct.pack("<16000h", *([0] * 16000)))
return stream.getvalue()
class SensorSubmissionTests(TestCase):
def setUp(self):
self.owner = get_user_model().objects.create_user("sensor-owner", password="test")
self.sensor = Sensor.objects.create(name="Waveshare V2", owner=self.owner)
self.token = self.sensor.issue_token()
self.url = reverse("sensor_pending")
self.audio = wav_bytes()
def submit(self, token=None, **fields):
data = {
"sensor_id": str(self.sensor.pk), "event_id": "device-event-1",
"captured_at": "2026-10-09T10:00:00Z", "duration_seconds": "1",
"firmware_version": "0.1.0-concept",
"file": SimpleUploadedFile("event.wav", self.audio, content_type="audio/wav"),
}
data.update(fields)
return self.client.post(self.url, data, HTTP_AUTHORIZATION=f"Bearer {token or self.token}")
def test_authenticated_upload_is_classified_and_retry_is_idempotent(self):
response_body = io.BytesIO(json.dumps({"predictions": [{"class": "Fireworks", "score": 0.8}], "duration_seconds": 1}).encode())
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body) as classify:
first = self.submit(
trigger_type="audio_spike", latitude="52.1",
capture_started_at="2026-10-09T10:00:00Z",
triggered_at="2026-10-09T10:00:02Z",
queued_at="2026-10-09T10:00:05Z",
)
second = self.submit()
self.assertEqual(first.status_code, 201)
self.assertEqual(second.status_code, 200)
self.assertEqual(first.json()["submission_id"], second.json()["submission_id"])
self.assertEqual(first.json()["event_id"], "device-event-1")
self.assertEqual(second.json()["event_id"], "device-event-1")
self.assertEqual(PendingEvent.objects.count(), 1)
self.assertEqual(SensorSubmission.objects.count(), 1)
self.assertEqual(classify.call_count, 1)
pending = PendingEvent.objects.get()
self.assertEqual(pending.sensor, self.sensor)
self.assertEqual(pending.source_type, "sensor")
self.assertFalse(pending.latitude)
self.assertEqual(pending.device_metadata["latitude"], "52.1")
self.assertEqual(pending.device_metadata["triggered_at"], "2026-10-09T10:00:02Z")
self.assertTrue(pending.audio_file.storage.exists(pending.audio_file.name))
def test_unknown_capture_time_is_explicit_and_retained(self):
response_body = io.BytesIO(json.dumps({"predictions": [], "duration_seconds": 1}).encode())
with TemporaryDirectory() as media, override_settings(MEDIA_ROOT=media), patch("fireworks_detect.views.urlopen", return_value=response_body):
response = self.submit(captured_at="", time_state="unknown")
self.assertEqual(response.status_code, 201)
self.assertIsNone(PendingEvent.objects.get().captured_at)
self.assertEqual(PendingEvent.objects.get().device_metadata["time_state"], "unknown")
def test_pending_admin_shows_sensor_details(self):
staff = get_user_model().objects.create_superuser("reviewer-sensor", password="test")
pending = PendingEvent.objects.create(sensor=self.sensor, source_type="sensor", original_filename="event.wav", classifier_response={"predictions": [{"class": "Fireworks", "score": 0.8}]}, firmware_version="0.1.0-concept", device_metadata={"trigger_type": "audio_spike"})
self.client.force_login(staff)
response = self.client.get(reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk]))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "sensor-owner")
self.assertContains(response, "0.1.0-concept")
self.assertContains(response, "audio_spike")
def test_classifier_failure_keeps_event_retryable(self):
from urllib.error import URLError
with patch("fireworks_detect.views.urlopen", side_effect=URLError("offline")):
response = self.submit()
self.assertEqual(response.status_code, 502)
self.assertEqual(response.json()["code"], "classifier_unavailable")
self.assertFalse(PendingEvent.objects.exists())
self.assertFalse(SensorSubmission.objects.exists())
def test_existing_event_id_with_different_audio_conflicts(self):
SensorSubmission.objects.create(sensor=self.sensor, event_id="device-event-1", audio_sha256="0" * 64)
response = self.submit()
self.assertEqual(response.status_code, 409)
self.assertEqual(response.json()["code"], "event_id_conflict")
def test_bad_token_sensor_mismatch_and_malformed_audio_are_rejected(self):
self.assertEqual(self.submit(token="wrong").status_code, 401)
self.assertEqual(self.submit(sensor_id="999").status_code, 403)
self.assertEqual(self.submit(file=SimpleUploadedFile("bad.wav", b"not wav", content_type="audio/wav")).status_code, 400)
self.assertFalse(PendingEvent.objects.exists())
+161 -5
View File
@@ -14,7 +14,8 @@ 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
from .models import ClassificationRule, Event, ManualReportRevision, PendingEvent
from .bursts import burst_intensity, burst_rate
class ClassificationRuleApiTests(TestCase):
@@ -54,6 +55,24 @@ class ManualPendingEventTests(TestCase):
def setUp(self):
self.client.cookies["django_language"] = "en"
def test_manual_visual_confirmation_is_optional_and_survives_review(self):
url = reverse("fireworks_detect:submit_manual_pending")
for posted, expected in (({}, False), ({"visually_confirmed": "on"}, True)):
with self.subTest(confirmed=expected):
response = self.client.post(url, {"occurrences": "1", **posted})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.latest("pk")
self.assertEqual(pending.visually_confirmed, expected)
self.assertContains(response, f"Visually confirmed: {'Yes' if expected else 'No'}")
update_url = reverse("fireworks_detect:update_manual_pending", args=[pending.pk])
self.client.post(update_url, {"occurrences": "2"})
pending.refresh_from_db()
self.assertEqual(pending.visually_confirmed, expected)
event = pending.approve()
self.assertEqual(event.visually_confirmed, expected)
self.assertContains(self.client.get(reverse("fireworks_detect:event_detail", args=[event.pk])),
f"Visually confirmed</strong><span>{'Yes' if expected else 'No'}")
def test_manual_report_creates_a_timestamped_pending_event(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "4",
@@ -88,6 +107,114 @@ class ManualPendingEventTests(TestCase):
self.assertContains(response, 'data-result="error"', status_code=400)
self.assertFalse(PendingEvent.objects.exists())
def test_burst_boundaries_and_intensity_rates(self):
for count, duration, category in ((1, 15, None), (2, 15, None), (3, 15, "light"), (10, 15, "intense"), (10, 30, "moderate"), (10, 60, "light")):
with self.subTest(count=count, duration=duration):
pending = PendingEvent(occurrences=count, observation_duration_minutes=duration, observation_duration_kind="estimated")
self.assertEqual(pending.is_burst, count >= 3)
self.assertEqual(pending.burst_intensity, category)
self.assertEqual(burst_rate(10, 30), Decimal("5"))
self.assertEqual(burst_intensity(10, None), None)
def test_server_rendered_quick_report_with_estimated_duration_and_approximate_time(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "10", "occurred_at": "2026-10-09T20:30", "time_approximate": "on",
"duration_minutes": "30", "duration_confirmed": "on",
})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Burst Event")
self.assertContains(response, "Moderate")
pending = PendingEvent.objects.get()
self.assertEqual(pending.occurrences, 10)
self.assertEqual(pending.observation_duration_minutes, 30)
self.assertEqual(pending.observation_duration_kind, "estimated")
self.assertTrue(pending.occurrence_time_approximate)
self.assertNotEqual(pending.captured_at, pending.created_at)
self.assertEqual(pending.bangs_per_15_minutes, Decimal("5"))
reviewed = pending.approve()
self.assertEqual(reviewed.observation_duration_minutes, 30)
self.assertEqual(reviewed.captured_at, pending.captured_at)
self.assertEqual(reviewed.submitted_at, pending.created_at)
def test_unaccepted_window_has_no_intensity_and_legacy_burst_stays_compatible(self):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {"occurrences": "3", "duration_minutes": "15"})
self.assertEqual(response.status_code, 200)
pending = PendingEvent.objects.get()
self.assertTrue(pending.is_burst)
self.assertIsNone(pending.observation_duration_minutes)
self.assertIsNone(pending.burst_intensity)
old = Event.objects.create(occurrences=10, original_filename="old report", classifier_response={}, source_type="manual")
self.assertTrue(old.is_burst)
self.assertIsNone(old.burst_intensity)
accepted = self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "3", "duration_confirmed": "on",
})
self.assertEqual(accepted.status_code, 200)
self.assertEqual(PendingEvent.objects.latest("pk").observation_duration_minutes, 15)
measured = Event.objects.create(occurrences=10, original_filename="measured", classifier_response={},
observation_duration_minutes=30, observation_duration_kind="measured")
self.assertEqual(measured.burst_intensity, "moderate")
self.assertEqual(measured.observation_duration_kind, "measured")
def test_session_scoped_count_edits_recalculate_and_preserve_original_time(self):
self.client.post(reverse("fireworks_detect:submit_manual_pending"), {
"occurrences": "2", "occurred_at": "2026-10-09T20:30",
})
pending = PendingEvent.objects.get()
occurred_at, submitted_at = pending.captured_at, pending.created_at
url = reverse("fireworks_detect:update_manual_pending", args=[pending.pk])
response = self.client.post(url, {"occurrences": "3", "duration_minutes": "15", "duration_confirmed": "on"})
self.assertEqual(response.status_code, 200)
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "light")
self.client.post(url, {"occurrences": "10", "duration_minutes": "10", "duration_confirmed": "on"})
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "intense")
self.client.post(url, {"occurrences": "10", "duration_minutes": "30", "duration_confirmed": "on"})
pending.refresh_from_db()
self.assertEqual(pending.burst_intensity, "moderate")
self.client.post(url, {"occurrences": "2"})
pending.refresh_from_db()
self.assertFalse(pending.is_burst)
self.assertIsNone(pending.burst_intensity)
self.assertEqual(pending.captured_at, occurred_at)
self.assertEqual(pending.created_at, submitted_at)
self.assertEqual(ManualReportRevision.objects.filter(original_pending_id=pending.pk).count(), 4)
from django.test import Client
self.assertEqual(Client().post(url, {"occurrences": "10"}).status_code, 404)
def test_invalid_estimated_duration_and_future_occurrence_are_rejected(self):
for data in (
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "0"},
{"occurrences": "10", "duration_confirmed": "on", "duration_minutes": "1441"},
{"occurrences": "10", "occurred_at": (timezone.localtime() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")},
):
with self.subTest(data=data):
response = self.client.post(reverse("fireworks_detect:submit_manual_pending"), data)
self.assertEqual(response.status_code, 400)
self.assertFalse(PendingEvent.objects.exists())
def test_map_data_exposes_derived_burst_fields_without_precise_location(self):
event = Event.objects.create(
original_filename="manual burst", classifier_response={}, source_type="manual", occurrences=10,
latitude=Decimal("52.123456"), longitude=Decimal("5.987654"),
observation_duration_minutes=30, observation_duration_kind="estimated",
occurrence_time_approximate=True, captured_at=timezone.now() - timedelta(hours=1),
)
from .views import _events_for_map
mapped, _ = _events_for_map({"date_from": None, "date_to": None, "visual": "all", "source": "manual"})
item = next(item for item in mapped if item["occurrences"] == 10)
self.assertEqual(item["event_kind"], "burst")
self.assertEqual(item["observation_duration_kind"], "estimated")
self.assertEqual(item["bangs_per_15_minutes"], 5.0)
self.assertEqual(item["burst_intensity"], "moderate")
self.assertTrue(item["occurrence_time_approximate"])
self.assertIsNone(item["submitted_on"])
self.assertNotIn("latitude", item)
self.assertNotIn("longitude", item)
def test_manual_report_accepts_optional_wav_on_the_same_pending_event(self):
from tempfile import TemporaryDirectory
@@ -220,7 +347,7 @@ class ManualPendingEventTests(TestCase):
)
list_response = self.client.get(reverse("fireworks_detect:events_list"))
self.assertContains(list_response, "Manual fireworks report")
self.assertContains(list_response, "Burst Event")
self.assertContains(list_response, "5 occurrences")
self.assertContains(list_response, "Back garden")
@@ -238,7 +365,7 @@ class ManualPendingEventTests(TestCase):
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):
def test_map_source_filter_separates_reviewed_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(
@@ -271,12 +398,41 @@ class ManualPendingEventTests(TestCase):
self.assertContains(response, '"direction_degrees": 237.0')
self.assertContains(response, "data-h3-resolution")
self.assertContains(response, 'type="module"')
self.assertContains(response, "sensor layer disabled")
self.assertContains(response, "Sensor events — coming soon")
self.assertContains(response, 'name="source"')
self.assertContains(response, "Sensor events")
self.assertNotContains(response, sensor_cell)
self.assertNotContains(response, "52.123456")
self.assertNotContains(response, "H3 demo cell")
sensor_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
self.assertEqual(len(sensor_response.context["map_events"]), 1)
self.assertEqual(sensor_response.context["map_events"][0]["source_type"], "sensor")
self.assertContains(sensor_response, sensor_cell)
self.assertNotContains(sensor_response, manual_cell)
self.assertNotContains(sensor_response, "53.123456")
both_response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "all"})
self.assertEqual(len(both_response.context["map_events"]), 2)
self.assertContains(both_response, manual_cell)
self.assertContains(both_response, sensor_cell)
def test_sensor_map_excludes_pending_and_device_only_locations(self):
pending_cell = cell_from_coordinates(Decimal("51.876543"), Decimal("5.123456"))
PendingEvent.objects.create(
original_filename="pending.wav", classifier_response={},
source_type=PendingEvent.SourceType.SENSOR, h3_cell=pending_cell,
)
Event.objects.create(
original_filename="unlocated.wav", classifier_response={},
source_type=Event.SourceType.SENSOR,
device_metadata={"latitude": "52.654321", "longitude": "5.654321"},
)
response = self.client.get(reverse("fireworks_detect:map"), {"range": "all", "source": "sensor"})
self.assertEqual(response.context["map_events"], [])
self.assertNotContains(response, pending_cell)
self.assertNotContains(response, "52.654321")
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"))
+13
View File
@@ -1,6 +1,7 @@
from django.urls import path
from .views import (
burst_session_start, burst_session_detail, burst_session_stop, burst_capture_audio,
classify_audio,
classify_upload,
event_audio,
@@ -12,14 +13,25 @@ from .views import (
pending_audio,
manual_direction_panel,
submit_manual_pending_event,
update_manual_pending_event,
submit_pending_event,
sensor_heartbeat,
submit_sensor_pending,
browser_processing_policy,
)
from . import note_views
app_name = "fireworks_detect"
urlpatterns = [
path("burst-sessions/", burst_session_start, name="burst_start"),
path("burst-sessions/<uuid:session_id>/", burst_session_detail, name="burst_detail"),
path("burst-sessions/<uuid:session_id>/stop/", burst_session_stop, name="burst_stop"),
path("admin-audio/burst/<int:capture_id>/", burst_capture_audio, name="burst_capture_audio"),
path("notes/", note_views.notes, name="field_notes"),
path("notes/<uuid:context_id>/link/", note_views.link_note, name="link_field_note"),
path("notes/export/<str:format>/", note_views.export_notes, name="export_field_notes"),
path("", fireworks_view, name="fireworks"),
path("map/", fireworks_map_view, name="map"),
path("classify/", classify_audio, name="classify"),
@@ -28,6 +40,7 @@ urlpatterns = [
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("submit-manual-pending/<int:event_id>/update/", update_manual_pending_event, name="update_manual_pending"),
path("manual-direction/", manual_direction_panel, name="manual_direction_panel"),
path("events/", events_view, name="events"),
path("events/list/", events_list, name="events_list"),
+392 -7
View File
@@ -1,4 +1,11 @@
import math
import hashlib
import re
import wave
from datetime import datetime, timezone as datetime_timezone
from django.core.cache import cache
from django.db import IntegrityError, transaction
from django.utils.dateparse import parse_datetime
from datetime import timedelta
from decimal import Decimal, InvalidOperation
import json
@@ -10,6 +17,7 @@ from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.http import FileResponse, Http404, JsonResponse
from django.core import signing
from django.shortcuts import get_object_or_404, redirect, render
@@ -22,7 +30,9 @@ from django.views.decorators.http import require_http_methods
from .h3_utils import cell_boundary, cell_center, cell_from_coordinates, h3_resolution
from .browser_policy import advisory_browser_metadata, browser_config, browser_policy
from .models import BrowserProcessingSettings, ClassificationRule, Event, PendingEvent, Sensor
from .models import BrowserProcessingSettings, BurstCapture, BurstSession, ClassificationRule, Event, ManualReportRevision, PendingEvent, Sensor, SensorSubmission
from .field_notes import draft_token
from .bursts import BURST_MIN_BANGS, DEFAULT_ESTIMATED_DURATION_MINUTES, burst_intensity, burst_rate
CLASSIFIER_URL = "http://192.168.1.122:5000/classify"
@@ -40,6 +50,79 @@ AUDIO_EXTENSIONS = {".aac", ".aif", ".aiff", ".flac", ".m4a", ".mp3", ".ogg", ".
logger = logging.getLogger(__name__)
def _burst_event(session, kind, **details):
events = session.diagnostic_events
if len(events) >= 200:
events = events[:20] + events[-179:]
events.append({"kind": kind, "server_at": timezone.now().isoformat(), **details})
session.diagnostic_events = events
@login_required
@require_http_methods(["POST"])
def burst_session_start(request):
try:
minutes = int(request.POST.get("maximum_minutes", 15))
except ValueError:
minutes = 0
if minutes not in (10, 15, 20):
return JsonResponse({"error": "Choose 10, 15 or 20 minutes."}, status=400)
session = BurstSession.objects.create(owner=request.user, maximum_minutes=minutes)
_burst_event(session, "started")
session.save(update_fields=["diagnostic_events"])
return JsonResponse({"id": str(session.pk), "started_at": session.started_at.isoformat()})
@login_required
@require_http_methods(["GET", "POST"])
def burst_session_detail(request, session_id):
session = get_object_or_404(BurstSession, pk=session_id, owner=request.user)
if request.method == "GET":
return JsonResponse({"id": str(session.pk), "status": session.status, "last_seen_at": session.last_seen_at.isoformat() if session.last_seen_at else None, "last_audio_at": session.last_audio_at.isoformat() if session.last_audio_at else None, "timeout_at": session.timeout_at.isoformat() if session.timeout_at else None, "events": session.diagnostic_events})
if len(request.body) > 1024:
return JsonResponse({"error": "Heartbeat is too large."}, status=413)
try:
payload = json.loads(request.body)
except (ValueError, UnicodeDecodeError):
return JsonResponse({"error": "Invalid heartbeat."}, status=400)
if session.ended_at or timezone.now() > session.started_at + timedelta(minutes=21):
return JsonResponse({"error": "Session has ended."}, status=409)
sequence = payload.get("sequence")
frames = payload.get("audio_frames")
elapsed = payload.get("elapsed_ms")
if not isinstance(sequence, int) or not session.last_sequence < sequence <= session.last_sequence + 1000 or not isinstance(frames, int) or not session.last_audio_frame <= frames <= 100_000_000 or not isinstance(elapsed, (int, float)) or not math.isfinite(elapsed) or not 0 <= elapsed <= 21 * 60 * 1000 or payload.get("track_state") not in ("live", "ended", "muted") or payload.get("visibility") not in ("visible", "hidden"):
return JsonResponse({"error": "Stale or invalid heartbeat."}, status=400)
now = timezone.now()
previous_timeout_at = session.timeout_at.isoformat() if session.timeout_at else None
previous_seen_at = session.last_seen_at.isoformat() if session.last_seen_at else None
if session.timeout_at:
_burst_event(session, "heartbeat_recovered", previous_timeout_at=session.timeout_at.isoformat())
if frames == session.last_audio_frame and session.last_seen_at:
_burst_event(session, "heartbeat_without_audio_progress")
if frames > session.last_audio_frame:
session.last_audio_at = now
session.last_audio_frame = frames
session.last_seen_at = now
session.last_sequence = sequence
session.timeout_at = None
session.status = "listening"
_burst_event(session, "heartbeat", sequence=sequence, audio_frames=frames, client_wall_at=str(payload.get("wall_at", ""))[:40], client_elapsed_ms=elapsed, track_state=str(payload.get("track_state", ""))[:20], visibility=str(payload.get("visibility", ""))[:20])
session.save()
return JsonResponse({"received_at": now.isoformat(), "last_audio_at": session.last_audio_at.isoformat() if session.last_audio_at else None, "previous_timeout_at": previous_timeout_at, "previous_seen_at": previous_seen_at})
@login_required
@require_http_methods(["POST"])
def burst_session_stop(request, session_id):
session = get_object_or_404(BurstSession, pk=session_id, owner=request.user)
if not session.ended_at:
session.ended_at = timezone.now()
session.status = "review"
_burst_event(session, "explicit_stop")
session.save()
return JsonResponse({"status": session.status})
@require_http_methods(["GET"])
@never_cache
def browser_processing_policy(request):
@@ -78,17 +161,24 @@ def _map_filters(request):
visual = request.GET.get("visual", "all")
if visual not in {"all", "yes", "no"}:
visual = "all"
source = request.GET.get("source", "manual")
if source not in {"manual", "sensor", "all"}:
source = "manual"
return {
"date_from": date_from,
"date_to": date_to,
"range": selected_range,
"visual": visual,
"source": source,
}
def _events_for_map(filters):
"""Create privacy-preserving map data for reviewed manual reports only."""
events = Event.objects.filter(source_type=Event.SourceType.MANUAL)
"""Create H3 map data for reviewed events with a stored, trusted location."""
source = filters.get("source", "manual")
events = Event.objects.all()
if source != "all":
events = events.filter(source_type=source)
if filters["date_from"]:
events = events.filter(created_at__date__gte=filters["date_from"])
if filters["date_to"]:
@@ -102,7 +192,8 @@ def _events_for_map(filters):
mapped_events = []
for event in events.values(
"h3_cell", "latitude", "longitude", "occurrences", "visually_confirmed",
"direction_degrees", "direction_accuracy_degrees", "created_at",
"direction_degrees", "direction_accuracy_degrees", "created_at", "captured_at", "submitted_at", "source_type",
"observation_duration_minutes", "observation_duration_kind", "occurrence_time_approximate",
):
# 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"])
@@ -117,13 +208,26 @@ def _events_for_map(filters):
"center": center,
"reports": 0,
"occurrences": 0,
"manual_reports": 0,
"sensor_reports": 0,
})
aggregate["reports"] += 1
aggregate["occurrences"] += event["occurrences"]
aggregate[f'{event["source_type"]}_reports'] += 1
rate = burst_rate(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None
mapped_events.append({
"cell": h3_cell,
"center": center,
"source_type": event["source_type"],
"occurrences": event["occurrences"],
"event_kind": "burst" if event["occurrences"] >= BURST_MIN_BANGS else "ordinary",
"observation_duration_minutes": event["observation_duration_minutes"],
"observation_duration_kind": event["observation_duration_kind"],
"bangs_per_15_minutes": float(rate) if rate is not None else None,
"burst_intensity": burst_intensity(event["occurrences"], event["observation_duration_minutes"]) if event["observation_duration_kind"] else None,
"occurrence_time_approximate": event["occurrence_time_approximate"],
"occurred_on": (event["captured_at"] or event["created_at"]).date().isoformat(),
"submitted_on": event["submitted_at"].date().isoformat() if event["submitted_at"] else None,
"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(),
@@ -145,17 +249,21 @@ def fireworks_map_view(request):
"h3_cells": h3_cells,
"map_events": map_events,
"mapped_event_count": len(map_events),
"map_source": filters["source"],
"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"],
"source": filters["source"],
},
})
@never_cache
def dashboard_view(request):
from .field_notes import draft_token
from .forms import FieldNoteForm
map_events, h3_cells = _events_for_map({
"date_from": None,
"date_to": None,
@@ -163,6 +271,10 @@ def dashboard_view(request):
"visual": "all",
})
return render(request, "fireworks_detect/dashboard.html", {
"note_token": draft_token(request.user),
"note_form": FieldNoteForm(),
"note_mode": "draft",
"note_panel_id": "live-field-notes",
"h3_resolution": h3_resolution(),
"h3_cells": h3_cells,
"map_events": map_events,
@@ -173,7 +285,7 @@ def dashboard_view(request):
def events_view(request):
return render(request, "fireworks_detect/events.html")
return render(request, "fireworks_detect/events.html", {"events": Event.objects.all()[:30]})
def _classification_context(payload):
@@ -374,7 +486,48 @@ def manual_direction_panel(request):
@require_http_methods(["POST"])
@never_cache
@transaction.atomic
def submit_manual_pending_event(request):
burst_id = request.POST.get("burst_session_id")
burst_session = None
burst_files = []
if burst_id:
if not request.user.is_authenticated:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Sign in to submit a Burst Listening session.")}, status=403)
burst_session = get_object_or_404(BurstSession.objects.select_for_update(), pk=burst_id, owner=request.user)
if burst_session.pending_event_id or burst_session.status not in ("review", "interrupted", "expired"):
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("This burst session cannot be submitted again.")}, status=409)
burst_files = request.FILES.getlist("burst_audio")
if not 1 <= len(burst_files) <= 30 or sum(clip.size for clip in burst_files) > 60 * 1024 * 1024:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("A burst session needs 1 to 30 clips.")}, status=400)
for clip in burst_files:
header = clip.read(12)
clip.seek(0)
if clip.size > 5 * 1024 * 1024 or clip.content_type not in ("audio/wav", "audio/wave", "audio/x-wav") or header[:4] != b"RIFF" or header[8:] != b"WAVE":
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Each burst clip must be a WAV file no larger than 5 MiB.")}, status=400)
try:
primary_index = int(request.POST.get("burst_primary", 0))
capture_metadata = json.loads(request.POST.get("burst_captures", "[]"))
except (ValueError, TypeError):
primary_index, capture_metadata = -1, []
if not 0 <= primary_index < len(burst_files) or len(capture_metadata) != len(burst_files):
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Burst clip metadata is incomplete.")}, status=400)
try:
browser_predictions = json.loads(request.POST.get("burst_predictions", "[]"))
except (ValueError, TypeError):
browser_predictions = []
if not isinstance(browser_predictions, list) or not 1 <= len(browser_predictions) <= 5 or any(
not isinstance(item, dict) or not isinstance(item.get("class"), str) or len(item["class"]) > 100 or
not isinstance(item.get("score"), (int, float)) or not math.isfinite(item["score"]) or not 0 <= item["score"] <= 1
for item in browser_predictions
):
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Primary clip classification is missing or invalid.")}, status=400)
for item in capture_metadata:
captured = parse_datetime(str(item.get("captured_at", ""))) if isinstance(item, dict) else None
duration = item.get("duration_seconds") if isinstance(item, dict) else None
if not captured or not isinstance(duration, (int, float)) or not 0 < duration <= 20:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": _("Burst clip timing is invalid.")}, status=400)
request.FILES["audio"] = burst_files[primary_index]
try:
occurrences = int(request.POST.get("occurrences", ""))
except (TypeError, ValueError):
@@ -388,6 +541,10 @@ def submit_manual_pending_event(request):
status=400,
)
details, error = _manual_observation_details(request, occurrences)
if error:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
uploaded_file = request.FILES.get("audio")
if uploaded_file:
if uploaded_file.size > MAX_AUDIO_SIZE or uploaded_file.content_type not in ("audio/wav", "audio/wave", "audio/x-wav"):
@@ -402,28 +559,125 @@ def submit_manual_pending_event(request):
h3_cell = cell_from_coordinates(latitude, longitude)
direction_degrees, direction_accuracy_degrees = _manual_direction(request)
# Reject stale/foreign contexts before FileField writes an audio file.
note_token = request.POST.get("field_note_context")
if request.user.is_authenticated and note_token:
from .field_notes import context_for_token
from django.core.exceptions import PermissionDenied
note_context = context_for_token(request.user, note_token)
if note_context.event_id or note_context.pending_event_id:
raise PermissionDenied("This note context already belongs to a report. Reload before reporting again.")
pending = PendingEvent.objects.create(
audio_file=uploaded_file,
original_filename="Manual fireworks report",
classifier_response={},
classifier_response={"predictions": browser_predictions, "classification_source": "browser_yamnet_advisory"} if burst_session else {},
source_type=PendingEvent.SourceType.MANUAL,
occurrences=occurrences,
**details,
latitude=latitude,
longitude=longitude,
h3_cell=h3_cell or "",
visually_confirmed=request.POST.get("visually_confirmed") == "on",
direction_degrees=direction_degrees,
direction_accuracy_degrees=direction_accuracy_degrees,
direction_source="device_compass" if direction_degrees is not None else "",
)
if burst_session:
burst_session.pending_event = pending
burst_session.status = "submitted"
_burst_event(burst_session, "submitted", capture_count=len(burst_files))
burst_session.save()
for index, (clip, item) in enumerate(zip(burst_files, capture_metadata)):
# The Pending record owns the primary file; child captures own attachments.
BurstCapture.objects.create(
session=burst_session, captured_at=parse_datetime(item["captured_at"]),
duration_seconds=item["duration_seconds"],
audio_file=pending.audio_file.name if index == primary_index else clip,
is_primary=index == primary_index,
)
from .field_notes import bind_report
bind_report(request.user, request.POST.get("field_note_context"), pending)
owned = request.session.get("manual_pending_ids", [])
request.session["manual_pending_ids"] = (owned + [pending.pk])[-20:]
direction_names = {
"N": _("North"), "NE": _("Northeast"), "E": _("East"), "SE": _("Southeast"),
"S": _("South"), "SW": _("Southwest"), "W": _("West"), "NW": _("Northwest"),
}
return render(request, "fireworks_detect/manual_pending_submission.html", {
"pending": pending,
"editable": True,
"next_note_token": draft_token(request.user),
"direction_label": direction_names.get(pending.direction_cardinal) if direction_degrees is not None else "",
})
def _manual_observation_details(request, occurrences):
raw_time = request.POST.get("occurred_at", "").strip()
if raw_time:
occurred_at = parse_datetime(raw_time)
if occurred_at is None:
return None, _("Enter a valid occurrence date and time.")
if timezone.is_naive(occurred_at):
occurred_at = timezone.make_aware(occurred_at, timezone.get_current_timezone())
if occurred_at > timezone.now() + timedelta(minutes=5):
return None, _("Occurrence time cannot be in the future.")
else:
occurred_at = timezone.now()
details = {
"captured_at": occurred_at,
"occurrence_time_approximate": request.POST.get("time_approximate") == "on",
"observation_duration_minutes": None,
"observation_duration_kind": "",
}
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
raw_duration = request.POST.get("duration_minutes", "").strip()
try:
duration = int(raw_duration) if raw_duration else DEFAULT_ESTIMATED_DURATION_MINUTES
except ValueError:
return None, _("Enter a duration between 1 and 1,440 minutes.")
if not 1 <= duration <= 1440:
return None, _("Enter a duration between 1 and 1,440 minutes.")
details["observation_duration_minutes"] = duration
details["observation_duration_kind"] = PendingEvent.DurationKind.ESTIMATED
return details, None
@require_http_methods(["POST"])
@never_cache
def update_manual_pending_event(request, event_id):
if event_id not in request.session.get("manual_pending_ids", []):
raise Http404
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)
_, error = _manual_observation_details(request, occurrences)
if error:
return render(request, "fireworks_detect/manual_pending_submission.html", {"error": error}, status=400)
# The occurrence time and location belong to the original observation.
duration = None
kind = ""
if occurrences >= BURST_MIN_BANGS and request.POST.get("duration_confirmed") == "on":
raw = request.POST.get("duration_minutes", "").strip()
duration = int(raw) if raw else DEFAULT_ESTIMATED_DURATION_MINUTES
kind = PendingEvent.DurationKind.ESTIMATED
with transaction.atomic():
pending = get_object_or_404(PendingEvent.objects.select_for_update(), pk=event_id, source_type=PendingEvent.SourceType.MANUAL)
ManualReportRevision.objects.create(
pending_event=pending, original_pending_id=pending.pk,
previous_occurrences=pending.occurrences, new_occurrences=occurrences,
previous_duration_minutes=pending.observation_duration_minutes,
new_duration_minutes=duration,
)
pending.occurrences = occurrences
pending.observation_duration_minutes = duration
pending.observation_duration_kind = kind
pending.save(update_fields=["occurrences", "observation_duration_minutes", "observation_duration_kind"])
return render(request, "fireworks_detect/manual_pending_submission.html", {"pending": pending, "editable": True, "updated": True})
@never_cache
def events_list(request):
return render(request, "fireworks_detect/events_list.html", {"events": Event.objects.all()[:30]})
@@ -435,7 +689,11 @@ def event_detail(request, 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)
if request.user.is_authenticated:
from .note_views import panel_context
context.update(panel_context(request, {"event": event.pk}))
template = "fireworks_detect/event_detail.html" if request.headers.get("HX-Request") == "true" else "fireworks_detect/event_page.html"
return render(request, template, context)
def _audio_response(record):
@@ -450,6 +708,11 @@ def pending_audio(request, event_id):
return _audio_response(get_object_or_404(PendingEvent, pk=event_id))
@staff_member_required
def burst_capture_audio(request, capture_id):
return _audio_response(get_object_or_404(BurstCapture, pk=capture_id))
@staff_member_required
def event_audio(request, event_id):
return _audio_response(get_object_or_404(Event, pk=event_id))
@@ -500,6 +763,128 @@ def classify_audio(request):
return JsonResponse({**payload, "pending_event_id": pending.pk, "sensor": sensor.name}, status=201)
def _submission_error(code, detail, status=400):
return JsonResponse({"code": code, "detail": detail}, status=status)
@csrf_exempt
@require_http_methods(["POST"])
def submit_sensor_pending(request):
sensor = _sensor_from_request(request)
if sensor is None:
return _submission_error("unauthorized", "A valid sensor API token is required.", 401)
if not sensor.owner_id:
return _submission_error("unowned_sensor", "Sensor has no registered owner.", 403)
if request.POST.get("sensor_id") != str(sensor.pk):
return _submission_error("sensor_mismatch", "sensor_id must match the authenticated sensor.", 403)
event_id = request.POST.get("event_id", "")
if not re.fullmatch(r"[A-Za-z0-9_-]{1,100}", event_id):
return _submission_error("invalid_event_id", "Provide a valid event_id.")
uploaded = request.FILES.get("file")
if uploaded is None:
return _submission_error("missing_file", "Attach PCM WAV as multipart field 'file'.")
if uploaded.size > MAX_AUDIO_SIZE:
return _submission_error("file_too_large", "Audio exceeds 25 MiB.", 413)
if not uploaded.name.lower().endswith(".wav"):
return _submission_error("invalid_audio", "Only PCM WAV is accepted.")
try:
with wave.open(uploaded, "rb") as wav:
if wav.getcomptype() != "NONE" or wav.getnchannels() != 1 or wav.getsampwidth() != 2 or wav.getframerate() != 16000:
raise ValueError("WAV must be 16-bit mono PCM at 16 kHz.")
frames = wav.getnframes()
if len(wav.readframes(frames)) != frames * 2:
raise ValueError("WAV sample data is truncated.")
actual_duration = frames / wav.getframerate()
if not 0.1 <= actual_duration <= 30:
raise ValueError("WAV duration must be between 0.1 and 30 seconds.")
declared_duration = float(request.POST.get("duration_seconds", ""))
if not math.isfinite(declared_duration) or abs(declared_duration - actual_duration) > 0.1:
raise ValueError("duration_seconds does not match the WAV.")
except (wave.Error, EOFError, ValueError, TypeError) as error:
return _submission_error("invalid_audio", str(error))
finally:
uploaded.seek(0)
raw_time = request.POST.get("captured_at", "")
if not raw_time and request.POST.get("time_state") == "unknown":
captured_at = None
else:
try:
captured_at = datetime.fromtimestamp(float(raw_time), datetime_timezone.utc) if re.fullmatch(r"[0-9]{10}(?:\.[0-9]+)?", raw_time) else parse_datetime(raw_time)
if captured_at is None or timezone.is_naive(captured_at):
raise ValueError()
if captured_at > timezone.now() + timedelta(minutes=5):
raise ValueError()
except (ValueError, OverflowError, OSError):
return _submission_error("invalid_capture_time", "Provide a valid UTC captured_at or time_state=unknown.")
firmware = request.POST.get("firmware_version", "")
if not 1 <= len(firmware) <= 64 or not firmware.isprintable():
return _submission_error("invalid_firmware_version", "Provide a printable firmware_version of at most 64 characters.")
metadata = {"time_state": "unknown"} if captured_at is None else {}
for key in ("trigger_type", "signal_rms", "signal_peak", "latitude", "longitude", "capture_started_at", "triggered_at", "queued_at"):
value = request.POST.get(key)
if value is None or value == "":
continue
if key.endswith("_at"):
parsed = parse_datetime(value)
if parsed is None or timezone.is_naive(parsed):
return _submission_error("invalid_metadata", f"Invalid {key}.")
elif key == "trigger_type":
if len(value) > 64 or not value.isprintable():
return _submission_error("invalid_metadata", "Invalid trigger_type.")
else:
try:
number = float(value)
if not math.isfinite(number) or (key.startswith("signal_") and number < 0) or (key == "latitude" and abs(number) > 90) or (key == "longitude" and abs(number) > 180):
raise ValueError()
except ValueError:
return _submission_error("invalid_metadata", f"Invalid {key}.")
metadata[key] = value
digest = hashlib.sha256()
for chunk in uploaded.chunks():
digest.update(chunk)
audio_hash = digest.hexdigest()
uploaded.seek(0)
existing = SensorSubmission.objects.filter(sensor=sensor, event_id=event_id).first()
if existing:
if existing.audio_sha256 != audio_hash:
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True}, status=200)
rate_key = f"sensor-submissions:{sensor.pk}"
if cache.get(rate_key, 0) >= 30:
response = _submission_error("rate_limited", "Sensor submission rate exceeded.", 429)
response["Retry-After"] = "60"
return response
cache.add(rate_key, 0, 60)
try:
cache.incr(rate_key)
except ValueError:
cache.set(rate_key, 1, 60)
body, content_type = _encode_audio_multipart(uploaded)
classifier_request = Request(CLASSIFIER_URL, data=body, headers={"Content-Type": content_type, "Accept": "application/json"}, method="POST")
try:
with urlopen(classifier_request, timeout=60) as response:
payload = json.loads(response.read().decode("utf-8"))
if not isinstance(payload, dict):
raise ValueError("Classifier response must be an object.")
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError):
return _submission_error("classifier_unavailable", "Classification failed; retain the queued recording.", 502)
uploaded.seek(0)
pending = None
try:
with transaction.atomic():
pending = PendingEvent.objects.create(audio_file=uploaded, sensor=sensor, source_type=PendingEvent.SourceType.SENSOR, original_filename=Path(uploaded.name).name[:255], classifier_response=payload, captured_at=captured_at, firmware_version=firmware, device_metadata=metadata)
receipt = SensorSubmission.objects.create(sensor=sensor, event_id=event_id, audio_sha256=audio_hash, pending_event=pending)
except IntegrityError:
if pending and pending.audio_file:
pending.audio_file.storage.delete(pending.audio_file.name)
existing = SensorSubmission.objects.get(sensor=sensor, event_id=event_id)
if existing.audio_sha256 != audio_hash:
return _submission_error("event_id_conflict", "event_id already belongs to different audio.", 409)
return JsonResponse({"submission_id": str(existing.submission_id), "event_id": event_id, "status": "pending" if existing.pending_event_id else "reviewed", "duplicate": True})
sensor.record_heartbeat(submission=True)
return JsonResponse({"submission_id": str(receipt.submission_id), "event_id": event_id, "pending_event_id": pending.pk, "status": "pending", "classification": payload}, status=201)
@csrf_exempt
@require_http_methods(["POST"])
def sensor_heartbeat(request):
+2 -1
View File
@@ -1,2 +1,3 @@
import "../styles/pages/admin-audio-preview.css";
import "../styles/fonts.scss";
import "../styles/pages/admin-audio-preview.scss";
import "../scripts/admin-audio-preview.js";
+2 -1
View File
@@ -1 +1,2 @@
import "../styles/pages/admin-login.css";
import "../styles/fonts.scss";
import "../styles/pages/admin-login.scss";
+12 -8
View File
@@ -1,12 +1,16 @@
import "../styles/components/fireworks-navigation.css";
import "../styles/pages/fireworks-home.css";
import "../styles/pages/map.css";
import "../styles/pages/dashboard.css";
import "../styles/components/burst-listener.css";
import "../styles/components/manual-compass.css";
import "../styles/components/manual-report-structure.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/components/fireworks-navigation.scss";
import "../styles/pages/fireworks-home.scss";
import "../styles/pages/map.scss";
import "../styles/pages/dashboard.scss";
import "../styles/components/burst-listener.scss";
import "../styles/components/manual-compass.scss";
import "../styles/components/manual-report-structure.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/manual-report.js";
import "../scripts/field-notes-dialog.js";
import "../scripts/audio-upload.js";
import "../scripts/event-map.js";
import "../styles/components/field-notes.scss";
+6 -3
View File
@@ -1,4 +1,7 @@
import "../styles/components/fireworks-navigation.css";
import "../styles/pages/events.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/components/fireworks-navigation.scss";
import "../styles/pages/events.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../styles/components/field-notes.scss";
+4 -3
View File
@@ -1,5 +1,6 @@
import "../styles/components/fireworks-navigation.css";
import "../styles/pages/fireworks-home.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/components/fireworks-navigation.scss";
import "../styles/pages/fireworks-home.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/audio-upload.js";
+6 -5
View File
@@ -1,7 +1,8 @@
import "../styles/pages/home.css";
import "../styles/components/burst-listener.css";
import "../styles/components/manual-compass.css";
import "../styles/components/manual-report-structure.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/home.scss";
import "../styles/components/burst-listener.scss";
import "../styles/components/manual-compass.scss";
import "../styles/components/manual-report-structure.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/manual-report.js";
@@ -1,4 +1,5 @@
import "../styles/pages/legacy-fireworks-home.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/legacy-fireworks-home.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/legacy-audio-upload.js";
+3 -2
View File
@@ -1,3 +1,4 @@
import "../styles/pages/login.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/login.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
+4 -3
View File
@@ -1,5 +1,6 @@
import "../styles/components/fireworks-navigation.css";
import "../styles/pages/map.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/components/fireworks-navigation.scss";
import "../styles/pages/map.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/event-map.js";
+3 -2
View File
@@ -1,3 +1,4 @@
import "../styles/pages/member-form.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/member-form.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
+3 -2
View File
@@ -1,3 +1,4 @@
import "../styles/pages/member-list.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/member-list.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
+3 -2
View File
@@ -1,3 +1,4 @@
import "../styles/pages/member-success.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/member-success.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
+3 -2
View File
@@ -1,3 +1,4 @@
import "../styles/pages/not-found.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/not-found.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
+4 -3
View File
@@ -1,5 +1,6 @@
import "../styles/pages/settings.css";
import "../styles/components/fireworks-navigation.css";
import "../styles/theme.css";
import "../styles/fonts.scss";
import "../styles/pages/settings.scss";
import "../styles/components/fireworks-navigation.scss";
import "../styles/theme.scss";
import "../scripts/theme.js";
import "../scripts/user-settings.js";
+27 -9
View File
@@ -1,7 +1,7 @@
class BurstListenerProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.samples = new Float32Array(Math.ceil(sampleRate * 10));
this.samples = new Float32Array(Math.ceil(sampleRate * 20));
this.position = 0;
this.count = 0;
this.interval = 0;
@@ -14,9 +14,15 @@ class BurstListenerProcessor extends AudioWorkletProcessor {
this.eventCount = 0;
this.frame = 0;
this.mode = "listening";
this.burst = false;
this.clipStart = 0;
this.lastHeartbeat = 0;
this.port.onmessage = ({ data }) => {
if (data === "snapshot") this.sendClip(this.count);
if (data === "reset") this.reset();
if (data === "burst") this.burst = true;
if (data === "single") this.burst = false;
if (data === "manual" && this.mode === "listening") this.startCapture();
};
}
@@ -40,9 +46,21 @@ class BurstListenerProcessor extends AudioWorkletProcessor {
this.port.postMessage({ type: "clip", samples: clip, sampleRate }, [clip.buffer]);
}
startCapture() {
this.mode = "tail";
this.clipStart = this.frame;
this.postRoll = Math.round(sampleRate * 2);
this.lastTrigger = this.frame;
this.port.postMessage({ type: "trigger" });
}
process(inputs) {
const channel = inputs[0]?.[0];
if (!channel || this.mode === "captured") return true;
if (this.frame - this.lastHeartbeat >= sampleRate) {
this.lastHeartbeat = this.frame;
this.port.postMessage({ type: "heartbeat", frames: this.frame });
}
for (let i = 0; i < channel.length; i++) {
const value = channel[i];
this.samples[this.position] = value;
@@ -53,21 +71,21 @@ class BurstListenerProcessor extends AudioWorkletProcessor {
this.interval++;
this.frame++;
if (this.mode === "tail") {
if (this.burst && this.frame - this.clipStart > sampleRate * 18) this.postRoll = 1;
if (--this.postRoll === 0) {
this.mode = "captured";
this.sendClip(Math.min(this.count, Math.round(sampleRate * 10)));
break;
this.mode = this.burst ? "listening" : "captured";
this.sendClip(Math.min(this.count, Math.round(sampleRate * (this.burst ? Math.min(20, 8 + (this.frame - this.clipStart) / sampleRate) : 10))));
if (!this.burst) break;
}
}
if (this.interval >= Math.round(sampleRate / 30)) {
const rms = Math.sqrt(this.energy / this.interval);
this.port.postMessage({ type: "level", value: Math.max(rms, this.peak * 0.5) });
if (this.mode === "listening" && this.frame > sampleRate && this.frame - this.lastTrigger > sampleRate * 3
&& rms > Math.max(0.075, this.baseline * 5) && this.peak > 0.16) {
this.mode = "tail";
if (this.mode === "tail" && this.burst && rms > Math.max(0.075, this.baseline * 5) && this.peak > 0.16) {
this.postRoll = Math.round(sampleRate * 2);
this.lastTrigger = this.frame;
this.port.postMessage({ type: "trigger" });
} else if (this.mode === "listening" && this.frame > sampleRate && this.frame - this.lastTrigger > sampleRate * 3
&& rms > Math.max(0.075, this.baseline * 5) && this.peak > 0.16) {
this.startCapture();
} else if (this.mode === "listening") {
this.baseline = this.baseline * 0.98 + Math.min(rms, this.baseline * 2) * 0.02;
}
+226 -9
View File
@@ -2,7 +2,7 @@ const form = document.querySelector("#manual-report-form");
const t = window.BOOMCAST_I18N || {};
export function createBurstListener() {
if (!form) return null;
if (!form || !document.querySelector("#burst-mode")) return null;
const start = document.querySelector("#burst-start");
const container = start.closest(".burst-listener");
const section = start.closest(".manual-report__supporting");
@@ -16,10 +16,102 @@ export function createBurstListener() {
const discard = document.querySelector("#burst-discard");
const stop = document.querySelector("#burst-stop");
const error = document.querySelector("#burst-error");
const mode = document.querySelector("#burst-mode");
const options = document.querySelector("#burst-options");
const maximum = document.querySelector("#burst-maximum");
const testMode = document.querySelector("#burst-test-mode");
const manualCapture = document.querySelector("#burst-manual-capture");
const diagnostics = document.querySelector("#burst-diagnostics");
const exportButton = document.querySelector("#burst-export");
const timelinePanel = document.querySelector("#burst-timeline");
const timelineList = document.querySelector("#burst-timeline-list");
const review = document.querySelector("#burst-review");
const captureList = document.querySelector("#burst-capture-list");
const uploadError = document.querySelector("#burst-upload-error");
const levels = new Float32Array(300);
let levelPosition = 0;
let state = "off";
let stream, context, source, node, silentOutput, previewUrl, captured, pendingSnapshot;
let sessionId, pressedAt, startedAt, lastFrameAt, frameCount = 0, sequence = 0, heartbeatTimer, displayTimer, wakeLock;
let captures = [], timeline = [], interrupted = false, submitting = false;
let serverGap = "";
let clockDriftNoted = false;
const database = () => new Promise((resolve, reject) => {
const open = indexedDB.open("boomcast-burst", 1);
open.onupgradeneeded = () => open.result.createObjectStore("clips", { keyPath: "key" });
open.onsuccess = () => resolve(open.result);
open.onerror = () => reject(open.error);
});
const clipStorage = async (operation, value) => {
const db = await database();
try {
return await new Promise((resolve, reject) => {
const tx = db.transaction("clips", operation === "read" ? "readonly" : "readwrite");
const store = tx.objectStore("clips");
const request = operation === "put" ? store.put(value) : operation === "delete" ? store.delete(value) : store.getAll();
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} finally { db.close(); }
};
const persistClip = (entry, index) => clipStorage("put", { key: `${sessionId}:${index}`, sessionId, index, file: entry.file, at: entry.at, duration: entry.duration, expires: Date.now() + 24 * 3600 * 1000 }).catch(() => { error.textContent = "Temporary clip storage unavailable. Keep this page open until submission."; error.hidden = false; });
const removeClip = (index) => clipStorage("delete", `${sessionId}:${index}`).catch(() => {});
const csrf = form.querySelector('[name="csrfmiddlewaretoken"]')?.value || "";
mode.addEventListener("change", () => { options.hidden = !mode.checked; });
const api = async (path, body = {}) => {
const response = await fetch(path, { method: "POST", credentials: "same-origin", headers: { "X-CSRFToken": csrf, ...(body instanceof FormData ? {} : { "Content-Type": "application/json" }) }, body: body instanceof FormData ? body : JSON.stringify(body) });
if (response.redirected && response.url.includes("/login")) throw new Error("Sign in before starting Burst Listening.");
const data = await response.json();
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
return data;
};
const sessionUrl = () => `/fireworks/burst-sessions/${sessionId}/`;
const log = (kind, extra = {}) => {
if (!mode.checked) return;
timeline.push({ kind, wall_at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - pressedAt), ...extra });
if (timeline.length > 250) timeline = [...timeline.slice(0, 20), ...timeline.slice(-230)];
const latest = timeline.at(-1);
const row = document.createElement("li");
row.textContent = `${latest.wall_at} · ${latest.kind}${latest.last_confirmed_active ? ` · last active ${latest.last_confirmed_active}` : ""}${latest.first_observed_inactive ? ` · first observed inactive ${latest.first_observed_inactive}` : ""}`;
timelineList.append(row);
while (timelineList.childElementCount > 250) timelineList.children[20]?.remove();
try { localStorage.setItem(`boomcast-burst-${sessionId || "starting"}`, JSON.stringify({ sessionId, timeline, lastFrameAt, frameCount, interrupted })); } catch (_) { /* storage optional */ }
};
const updateDiagnostics = () => {
if (!mode.checked || !pressedAt) return;
const elapsed = Math.floor((Date.now() - startedAt) / 1000);
if (!clockDriftNoted && Math.abs((Date.now() - startedAt) - (performance.now() - pressedAt)) > 5000) {
clockDriftNoted = true; log("clock_disagreement", { note: "Wall and monotonic elapsed time differ; an exact interruption time cannot be inferred." });
}
diagnostics.textContent = `${interrupted ? "Interrupted" : state === "review" ? "Review" : "Listening"} · ${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, "0")} · ${captures.length} clips · Last confirmed microphone activity: ${lastFrameAt || "none yet"}${serverGap}`;
if (!interrupted && state !== "review" && elapsed >= Number(maximum.value) * 60) { log("auto_stop"); end(); }
};
const sendHeartbeat = async () => {
if (!sessionId || state === "off" || state === "review") return;
try {
const receipt = await api(sessionUrl(), { sequence: ++sequence, wall_at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - pressedAt), audio_frames: frameCount, track_state: stream?.getAudioTracks()[0]?.readyState || "ended", visibility: document.visibilityState });
log("heartbeat_received", { audio_frames: frameCount, last_confirmed_audio_at: lastFrameAt, server_at: receipt.received_at });
if (receipt.previous_timeout_at) {
log("server_heartbeat_recovered", { last_server_heartbeat: receipt.previous_seen_at, timeout_detected_at: receipt.previous_timeout_at, first_recovered_at: receipt.received_at });
serverGap = ` · Server gap: last received ${receipt.previous_seen_at}, timeout detected ${receipt.previous_timeout_at}, recovered ${receipt.received_at}. Microphone coverage during this gap is uncertain.`;
updateDiagnostics();
}
} catch (cause) { log("heartbeat_error", { message: cause.message }); }
};
const renderCaptures = () => {
captureList.replaceChildren();
captures.forEach((entry, index) => {
const item = document.createElement("li");
const label = document.createElement("span"); label.textContent = `${new Date(entry.at).toLocaleTimeString()} · ${entry.duration.toFixed(1)}s `;
const audio = document.createElement("audio"); audio.controls = true; audio.src = entry.url;
const choice = document.createElement("label");
const radio = document.createElement("input"); radio.type = "radio"; radio.name = "burst-primary-choice"; radio.checked = index === 0; radio.value = String(index);
choice.append(radio, " Primary clip ");
const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Delete";
remove.addEventListener("click", async () => { const oldLastIndex = captures.length - 1; URL.revokeObjectURL(entry.url); captures.splice(index, 1); await removeClip(oldLastIndex); for (const [position, clip] of captures.entries()) await persistClip(clip, position); renderCaptures(); updateDiagnostics(); });
item.append(label, audio, choice, remove); captureList.append(item);
});
};
function draw() {
const ctx = canvas.getContext("2d");
@@ -48,11 +140,11 @@ export function createBurstListener() {
state = next;
if (container) container.dataset.state = next;
if (section) section.dataset.state = next;
if (stateLabel) stateLabel.textContent = next === "listening" ? (t.listeningNextBang || "Listening for the next bang") : next === "tail" ? (t.soundDetected || "Sound detected") : next === "captured" ? (t.soundCaptured || "Sound captured") : (t.notListening || "Not listening");
if (stateLabel) stateLabel.textContent = next === "review" ? "Review captures" : next === "listening" ? (t.listeningNextBang || "Listening for the next bang") : next === "tail" ? (t.soundDetected || "Sound detected") : next === "captured" ? (t.soundCaptured || "Sound captured") : (t.notListening || "Not listening");
start.hidden = next !== "off";
panel.hidden = next === "off";
panel.hidden = next === "off" && !(mode.checked && sessionId);
resume.hidden = discard.hidden = next !== "captured";
heading.textContent = next === "captured" ? (t.soundCaptured || "Sound captured") : next === "tail" ? (t.soundDetectedFinishing || "Sound detected — finishing clip…") : (t.listeningNextSound || "Listening for the next sound…");
heading.textContent = next === "review" ? "Review captures before submitting" : next === "captured" ? (t.soundCaptured || "Sound captured") : next === "tail" ? (t.soundDetectedFinishing || "Sound detected — finishing clip…") : (t.listeningNextSound || "Listening for the next sound…");
detail.textContent = next === "listening" ? (t.keepingRecentAudio || "Keeping the most recent ~10 seconds") : next === "captured" ? (t.previewClipOrSend || "Preview the clip or send your report.") : "";
}
@@ -78,18 +170,37 @@ export function createBurstListener() {
}
async function begin() {
if (mode.checked) { pressedAt = performance.now(); startedAt = Date.now(); timeline = []; timelineList.replaceChildren(); captures = []; interrupted = false; serverGap = ""; clockDriftNoted = false; frameCount = sequence = 0; log("listen_pressed"); diagnostics.hidden = exportButton.hidden = timelinePanel.hidden = false; review.hidden = true; manualCapture.hidden = false; mode.disabled = maximum.disabled = testMode.disabled = true; }
error.hidden = true;
start.disabled = true;
if (container) container.dataset.state = "starting";
if (section) section.dataset.state = "starting";
if (stateLabel) stateLabel.textContent = t.startingMicrophone || "Starting microphone…";
try {
if (mode.checked) {
const data = new FormData(); data.append("maximum_minutes", maximum.value);
const started = await api("/fireworks/burst-sessions/", data); sessionId = started.id; localStorage.setItem("boomcast-burst-active", sessionId); log("server_session_created");
heartbeatTimer = window.setInterval(sendHeartbeat, 5000);
displayTimer = window.setInterval(updateDiagnostics, 1000);
}
if (!navigator.mediaDevices?.getUserMedia || !window.AudioWorkletNode) throw new Error("Microphone listening is unavailable in this browser or connection.");
stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 }, video: false });
log("microphone_permission_granted");
if (mode.checked) {
log("stream_acquired");
if (testMode.value === "wake_lock" && navigator.wakeLock?.request) {
try { wakeLock = await navigator.wakeLock.request("screen"); log("wake_lock_acquired"); wakeLock.addEventListener("release", () => log("wake_lock_released")); } catch (cause) { log("wake_lock_error", { message: cause.message }); }
}
const track = stream.getAudioTracks()[0];
track.addEventListener("mute", () => interrupt("track_muted"));
track.addEventListener("ended", () => interrupt("track_ended"));
track.addEventListener("unmute", () => log("track_unmuted"));
}
context = new AudioContext();
await context.audioWorklet.addModule(new URL("./burst-listener-worklet.js", import.meta.url));
source = context.createMediaStreamSource(stream);
node = new AudioWorkletNode(context, "burst-listener");
node.port.postMessage(mode.checked ? "burst" : "single");
silentOutput = context.createGain();
silentOutput.gain.value = 0;
node.port.onmessage = ({ data }) => {
@@ -98,12 +209,24 @@ export function createBurstListener() {
levelPosition = (levelPosition + 1) % levels.length;
draw();
} else if (data.type === "trigger" && state === "listening") {
log("capture_start");
setState("tail");
} else if (data.type === "heartbeat") {
if (mode.checked && lastFrameAt && Date.now() - Date.parse(lastFrameAt) > 10000) {
interrupt("audio_frame_gap_after_resume");
return;
}
frameCount = data.frames;
lastFrameAt = new Date().toISOString();
if (frameCount === data.frames && !timeline.some((item) => item.kind === "first_audio_frames")) log("first_audio_frames");
} else if (data.type === "clip") {
const file = new File([wav(data.samples, data.sampleRate)], filename(), { type: "audio/wav" });
if (pendingSnapshot) {
pendingSnapshot(file);
pendingSnapshot = null;
} else if (mode.checked && (state === "tail" || state === "listening")) {
if (captures.length < 30) { const entry = { file, url: URL.createObjectURL(file), at: new Date().toISOString(), duration: data.samples.length / data.sampleRate }; captures.push(entry); persistClip(entry, captures.length - 1); }
log("capture_end", { count: captures.length }); renderCaptures(); updateDiagnostics(); setState("listening");
} else if (state === "tail") {
clearClip();
captured = file;
@@ -117,14 +240,23 @@ export function createBurstListener() {
source.connect(node);
node.connect(silentOutput).connect(context.destination);
await context.resume();
log("audio_context_running");
context.addEventListener("statechange", () => { log(`audio_context_${context.state}`); if (context.state === "suspended") interrupt("audio_context_suspended"); });
levels.fill(0); levelPosition = 0; draw();
setState("listening");
log("recording_armed"); updateDiagnostics(); sendHeartbeat();
} catch (cause) {
await end();
if (mode.checked && captures.length === 0) {
localStorage.removeItem("boomcast-burst-active");
sessionId = null; mode.disabled = maximum.disabled = testMode.disabled = false;
review.hidden = true; diagnostics.hidden = exportButton.hidden = timelinePanel.hidden = true; manualCapture.hidden = true;
setState("off");
}
if (container) container.dataset.state = "error";
if (section) section.dataset.state = "error";
if (stateLabel) stateLabel.textContent = t.microphoneUnavailable || "Microphone unavailable";
error.textContent = cause.name === "NotAllowedError" ? (t.microphoneDenied || "Microphone permission was denied. Manual reporting is still available.") : (t.microphoneFailed || "Microphone capture failed.");
error.textContent = cause.name === "NotAllowedError" ? (t.microphoneDenied || "Microphone permission was denied. Manual reporting is still available.") : (cause.message || t.microphoneFailed || "Microphone capture failed.");
error.hidden = false;
} finally {
start.disabled = false;
@@ -132,6 +264,23 @@ export function createBurstListener() {
}
async function end() {
if (mode.checked && state === "tail" && node) {
const snapshot = await Promise.race([
new Promise((resolve) => { pendingSnapshot = resolve; node.port.postMessage("snapshot"); }),
new Promise((resolve) => setTimeout(() => resolve(null), 750)),
]);
pendingSnapshot = null;
if (snapshot && captures.length < 30) {
const entry = { file: snapshot, url: URL.createObjectURL(snapshot), at: new Date().toISOString(), duration: Math.min(20, snapshot.size / (context.sampleRate * 2)) };
captures.push(entry); persistClip(entry, captures.length - 1); log("capture_end_on_stop");
}
}
if (mode.checked && sessionId && state !== "review") {
log("explicit_stop");
window.clearInterval(heartbeatTimer); window.clearInterval(displayTimer);
try { await api(`${sessionUrl()}stop/`); } catch (cause) { log("stop_error", { message: cause.message }); }
try { await wakeLock?.release(); } catch (_) { /* already released */ }
}
if (pendingSnapshot) { pendingSnapshot(null); pendingSnapshot = null; }
clearClip();
node?.disconnect(); source?.disconnect(); silentOutput?.disconnect();
@@ -139,7 +288,15 @@ export function createBurstListener() {
await context?.close();
stream = context = source = node = silentOutput = null;
levels.fill(0); levelPosition = 0;
setState("off");
if (mode.checked && sessionId) { review.hidden = false; manualCapture.hidden = true; renderCaptures(); setState("review"); updateDiagnostics(); }
else { mode.disabled = maximum.disabled = testMode.disabled = false; setState("off"); }
}
function interrupt(kind) {
if (!mode.checked || state === "off" || state === "review") return;
interrupted = true; log(kind, { last_confirmed_active: lastFrameAt, first_observed_inactive: new Date().toISOString() });
error.textContent = `Listening interrupted. Last confirmed active: ${lastFrameAt || "unknown"}; first observed inactive: ${new Date().toISOString()}. The stop time is uncertain.`;
error.hidden = false; end();
}
function reset() {
@@ -153,10 +310,70 @@ export function createBurstListener() {
stop.addEventListener("click", end);
discard.addEventListener("click", reset);
resume.addEventListener("click", reset);
window.addEventListener("pagehide", end);
document.addEventListener("visibilitychange", () => { if (document.hidden) end(); });
manualCapture.addEventListener("click", () => { log("manual_capture"); node?.port.postMessage("manual"); });
exportButton.addEventListener("click", async () => {
let server = null; try { server = await (await fetch(sessionUrl(), { credentials: "same-origin" })).json(); } catch (_) { /* offline export */ }
const iosVersion = /(?:iPhone|iPad|iPod).*?OS (\d+[._]\d+(?:[._]\d+)?)/.exec(navigator.userAgent)?.[1]?.replaceAll("_", ".") || null;
const content = { session_id: sessionId, pwa: window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true, ios_version_reported_by_browser: iosVersion, test_mode: testMode.value, timeline, last_audio_frame_at: lastFrameAt, audio_frames: frameCount, capture_count: captures.length, server };
const url = URL.createObjectURL(new Blob([JSON.stringify(content, null, 2)], { type: "application/json" }));
const anchor = document.createElement("a"); anchor.href = url; anchor.download = `boomcast-burst-${sessionId}.json`; anchor.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
});
window.addEventListener("pagehide", () => { log("pagehide"); if (mode.checked) interrupt("pagehide"); else end(); });
window.addEventListener("pageshow", () => { log("pageshow"); if (mode.checked && lastFrameAt && Date.now() - Date.parse(lastFrameAt) > 10000) interrupt("audio_frame_gap_after_pageshow"); });
document.addEventListener("visibilitychange", () => { log(`visibility_${document.visibilityState}`); if (document.hidden) { if (mode.checked) interrupt("visibility_hidden"); else end(); } else if (mode.checked && lastFrameAt && Date.now() - Date.parse(lastFrameAt) > 10000) interrupt("audio_frame_gap_after_visibility_resume"); });
document.addEventListener("freeze", () => { log("freeze"); interrupt("freeze"); });
document.addEventListener("resume", () => log("resume"));
(async () => {
if (!window.indexedDB) return;
try {
const stored = await clipStorage("read");
for (const item of stored.filter((item) => item.expires < Date.now())) await clipStorage("delete", item.key);
const active = localStorage.getItem("boomcast-burst-active");
const saved = stored.filter((item) => item.sessionId === active && item.expires >= Date.now()).sort((a, b) => a.index - b.index);
if (!active || !saved.length) return;
sessionId = active; mode.checked = true; options.hidden = false; mode.disabled = maximum.disabled = testMode.disabled = true;
captures = saved.map((item) => ({ file: item.file, url: URL.createObjectURL(item.file), at: item.at, duration: item.duration }));
const savedDiagnostics = JSON.parse(localStorage.getItem(`boomcast-burst-${sessionId}`) || "{}");
timeline = savedDiagnostics.timeline || []; lastFrameAt = savedDiagnostics.lastFrameAt || null; frameCount = savedDiagnostics.frameCount || 0;
pressedAt = performance.now(); startedAt = Date.now(); interrupted = true;
log("page_reloaded", { last_confirmed_active: lastFrameAt, first_observed_inactive: new Date().toISOString() });
diagnostics.hidden = exportButton.hidden = timelinePanel.hidden = false; timelineList.replaceChildren(); timeline.forEach((item) => { const row = document.createElement("li"); row.textContent = `${item.wall_at} · ${item.kind}`; timelineList.append(row); }); review.hidden = false; renderCaptures(); setState("review");
error.textContent = "Previous listening was interrupted by a page reload. Captured clips were recovered; coverage after the last confirmed audio frame is unknown."; error.hidden = false;
} catch (_) { /* storage disabled */ }
})();
return {
get active() { return state !== "off"; },
get reviewingBurst() { return mode.checked && state === "review"; },
async burstForSubmission(data) {
if (!sessionId || state !== "review" || !captures.length) throw new Error("Stop listening and keep at least one clip before submitting.");
if (submitting) throw new Error("Burst submission is already in progress.");
submitting = true;
try {
uploadError.hidden = false; uploadError.textContent = "Checking clips for speech and classifying the primary clip on this device…";
const { AudioPreprocessor } = await import("./audio-preprocessor.js");
const { BrowserYamnetClassifier } = await import("./browser-yamnet-classifier.js");
let primaryPredictions = null;
const primary = Number(captureList.querySelector('input[name="burst-primary-choice"]:checked')?.value || 0);
for (let index = 0; index < captures.length; index++) {
try {
let waveform = await AudioPreprocessor.prepare(captures[index].file);
const predictions = await BrowserYamnetClassifier.classify(waveform, { modelUrl: "/static/browser-yamnet/model.json", classMapUrl: "/static/browser-yamnet/yamnet_class_map.json" });
waveform = null;
if (predictions.some((item) => /speech|conversation|narration|monologue|whisper|speaking/i.test(item.class) && item.score >= 0.5)) throw new Error("speech detected; delete this clip before submitting");
if (index === primary) primaryPredictions = predictions.slice(0, 5).map(({ class: label, score }) => ({ class: label, score }));
} catch (cause) {
uploadError.textContent = `Clip ${index + 1}: ${cause.message}. Review or retry this clip.`;
throw new Error(uploadError.textContent);
}
}
data.append("burst_predictions", JSON.stringify(primaryPredictions));
uploadError.hidden = true;
} finally { submitting = false; }
data.append("burst_session_id", sessionId);
data.append("burst_primary", captureList.querySelector('input[name="burst-primary-choice"]:checked')?.value || "0");
data.append("burst_captures", JSON.stringify(captures.map((entry) => ({ captured_at: entry.at, duration_seconds: entry.duration }))));
captures.forEach((entry) => data.append("burst_audio", entry.file));
},
async clipForSubmission() {
if (captured) return captured;
if (state === "off" || !node) return null;
@@ -165,6 +382,6 @@ export function createBurstListener() {
node.port.postMessage("snapshot");
});
},
submissionSucceeded: reset,
submissionSucceeded() { if (mode.checked) { captures.forEach((entry, index) => { URL.revokeObjectURL(entry.url); removeClip(index); }); captures = []; localStorage.removeItem(`boomcast-burst-${sessionId}`); localStorage.removeItem("boomcast-burst-active"); review.hidden = diagnostics.hidden = exportButton.hidden = timelinePanel.hidden = true; timelineList.replaceChildren(); sessionId = null; mode.checked = false; options.hidden = true; mode.disabled = maximum.disabled = testMode.disabled = false; setState("off"); } else reset(); },
};
}
+13 -5
View File
@@ -24,13 +24,17 @@
const bounds = L.latLngBounds([]);
h3Cells.forEach((cell) => {
const hasManual = cell.manual_reports > 0;
const hasSensor = cell.sensor_reports > 0;
const color = hasManual && hasSensor ? "#a78bfa" : hasSensor ? "#22d3ee" : "#f59e0b";
const polygon = L.polygon(cell.boundary, {
color: "#f59e0b", weight: 2, fillColor: "#f59e0b", fillOpacity: 0.25,
color, weight: 2, fillColor: color, fillOpacity: 0.25,
}).addTo(map);
polygon.bindPopup(
"<span class=\"popup-title\">H3 " + cell.cell + "</span>" +
"<span class=\"popup-meta\">" + cell.reports + " " + (cell.reports === 1 ? (t.report || "report") : (t.reports || "reports")) + " · " + cell.occurrences +
" " + (cell.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) + " · " + (t.resolution || "resolution") + " " + h3Resolution + "</span>"
" " + (cell.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) + " · " + (t.resolution || "resolution") + " " + h3Resolution +
"<br>" + cell.manual_reports + " " + (t.manualReport || "Manual report") + " · " + cell.sensor_reports + " " + (t.sensorEvent || "Sensor event") + "</span>"
);
bounds.extend(L.latLngBounds(cell.boundary));
});
@@ -60,7 +64,11 @@
const reportIcon = L.divIcon({
className: "", html: "<div class=\"report-icon\">✦</div>", iconSize: [37, 37], iconAnchor: [19, 19],
});
const sensorIcon = L.divIcon({
className: "", html: "<div class=\"sensor-icon\">S</div>", iconSize: [37, 37], iconAnchor: [19, 19],
});
reports.forEach((report) => {
const isSensor = report.source_type === "sensor";
const visualStatus = report.visually_confirmed ? (t.visuallyConfirmed || "Visually confirmed") : (t.notVisuallyConfirmed || "Not visually confirmed");
let detail = report.occurrences + " " + (report.occurrences === 1 ? (t.occurrence || "occurrence") : (t.occurrences || "occurrences")) +
" · " + visualStatus + "<br>" + (t.reported || "Reported") + " " + report.reported_on;
@@ -70,8 +78,8 @@
detail += " (±" + Math.round(report.direction_accuracy_degrees) + "°)";
}
}
L.marker(report.center, { icon: reportIcon }).addTo(map).bindPopup(
"<span class=\"popup-title\">" + (t.manualReport || "Manual report") + " · H3 " + report.cell + "</span>" +
L.marker(report.center, { icon: isSensor ? sensorIcon : reportIcon }).addTo(map).bindPopup(
"<span class=\"popup-title\">" + (isSensor ? (t.sensorEvent || "Sensor event") : (t.manualReport || "Manual report")) + " · H3 " + report.cell + "</span>" +
"<span class=\"popup-meta\">" + detail + "</span>"
);
@@ -98,4 +106,4 @@
input.addEventListener("change", () => { range.value = "custom"; });
});
}
@@ -0,0 +1,17 @@
const notesToggle = document.querySelector("#field-notes-toggle");
const notesDialog = document.querySelector("#field-notes-dialog");
const notesClose = document.querySelector("#field-notes-close");
if (notesToggle && notesDialog && notesClose) {
notesToggle.addEventListener("click", () => notesDialog.showModal());
notesClose.addEventListener("click", () => notesDialog.close());
notesDialog.addEventListener("close", () => notesToggle.focus());
notesDialog.addEventListener("htmx:afterSwap", () => {
if (!notesDialog.open) return;
const feedback = notesDialog.querySelector(".field-notes .errorlist, .field-notes [role='status']");
if (feedback) {
feedback.tabIndex = -1;
feedback.focus();
}
});
}
+123 -6
View File
@@ -21,6 +21,23 @@
const reportTime = document.querySelector("#manual-report-time");
const reportHours = document.querySelector("#report-clock-hours");
const reportMinutes = document.querySelector("#report-clock-minutes");
const occurredAt = document.querySelector("#manual-occurred-at");
const clockModeLabel = document.querySelector("#report-clock-mode-label");
const clockDate = document.querySelector("#report-clock-date");
const clockEdit = document.querySelector("#report-clock-edit");
const clockReset = document.querySelector("#report-clock-reset");
const clockEditor = document.querySelector("#report-clock-editor");
const clockDraftDate = document.querySelector("#report-clock-draft-date");
const clockDraftTime = document.querySelector("#report-clock-draft-time");
const clockApply = document.querySelector("#report-clock-apply");
const clockCancel = document.querySelector("#report-clock-cancel");
const clockError = document.querySelector("#report-clock-error");
const timeApproximate = document.querySelector("#manual-time-approximate");
let timestampMode = "NOW";
let overrideTime = null;
let overrideApproximate = false;
const burstStatus = document.querySelector("#manual-burst-status");
const burstDuration = document.querySelector("#manual-burst-duration");
let orientationListener;
let compassUnavailableTimeout;
let compassRotation = null;
@@ -34,19 +51,94 @@
const displayDegrees = (value) => Number(value.toFixed(1)).toString();
const updateReportTime = () => {
if (!reportTime) return;
const now = new Date();
reportTime.dateTime = now.toISOString();
const parts = new Intl.DateTimeFormat(document.documentElement.lang || undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(now);
const shown = timestampMode === "OVERRIDE" ? overrideTime : new Date();
reportTime.dateTime = shown.toISOString();
const parts = new Intl.DateTimeFormat(document.documentElement.lang || undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(shown);
const hours = parts.find((part) => part.type === "hour")?.value;
const minutes = parts.find((part) => part.type === "minute")?.value;
if (!hours || !minutes || !reportHours || !reportMinutes) return;
reportHours.textContent = hours;
reportMinutes.textContent = minutes;
reportTime.setAttribute("aria-label", `${hours}:${minutes}`);
if (clockDate) {
clockDate.hidden = timestampMode !== "OVERRIDE";
if (timestampMode === "OVERRIDE") clockDate.textContent = new Intl.DateTimeFormat(document.documentElement.lang || undefined, { day: "numeric", month: "long", year: "numeric" }).format(shown);
}
};
updateReportTime();
if (reportTime) window.setInterval(updateReportTime, 60000);
const idleSubmitLabel = submitLabel?.textContent || "I heard fireworks";
const localInputValue = (date) => {
const pad = (value) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
};
const clearClockError = () => {
if (!clockError) return;
clockError.hidden = true;
clockError.textContent = "";
clockDraftDate.removeAttribute("aria-invalid");
clockDraftTime.removeAttribute("aria-invalid");
};
const closeClockEditor = () => {
clockEditor.hidden = true;
clockEdit.setAttribute("aria-expanded", "false");
clearClockError();
clockEdit.focus();
};
clockEdit?.addEventListener("click", () => {
const [date, time] = localInputValue(timestampMode === "OVERRIDE" ? overrideTime : new Date()).split("T");
clockDraftDate.value = date;
clockDraftTime.value = time;
timeApproximate.checked = timestampMode === "OVERRIDE" && overrideApproximate;
timeApproximate.disabled = false;
clearClockError();
clockEditor.hidden = false;
clockEdit.setAttribute("aria-expanded", "true");
clockDraftDate.focus();
});
clockCancel?.addEventListener("click", () => {
timeApproximate.checked = timestampMode === "OVERRIDE" && overrideApproximate;
timeApproximate.disabled = timestampMode === "NOW";
closeClockEditor();
});
clockApply?.addEventListener("click", () => {
const date = clockDraftDate.value;
const time = clockDraftTime.value.trim();
const value = `${date}T${time}`;
const complete = /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d$/.test(value);
const chosen = complete ? new Date(value) : null;
if (!chosen || Number.isNaN(chosen.getTime()) || localInputValue(chosen) !== value || chosen.getTime() > Date.now() + 300000) {
clockError.textContent = !chosen || Number.isNaN(chosen.getTime()) || localInputValue(chosen) !== value
? (t.invalidReportTime || "Enter a valid date and time.")
: (t.futureReportTime || "Report time cannot be in the future.");
clockError.hidden = false;
clockDraftDate.setAttribute("aria-invalid", "true");
clockDraftTime.setAttribute("aria-invalid", "true");
(!date ? clockDraftDate : clockDraftTime).focus();
return;
}
overrideTime = chosen;
overrideApproximate = timeApproximate.checked;
timestampMode = "OVERRIDE";
occurredAt.value = chosen.toISOString();
clockModeLabel.textContent = t.adjusted || "Adjusted";
clockReset.hidden = false;
updateReportTime();
closeClockEditor();
});
clockReset?.addEventListener("click", () => {
timestampMode = "NOW";
overrideTime = null;
overrideApproximate = false;
occurredAt.value = "";
timeApproximate.checked = false;
timeApproximate.disabled = true;
clockModeLabel.textContent = t.now || "Now";
clockReset.hidden = true;
updateReportTime();
if (!clockEditor.hidden) closeClockEditor();
clockEdit.focus();
});
const setSubmissionState = (next, message = "") => {
manualForm.dataset.state = next;
@@ -59,6 +151,13 @@
}
};
const rotateNoteContext = (receipt) => {
const token = receipt?.dataset.nextNoteToken;
const input = document.querySelector("#manual-note-context");
if (!token || !input || input.value === token) return;
input.value = token;
if (window.htmx) htmx.ajax("GET", "/fireworks/notes/?token=" + encodeURIComponent(token), {target: "#live-field-notes", swap: "outerHTML"});
};
const showResponse = (html, successful) => {
const parsed = new DOMParser().parseFromString(html, "text/html").querySelector("#manual-submission");
if (!parsed) {
@@ -66,20 +165,28 @@
return false;
}
document.querySelector("#manual-submission").replaceWith(parsed);
if (successful) rotateNoteContext(parsed);
setSubmissionState(successful ? "submitted" : "error");
return successful;
};
const showBurstState = () => {
const burst = Number(occurrences.value) >= 3;
if (burstStatus) burstStatus.textContent = burst ? (t.burstEvent || "Burst Event") : (t.ordinaryReport || "Ordinary report");
if (burstDuration) burstDuration.hidden = !burst;
};
const setCount = (value) => {
const count = Number.parseInt(value, 10);
occurrences.value = String(Math.min(1000, Math.max(1, Number.isFinite(count) ? count : 1)));
decrease.disabled = occurrences.value === "1";
increase.disabled = occurrences.value === "1000";
showBurstState();
};
setCount(occurrences.value);
decrease.addEventListener("click", () => setCount(Number(occurrences.value) - 1));
increase.addEventListener("click", () => setCount(Number(occurrences.value) + 1));
occurrences.addEventListener("change", () => setCount(occurrences.value));
occurrences.addEventListener("input", showBurstState);
const stopCompassReading = () => {
if (orientationListener) window.removeEventListener("deviceorientation", orientationListener);
@@ -197,19 +304,27 @@
};
const submitManualReport = async () => {
if (occurredAt) occurredAt.value = timestampMode === "OVERRIDE" ? overrideTime.toISOString() : "";
if (timeApproximate) {
timeApproximate.checked = timestampMode === "OVERRIDE" && overrideApproximate;
timeApproximate.disabled = timestampMode === "NOW";
}
setCount(occurrences.value);
stopCompassReading();
setSubmissionState("submitting", t.sendingReport || "Sending…");
if (burstListener?.active) {
try {
const audio = await burstListener.clipForSubmission();
const data = new FormData(manualForm);
if (audio) data.append("audio", audio);
if (burstListener.reviewingBurst) await burstListener.burstForSubmission(data);
else {
const audio = await burstListener.clipForSubmission();
if (audio) data.append("audio", audio);
}
const response = await fetch(manualForm.action, { method: "POST", body: data, credentials: "same-origin" });
const html = await response.text();
if (showResponse(html, response.ok)) burstListener.submissionSucceeded();
} catch (error) {
setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
setSubmissionState("error", error.message || t.reportFailed || "Could not send the report. Please try again.");
}
return;
}
@@ -284,3 +399,5 @@
if (event.detail.elt === manualForm) setSubmissionState("error", t.reportFailed || "Could not send the report. Please try again.");
});
document.body.addEventListener("htmx:afterSwap", () => rotateNoteContext(document.querySelector("#manual-submission")));
+9
View File
@@ -0,0 +1,9 @@
# Styles
Page and component styles are SCSS imported by the JavaScript entries in `frontend/src/entries/`. Vite compiles them during development and production builds.
`_settings.scss` holds build-time defaults. `theme.scss` exposes shared colors as CSS custom properties on `:root`, and `fonts.scss` exposes the UI font stack as `--font-ui`. Prefer `var(...)` in component rules for values that should remain visible and adjustable in browser developer tools. Use Sass variables for values shared at build time; keep nesting shallow so selectors and source order remain easy to inspect.
The Django admin and hello pages load CSS directly from Django's static directory. Their SCSS sources live in `static/`; `npm run styles:static` compiles them to the existing static paths. `npm run dev` watches those sources, and `npm run build` compiles them before Vite and `collectstatic`.
There is no downloaded web font. If one is added later, put its loading rule in `fonts.scss`.
+16
View File
@@ -0,0 +1,16 @@
// Build-time defaults. Theme values are exposed as CSS custom properties so
// they remain inspectable and can change at runtime.
$font-ui: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
$night-bg: #090e1d;
$night-ink: #eef3ff;
$night-muted: #aab9d8;
$night-surface: #172443;
$night-surface-raised: #111a31;
$night-line: #2b3d68;
$night-input: #0a1123;
$day-bg: #f4f7fc;
$day-ink: #172033;
$day-muted: #536174;
$day-surface: #ffffff;
$day-surface-raised: #f2f6fc;
$day-line: #c4cede;
@@ -1,26 +0,0 @@
.manual-report__supporting { padding: 1rem; border: 1px solid #514282; border-radius: 1rem; background: #11152c; }
.manual-report__supporting-header { display: flex; align-items: center; gap: .7rem; }
.manual-report__microphone { display: grid; width: 2.5rem; height: 2.5rem; flex: none; place-items: center; border-radius: .7rem; background: #2a2051; font-size: 1.3rem; }
.burst-listener__state { display: block; margin-top: .15rem; color: #b9addb; font-size: .84rem; }
.manual-report__supporting[data-state="listening"] .burst-listener__state { color: #8fe5cc; }
.manual-report__supporting[data-state="error"] .burst-listener__state { color: #ffbd9d; }
.burst-listener { width: 100%; margin-top: .85rem; }
.burst-listener__button, .burst-listener__actions button { min-height: 2.75rem; padding: .65rem 1rem; border: 1px solid #8d77d2; border-radius: .7rem; color: #e8dcff; font: inherit; font-weight: 750; background: #292148; cursor: pointer; }
.burst-listener__button { width: 100%; }
.burst-listener__panel { color: #f0eaff; }
.burst-listener__panel strong { font-size: .92rem; }
.burst-listener__panel canvas { display: block; width: 100%; height: 4rem; margin: .7rem 0 .35rem; border-radius: .5rem; background: linear-gradient(90deg, #191738, #241b44); }
.burst-listener__panel p { margin: .35rem 0 .75rem; color: #b9addb; font-size: .82rem; }
.burst-listener__panel audio { width: 100%; margin-bottom: .75rem; }
.burst-listener__actions { display: flex; flex-wrap: wrap; gap: .5rem; }
.burst-listener__actions button { flex: 1 1 10rem; }
.burst-listener__actions #burst-stop { border-color: #fb9b72; color: #ffd8c4; background: #2e1b31; }
.burst-listener [hidden] { display: none !important; }
.burst-listener [role="alert"] { margin: .65rem 0 0; color: #ffd1b6; }
.burst-listener button:focus-visible { outline: 3px solid #c9b4ff; outline-offset: 3px; }
:root[data-theme="light"] .manual-report__supporting { border-color: #d9b4d8; background: #fff8fb; }
:root[data-theme="light"] .manual-report__microphone { background: #ead2eb; }
:root[data-theme="light"] .burst-listener__state, :root[data-theme="light"] .burst-listener__panel p { color: #694b68; }
:root[data-theme="light"] .burst-listener__panel { color: #321d42; }
:root[data-theme="light"] .burst-listener__button, :root[data-theme="light"] .burst-listener__actions button { border-color: #b68bb5; color: #321d42; background: #ead2eb; }
:root[data-theme="light"] .burst-listener__actions #burst-stop { border-color: #cf7957; color: #71331d; background: #ffe9de; }
@@ -0,0 +1,140 @@
.manual-report__supporting {
padding: 1rem;
border: 1px solid #514282;
border-radius: 1rem;
background: #11152c;
}
.manual-report__supporting-header {
display: flex;
align-items: center;
gap: .7rem;
}
.manual-report__microphone {
display: grid;
width: 2.5rem;
height: 2.5rem;
flex: none;
place-items: center;
border-radius: .7rem;
background: #2a2051;
font-size: 1.3rem;
}
.burst-listener__state {
display: block;
margin-top: .15rem;
color: #b9addb;
font-size: .84rem;
}
.manual-report__supporting[data-state="listening"] .burst-listener__state {
color: #8fe5cc;
}
.manual-report__supporting[data-state="error"] .burst-listener__state {
color: #ffbd9d;
}
.burst-listener {
width: 100%;
margin-top: .85rem;
}
.burst-listener__button, .burst-listener__actions button, #burst-manual-capture, #burst-export, #burst-review button {
min-height: 2.75rem;
padding: .65rem 1rem;
border: 1px solid #8d77d2;
border-radius: .7rem;
color: #e8dcff;
font: inherit;
font-weight: 750;
background: #292148;
cursor: pointer;
}
.burst-listener__button {
width: 100%;
}
.burst-listener__panel {
color: #f0eaff;
strong {
font-size: .92rem;
}
canvas {
display: block;
width: 100%;
height: 4rem;
margin: .7rem 0 .35rem;
border-radius: .5rem;
background: linear-gradient(90deg, #191738, #241b44);
}
p {
margin: .35rem 0 .75rem;
color: #b9addb;
font-size: .82rem;
}
audio {
width: 100%;
margin-bottom: .75rem;
}
}
.burst-listener__actions {
display: flex;
flex-wrap: wrap;
gap: .5rem;
button {
flex: 1 1 10rem;
}
#burst-stop {
border-color: #fb9b72;
color: #ffd8c4;
background: #2e1b31;
}
}
.burst-listener [hidden] {
display: none !important;
}
.burst-listener [role="alert"] {
margin: .65rem 0 0;
color: #ffd1b6;
}
.burst-listener button:focus-visible {
outline: 3px solid #c9b4ff;
outline-offset: 3px;
}
:root[data-theme="light"] .manual-report__supporting {
border-color: #d9b4d8;
background: #fff8fb;
}
:root[data-theme="light"] .manual-report__microphone {
background: #ead2eb;
}
:root[data-theme="light"] .burst-listener__state, :root[data-theme="light"] .burst-listener__panel p {
color: #694b68;
}
:root[data-theme="light"] .burst-listener__panel {
color: #321d42;
}
:root[data-theme="light"] .burst-listener__button, :root[data-theme="light"] .burst-listener__actions button, :root[data-theme="light"] #burst-manual-capture, :root[data-theme="light"] #burst-export, :root[data-theme="light"] #burst-review button {
border-color: #b68bb5;
color: #321d42;
background: #ead2eb;
}
:root[data-theme="light"] .burst-listener__actions #burst-stop {
border-color: #cf7957;
color: #71331d;
background: #ffe9de;
}
@@ -0,0 +1,96 @@
.field-notes {
margin-top: 1.5rem; padding: 1rem; border: 1px solid var(--theme-line); border-radius: 1rem;
color: var(--theme-ink); background: var(--theme-surface); overflow-wrap: anywhere;
h2 { font-size: 1.3rem; }
p, small { line-height: 1.55; }
details { margin: .8rem 0; }
summary { cursor: pointer; padding: .4rem 0; font-weight: 650; }
form { margin-top: .8rem; }
label, small { display: block; margin: .4rem 0; }
input, select, textarea { width: 100%; max-width: 100%; min-width: 0; padding: .65rem; border: 1px solid var(--theme-line); border-radius: .5rem; font: inherit; color: var(--theme-ink); background: var(--theme-input); }
textarea { resize: vertical; }
button { margin-top: .7rem; padding: .65rem 1rem; border: 1px solid var(--theme-line); border-radius: .5rem; background: var(--theme-surface-raised); color: var(--theme-ink); font: inherit; cursor: pointer; }
:focus-visible { outline: 3px solid #789eff; outline-offset: 3px; }
&__fields { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .8rem; }
&__timeline { padding-left: 1.3rem; }
&__timeline > li { padding: .6rem 0 1rem .4rem; border-bottom: 1px solid var(--theme-line); }
&__content { white-space: pre-wrap; }
&__meta, small { color: var(--theme-muted); font-size: .85rem; }
.errorlist { color: #f28c96; }
@media (max-width: 650px) { &__fields { grid-template-columns: 1fr; } }
}
.field-notes-trigger {
position: absolute !important;
z-index: 2;
top: clamp(1.35rem, 4vw, 2.4rem);
right: clamp(1.35rem, 4vw, 2.4rem);
display: grid;
place-items: center;
width: 2.75rem;
height: 2.75rem;
padding: .55rem;
border: 1px solid #a985b5;
border-radius: .8rem;
color: #f5f0ff;
background: #302553;
box-shadow: 0 .3rem 1rem #08071766;
cursor: pointer;
svg { width: 100%; height: 100%; }
&:focus-visible { outline: 3px solid #c9b4ff; outline-offset: 3px; }
}
.field-notes-dialog {
position: fixed !important;
box-sizing: border-box;
width: min(42rem, calc(100vw - 2rem));
max-width: none;
max-height: calc(100dvh - 2rem);
margin: auto;
padding: 1rem;
overflow-y: auto;
overscroll-behavior: contain;
border: 1px solid var(--theme-line);
border-radius: 1rem;
color: var(--theme-ink);
background: var(--theme-surface);
box-shadow: 0 1.5rem 5rem #020616aa;
&::backdrop { background: #050a19bb; backdrop-filter: blur(3px); }
.field-notes { margin: 0; padding: 0; border: 0; background: transparent; }
.field-notes h2 { margin-top: 0; }
}
.field-notes-dialog__toolbar {
position: sticky;
top: -1rem;
z-index: 1;
display: flex;
justify-content: flex-end;
margin-bottom: .25rem;
padding: .25rem 0;
background: var(--theme-surface);
button {
display: grid;
place-items: center;
width: 2.5rem;
height: 2.5rem;
padding: 0;
border: 1px solid var(--theme-line);
border-radius: .6rem;
color: var(--theme-ink);
background: var(--theme-surface-raised);
font: inherit;
font-size: 1.5rem;
cursor: pointer;
&:focus-visible { outline: 3px solid #789eff; outline-offset: 3px; }
}
}
.field-notes-dialog__signin { padding: 0 .25rem .5rem; }
.field-notes-dialog__signin h2 { margin: 0 0 .5rem; }
.field-notes-dialog__signin a { color: var(--theme-ink); }
@media (max-width: 30rem) {
.field-notes-trigger { top: .8rem; right: .8rem; }
.dashboard-report .manual-report__heading-row { margin-top: .75rem; }
}
@@ -1,104 +0,0 @@
.fireworks-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 3.5rem;
}
.fireworks-brand {
display: flex;
align-items: center;
gap: .7rem;
color: var(--ink, var(--i, #eef3ff));
font-size: .9rem;
font-weight: 800;
letter-spacing: .1em;
text-decoration: none;
text-transform: uppercase;
}
.fireworks-header .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;
}
.fireworks-header__controls { display: flex; align-items: center; gap: .65rem; }
.fireworks-menu-toggle { display: none; }
.fireworks-nav {
display: flex;
gap: .3rem;
padding: .25rem;
border: 1px solid var(--line, var(--l, #2b3d68));
border-radius: .75rem;
background: #111a31d9;
box-shadow: 0 .5rem 1.5rem #03071440;
}
.fireworks-nav a,
.fireworks-nav button {
padding: .5rem .75rem;
border-radius: .5rem;
color: var(--muted, var(--m, #aab9d8));
font-size: .86rem;
font-weight: 750;
text-decoration: none;
}
.fireworks-nav form { display: flex; margin: 0; }
.fireworks-nav button { border: 0; background: transparent; font: inherit; cursor: pointer; }
.fireworks-nav a:hover,
.fireworks-nav button:hover { color: var(--ink, var(--i, #eef3ff)); background: #20345f; }
.fireworks-nav a[aria-current="page"] { color: var(--ink, var(--i, #eef3ff)); background: #2a3b67; }
.theme-toggle--inline {
position: static;
flex: 0 0 auto;
min-height: 2.35rem;
padding: .45rem .7rem;
white-space: nowrap;
}
:root[data-theme="light"] .fireworks-nav {
border-color: #cbd9ed;
background: #edf4ff;
box-shadow: 0 .45rem 1.25rem rgba(34, 68, 117, .12);
}
:root[data-theme="light"] .fireworks-nav a,
:root[data-theme="light"] .fireworks-nav button { color: #47617f; }
:root[data-theme="light"] .fireworks-nav a:hover,
:root[data-theme="light"] .fireworks-nav button:hover { color: #234a7b; background: #dceaff; }
:root[data-theme="light"] .fireworks-nav a[aria-current="page"] {
color: #173d6a;
background: #cfe3ff;
box-shadow: inset 0 0 0 1px #9cc0ed;
}
@media (max-width: 44rem) {
.fireworks-header { flex-wrap: wrap; justify-content: flex-start; margin-bottom: 2.5rem; }
.fireworks-menu-toggle {
display: flex;
flex: 0 0 auto;
flex-direction: column;
align-items: center;
justify-content: center;
gap: .3rem;
width: 2.75rem;
height: 2.75rem;
padding: 0;
border: 1px solid var(--theme-line);
border-radius: .7rem;
color: var(--theme-ink);
background: var(--theme-surface-raised);
cursor: pointer;
}
.fireworks-menu-toggle span { width: 1.2rem; height: 2px; border-radius: 2px; background: currentColor; }
.fireworks-menu-toggle:focus-visible { outline: 3px solid #8abaff; outline-offset: 3px; }
.fireworks-header__controls { display: none; flex-basis: 100%; width: 100%; flex-direction: column; align-items: stretch; }
.fireworks-menu-toggle[aria-expanded="true"] ~ .fireworks-header__controls { display: flex; }
.fireworks-nav { flex-direction: column; }
.fireworks-nav a,
.fireworks-nav button { padding: .75rem; }
.fireworks-nav form,
.fireworks-nav button { width: 100%; }
.fireworks-nav button { text-align: left; }
.theme-toggle--inline { width: 100%; }
}
@@ -0,0 +1,161 @@
.fireworks-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 3.5rem;
}
.fireworks-brand {
display: flex;
align-items: center;
gap: .7rem;
color: var(--ink, var(--i, #eef3ff));
font-size: .9rem;
font-weight: 800;
letter-spacing: .1em;
text-decoration: none;
text-transform: uppercase;
}
.fireworks-header .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;
}
.fireworks-header__controls {
display: flex;
align-items: center;
gap: .65rem;
}
.fireworks-menu-toggle {
display: none;
}
.fireworks-nav {
display: flex;
gap: .3rem;
padding: .25rem;
border: 1px solid var(--line, var(--l, #2b3d68));
border-radius: .75rem;
background: #111a31d9;
box-shadow: 0 .5rem 1.5rem #03071440;
a, button {
padding: .5rem .75rem;
border-radius: .5rem;
color: var(--muted, var(--m, #aab9d8));
font-size: .86rem;
font-weight: 750;
text-decoration: none;
}
form {
display: flex;
margin: 0;
}
button {
border: 0;
background: transparent;
font: inherit;
cursor: pointer;
}
a:hover, button:hover {
color: var(--ink, var(--i, #eef3ff));
background: #20345f;
}
a[aria-current="page"] {
color: var(--ink, var(--i, #eef3ff));
background: #2a3b67;
}
}
.theme-toggle--inline {
position: static;
flex: 0 0 auto;
min-height: 2.35rem;
padding: .45rem .7rem;
white-space: nowrap;
}
:root[data-theme="light"] .fireworks-nav {
border-color: #cbd9ed;
background: #edf4ff;
box-shadow: 0 .45rem 1.25rem rgba(34, 68, 117, .12);
a, button {
color: #47617f;
}
a:hover, button:hover {
color: #234a7b;
background: #dceaff;
}
a[aria-current="page"] {
color: #173d6a;
background: #cfe3ff;
box-shadow: inset 0 0 0 1px #9cc0ed;
}
}
@media (max-width: 44rem) {
.fireworks-header {
flex-wrap: wrap;
justify-content: flex-start;
margin-bottom: 2.5rem;
}
.fireworks-menu-toggle {
display: flex;
flex: 0 0 auto;
flex-direction: column;
align-items: center;
justify-content: center;
gap: .3rem;
width: 2.75rem;
height: 2.75rem;
padding: 0;
border: 1px solid var(--theme-line);
border-radius: .7rem;
color: var(--theme-ink);
background: var(--theme-surface-raised);
cursor: pointer;
span {
width: 1.2rem;
height: 2px;
border-radius: 2px;
background: currentColor;
}
&:focus-visible {
outline: 3px solid #8abaff;
outline-offset: 3px;
}
}
.fireworks-header__controls {
display: none;
flex-basis: 100%;
width: 100%;
flex-direction: column;
align-items: stretch;
}
.fireworks-menu-toggle[aria-expanded="true"] ~ .fireworks-header__controls {
display: flex;
}
.fireworks-nav {
flex-direction: column;
a, button {
padding: .75rem;
}
form, button {
width: 100%;
}
button {
text-align: left;
}
}
.theme-toggle--inline {
width: 100%;
}
}
@@ -7,8 +7,11 @@
font-size: .78rem;
font-weight: 850;
font-variant-numeric: tabular-nums;
&[hidden] {
display: none;
}
}
.manual-compass[hidden] { display: none; }
.manual-compass__dial {
position: relative;
width: 5.75rem;
@@ -18,12 +21,42 @@
background: radial-gradient(circle, #342441 0 28%, #211a32 75%);
box-shadow: 0 .35rem 1rem #09061566, inset 0 0 0 .25rem #ffffff12;
}
.manual-compass__rose { position: absolute; inset: 0; transition: transform 120ms ease-out; }
.manual-compass__rose span { position: absolute; line-height: 1; }
.manual-compass__north { top: .38rem; left: 50%; color: #ff9e78; transform: translateX(-50%); }
.manual-compass__east { right: .47rem; top: 50%; transform: translateY(-50%); }
.manual-compass__south { bottom: .38rem; left: 50%; transform: translateX(-50%); }
.manual-compass__west { left: .47rem; top: 50%; transform: translateY(-50%); }
.manual-compass__rose {
position: absolute;
inset: 0;
transition: transform 120ms ease-out;
span {
position: absolute;
line-height: 1;
}
}
.manual-compass__north {
top: .38rem;
left: 50%;
color: #ff9e78;
transform: translateX(-50%);
}
.manual-compass__east {
right: .47rem;
top: 50%;
transform: translateY(-50%);
}
.manual-compass__south {
bottom: .38rem;
left: 50%;
transform: translateX(-50%);
}
.manual-compass__west {
left: .47rem;
top: 50%;
transform: translateY(-50%);
}
.manual-compass__pointer {
position: absolute;
top: -.55rem;
@@ -36,6 +69,7 @@
transform: translateX(-50%);
filter: drop-shadow(0 .1rem .15rem #160d1b);
}
.manual-compass__center {
position: absolute;
top: 50%;
@@ -46,10 +80,29 @@
background: #ffbd62;
transform: translate(-50%, -50%);
}
.manual-compass__heading { margin-top: .5rem; white-space: nowrap; }
:root[data-theme="light"] .manual-compass { color: #43243d; }
:root[data-theme="light"] .manual-compass__dial { border-color: #996a9b; background: radial-gradient(circle, #f8ebf8 0 28%, #e8d7e9 75%); }
.manual-compass__heading {
margin-top: .5rem;
white-space: nowrap;
}
:root[data-theme="light"] .manual-compass {
color: #43243d;
}
:root[data-theme="light"] .manual-compass__dial {
border-color: #996a9b;
background: radial-gradient(circle, #f8ebf8 0 28%, #e8d7e9 75%);
}
:root[data-theme="light"] .manual-compass__east,
:root[data-theme="light"] .manual-compass__south,
:root[data-theme="light"] .manual-compass__west { color: #43243d; }
@media (prefers-reduced-motion: reduce) { .manual-compass__rose { transition: none; } }
:root[data-theme="light"] .manual-compass__west {
color: #43243d;
}
@media (prefers-reduced-motion: reduce) {
.manual-compass__rose {
transition: none;
}
}
@@ -1,218 +0,0 @@
.manual-report__header {
max-width: 42rem;
}
.manual-report { --manual-report-section-gap: 1rem; }
.manual-report__primary {
display: grid;
gap: var(--manual-report-section-gap);
max-width: 36rem;
}
.manual-report__quantity {
padding: 1rem;
border: 1px solid #584891;
border-radius: 1rem;
background: #151932;
}
.manual-report .manual-report__quantity #manual-occurrences {
width: 100%;
min-width: 0;
min-height: 3.75rem;
margin: 0;
padding: 0;
border: 0;
color: #f5f0ff;
font-size: clamp(2.25rem, 8vw, 3.5rem);
font-weight: 850;
text-align: center;
background: transparent;
appearance: textfield;
-moz-appearance: textfield;
}
.manual-report__quantity #manual-occurrences::-webkit-inner-spin-button,
.manual-report__quantity #manual-occurrences::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
.manual-report__stepper { display: grid; grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem; align-items: center; gap: .5rem; }
.manual-report__stepper button { display: grid; place-items: center; width: 3.5rem; height: 3.5rem; min-height: 0; padding: 0; border: 1px solid #6d54ac; border-radius: 50%; color: #f5f0ff; font: inherit; font-size: 2rem; line-height: 1; background: #302553; cursor: pointer; }
.manual-report__stepper button:disabled { opacity: .4; cursor: default; }
.manual-report .manual-report__primary .manual-direction-panel {
width: 100%;
margin: 0;
border-radius: 1rem;
background: #1a1739;
}
.manual-direction-panel[data-state="measuring"] { border-color: #a27cff; }
.manual-direction-panel[data-state="captured"] { border-color: #68dba1; }
.manual-direction-panel[data-state="unavailable"] { border-color: #d38b7a; }
.manual-direction-panel__topline { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
.manual-direction-panel__summary { margin: .35rem 0 .8rem; color: #f5f0ff; font-weight: 700; }
.manual-report .manual-direction-panel__status--accuracy { display: flex; align-items: center; justify-content: space-between; gap: .75rem; margin: .75rem 0; padding: .55rem .75rem; border: 1px solid #5d4d92; border-radius: .7rem; color: #d9cfee; background: #191630; font-size: .85rem; }
.manual-direction-panel__status--accuracy strong { color: #f5edff; font-size: 1rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
.manual-direction-panel__open, .manual-direction-panel__close { min-height: 2.75rem; border: 1px solid #8d77d2; border-radius: .7rem; color: #e8dcff; font: inherit; font-weight: 750; background: #302553; cursor: pointer; }
.manual-direction-panel__open { padding: .5rem .85rem; }
.manual-direction-panel__close { min-width: 2.75rem; font-size: 1.4rem; }
.manual-report #manual-submit {
width: 100%;
max-width: 36rem;
min-height: 4.5rem;
margin-top: var(--manual-report-section-gap);
}
.manual-report__submit:disabled { cursor: wait; opacity: .72; }
.manual-submission { display: grid; justify-items: center; gap: .5rem; max-width: 36rem; margin-top: 1rem; padding: 1.3rem; border: 1px solid #4caa82; border-radius: 1rem; color: #eafff2; text-align: center; background: #10352e; }
.manual-submission__icon { display: grid; width: 3.5rem; height: 3.5rem; place-items: center; border: 2px solid #6ce4a8; border-radius: 50%; color: #eafff2; font-size: 2rem; background: #226c51; }
.manual-submission strong { font-size: 1.35rem; }
.manual-submission p { margin: 0; line-height: 1.45; }
.manual-submission__summary { margin-top: .35rem !important; color: #b2e8cf; font-size: .9rem; }
.manual-submission--error { border-color: #d37c6a; color: #fff0e8; background: #3a1c2b; }
.manual-submission--error .manual-submission__icon { border-color: #ffac8c; background: #9b493a; }
.manual-report__submission:empty { display: none; }
.manual-report button:focus-visible, .manual-report input:focus-visible { outline: 3px solid #c9b4ff; outline-offset: 3px; }
.manual-report__supporting {
max-width: 36rem;
margin-top: var(--manual-report-section-gap);
padding-top: 1.25rem;
border-top: 1px solid #584891;
}
.manual-report__supporting h3 {
margin: 0;
color: #d8cffd;
font-size: 1rem;
}
.manual-report__supporting .burst-listener {
width: 100%;
}
:root[data-theme="light"] .manual-report__quantity {
border-color: #d9b4d8;
background: #fff8fb;
}
:root[data-theme="light"] .manual-report__quantity #manual-occurrences { border: 0 !important; color: #321d42 !important; background: transparent !important; }
:root[data-theme="light"] .manual-report__stepper button,
:root[data-theme="light"] .manual-direction-panel__open,
:root[data-theme="light"] .manual-direction-panel__close { color: #321d42; border-color: #b68bb5; background: #ead2eb; }
:root[data-theme="light"] .manual-direction-panel__summary { color: #321d42; }
:root[data-theme="light"] .manual-report .manual-direction-panel__status--accuracy { border-color: #cfaad1; color: #694b68; background: #fff8fb; }
:root[data-theme="light"] .manual-direction-panel__status--accuracy strong { color: #321d42; }
:root[data-theme="light"] .manual-submission { border-color: #54a67b; color: #164d34; background: #e8fff2; }
:root[data-theme="light"] .manual-submission__icon { color: #fff; }
:root[data-theme="light"] .manual-submission__summary { color: #2b6b48; }
:root[data-theme="light"] .manual-submission--error { border-color: #ca7d65; color: #743520; background: #fff0e8; }
:root[data-theme="light"] .manual-report__supporting {
border-color: #d9b4d8;
}
:root[data-theme="light"] .manual-report__supporting h3 {
color: #492846;
}
@media (max-width: 42rem) {
.home-grid { grid-template-columns: minmax(0, 1fr); }
body:not(.dashboard-page) { padding: max(1rem, env(safe-area-inset-top, 0px)) max(.5rem, env(safe-area-inset-right, 0px)) max(1rem, env(safe-area-inset-bottom, 0px)) max(.5rem, env(safe-area-inset-left, 0px)); }
.home-grid .manual-report, .dashboard-report, .dashboard-report .manual-report { overflow: visible; }
.manual-report { padding: 1.25rem; }
.dashboard-report .manual-report { padding: 0; }
.manual-report__header { padding-right: 2.5rem; }
.manual-report form { padding-bottom: calc(5rem + env(safe-area-inset-bottom, 0px)); }
.manual-report #manual-submit {
position: sticky;
bottom: calc(.5rem + env(safe-area-inset-bottom, 0px));
z-index: 10;
box-shadow: 0 .7rem 1.6rem #070a18b3;
}
body:has(#manual-occurrences:focus) .manual-report #manual-submit { position: static; }
.dashboard-intro { margin-bottom: 1rem; }
.dashboard-intro h1 { font-size: clamp(2rem, 8vw, 2.8rem); }
.dashboard-intro p:last-child { margin-top: .75rem; font-size: .95rem; line-height: 1.4; }
.dashboard-section { margin-top: 1rem; }
.dashboard-shell { padding-bottom: calc(2rem + env(safe-area-inset-bottom, 0px)); }
.manual-report__stepper { grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem; }
}
@media (max-width: 23.5rem) {
.manual-report { padding: 1rem; }
.manual-report__quantity { padding: .75rem; }
.manual-report__stepper { grid-template-columns: 3rem minmax(0, 1fr) 3rem; gap: .25rem; }
.manual-report__stepper button { width: 3rem; height: 3rem; }
}
.manual-report__heading-row { display: flex; align-items: center; gap: .7rem; }
.manual-report__fire { flex: none; font-size: clamp(1.8rem, 5vw, 2.5rem); filter: drop-shadow(0 .2rem .65rem #ff703b88); }
.manual-report__intro, .dashboard-report .manual-report__intro { margin-bottom: .85rem; }
.report-clock {
box-sizing: border-box;
width: 100%;
max-width: 36rem;
margin: 0 0 1rem;
padding: .65rem .95rem .7rem;
border: 1px solid #69539d;
border-radius: .85rem;
background: linear-gradient(115deg, #17162d, #10182c);
box-shadow: inset 0 1px #ffffff0a;
}
.report-clock__label { color: #cbbce5; font-size: .66rem; font-weight: 750; letter-spacing: .13em; text-transform: uppercase; }
.report-clock__display { display: flex; align-items: end; justify-content: space-between; gap: .75rem; }
.report-clock__time {
display: inline-flex;
align-items: center;
color: #ffbf72;
font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
font-size: clamp(2rem, 9vw, 2.45rem);
font-weight: 700;
line-height: 1.1;
letter-spacing: 0;
font-variant-numeric: tabular-nums;
text-shadow: 0 0 .7rem #ff963b55;
white-space: nowrap;
}
.report-clock__time span { display: inline-block; }
.report-clock__time #report-clock-hours, .report-clock__time #report-clock-minutes { width: 2ch; }
.report-clock__colon { width: 1ch; flex: none; margin-inline: -.08em; line-height: 1; text-align: center; transform: translateY(-.06em); animation: report-clock-blink 2s steps(1, end) infinite; }
.report-clock__now { display: inline-flex; align-items: center; gap: .4rem; flex: none; padding: .2rem .45rem; border: 1px solid #93634d; border-radius: 999px; color: #ffd2a2; font-size: .7rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
.report-clock__dot { width: .4rem; height: .4rem; border-radius: 50%; background: #ffab5d; }
@keyframes report-clock-blink { 50% { opacity: 0; } }
.manual-direction-panel__open { width: 100%; text-align: left; }
.manual-direction-panel--open .manual-compass { width: 100%; margin: .5rem auto 1rem; }
.manual-direction-panel--open .manual-compass__dial { width: min(100%, 12rem); border-color: #8b67d4; background: radial-gradient(circle, #302054 0 20%, #17132d 70%); box-shadow: 0 0 0 .35rem #6640a228, 0 0 2rem #ac6aff35; }
.manual-direction-panel--open .manual-compass__pointer { border-bottom-color: #ff925f; }
.manual-direction-panel--open .manual-compass__heading { font-size: 1.1rem; }
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit { transition: transform .15s ease, box-shadow .15s ease, filter .15s ease; }
.manual-report__stepper button:not(:disabled):active, .manual-direction-panel__open:active, .manual-report__submit:not(:disabled):active { transform: scale(.97); }
.manual-report__submit:not(:disabled):hover { filter: brightness(1.05); }
.manual-submission--success .manual-submission__icon { animation: manual-confirm .35s ease-out both; }
@keyframes manual-confirm { from { transform: scale(.75); opacity: .3; } to { transform: scale(1); opacity: 1; } }
:root[data-theme="dark"] .home-grid .manual-report,
:root[data-theme="dark"] .dashboard-report { border-color: #7256ab; background: radial-gradient(circle at 88% 5%, #58254a55, transparent 13rem), linear-gradient(155deg, #151326, #0d1022 72%); box-shadow: 0 1rem 3rem #02041399; }
:root[data-theme="dark"] .manual-report__title { color: #fff8f3; }
:root[data-theme="dark"] .manual-report__intro { color: #d6cce4; }
:root[data-theme="dark"] .manual-report__quantity { border-color: #514896; background: linear-gradient(145deg, #19183a, #121834); box-shadow: inset 0 0 0 1px #ffffff08; }
:root[data-theme="dark"] .home-grid .manual-direction-panel,
:root[data-theme="dark"] .dashboard-report .manual-direction-panel { border-color: #59499b; background: linear-gradient(145deg, #211945, #151835); }
:root[data-theme="dark"] .manual-report__supporting { border-color: #493d7d; background: linear-gradient(145deg, #15142f, #10162d); }
:root[data-theme="dark"] .manual-report__stepper button { box-shadow: 0 .25rem .7rem #07041655; }
:root[data-theme="dark"] .manual-report__submit { background: linear-gradient(110deg, #ffc276, #ff7654); box-shadow: 0 .55rem 1.35rem #e2633a4d; }
:root[data-theme="dark"] .manual-direction-panel[data-state="measuring"] { border-color: #a27cff; }
:root[data-theme="dark"] .manual-direction-panel[data-state="captured"] { border-color: #68dba1; }
:root[data-theme="dark"] .manual-direction-panel[data-state="unavailable"] { border-color: #d38b7a; }
:root[data-theme="light"] .report-clock { border-color: #8b6bab; background: linear-gradient(115deg, #221b37, #182039); }
:root[data-theme="light"] .manual-direction-panel--open .manual-compass__dial { background: radial-gradient(circle, #f8ebf8 0 25%, #e8d7e9 75%); }
@media (prefers-reduced-motion: reduce) {
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit { transition: none; }
.manual-submission--success .manual-submission__icon { animation: none; }
.report-clock__colon { animation: none; opacity: 1; }
}
@@ -0,0 +1,725 @@
.manual-report__header {
max-width: 42rem;
}
.manual-report {
--manual-report-section-gap: 1rem;
}
.manual-report__duration {
display: grid;
gap: .55rem;
max-width: 36rem;
margin-bottom: var(--manual-report-section-gap);
padding: .85rem 1rem;
border: 1px solid #584891;
border-radius: 1rem;
background: #151932;
color: #e9def8;
input[type="datetime-local"], input[type="number"] {
width: 100%;
min-height: 2.75rem;
padding: .45rem .65rem;
border: 1px solid #725da4;
border-radius: .55rem;
color: #f5f0ff;
background: #211d3d;
font: inherit;
color-scheme: dark;
}
small { color: #cbbce5; }
}
.manual-report__duration[hidden] { display: none; }
.manual-report__check {
display: flex;
align-items: center;
gap: .5rem;
color: #e9def8;
}
.burst-listener {
display: grid;
gap: .65rem;
}
.burst-listener__options { display: grid; gap: .5rem; }
.burst-listener__options[hidden] { display: none; }
.burst-listener__options > label {
color: #d5caeb;
font-weight: 650;
}
.burst-listener__options > select {
width: 100%;
min-height: 2.75rem;
padding: .45rem .7rem;
border: 1px solid #725da4;
border-radius: .55rem;
color: #f5f0ff;
background: #211d3d;
font: inherit;
}
#burst-diagnostics {
padding: .7rem;
border: 1px solid #725da4;
border-radius: .6rem;
line-height: 1.45;
}
#burst-review ol { padding-left: 1.5rem; }
#burst-review li { margin: .8rem 0; }
#burst-review audio { display: block; max-width: 100%; margin: .5rem 0; }
#burst-review button { margin-left: .5rem; }
:root[data-theme="light"] .burst-listener__options > label { color: #492846; }
:root[data-theme="light"] .burst-listener > .manual-report__check { color: #492846; }
:root[data-theme="light"] .burst-listener__options > select { color: #321d42; background: #fff; border-color: #b68bb5; }
:root[data-theme="light"] #burst-diagnostics { border-color: #b68bb5; color: #321d42; }
@media (max-width: 600px) {
#burst-review li { overflow-wrap: anywhere; }
#burst-review audio { width: 100%; }
}
.manual-report__burst-status { margin: .5rem 0 0; color: #ffbf72; font-weight: 750; }
.manual-submission__edit {
display: grid;
gap: .4rem;
max-width: 18rem;
margin-top: 1rem;
input[type="number"] { min-height: 2.5rem; padding: .4rem; border-radius: .5rem; }
button { min-height: 2.5rem; cursor: pointer; }
}
.manual-report__primary {
display: grid;
gap: var(--manual-report-section-gap);
max-width: 36rem;
}
.manual-report__quantity {
padding: 1rem;
border: 1px solid #584891;
border-radius: 1rem;
background: #151932;
}
.manual-report .manual-report__quantity #manual-occurrences {
width: 100%;
min-width: 0;
min-height: 3.75rem;
margin: 0;
padding: 0;
border: 0;
color: #f5f0ff;
font-size: clamp(2.25rem, 8vw, 3.5rem);
font-weight: 850;
text-align: center;
background: transparent;
appearance: textfield;
-moz-appearance: textfield;
}
.manual-report__quantity #manual-occurrences::-webkit-inner-spin-button,
.manual-report__quantity #manual-occurrences::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
.manual-report__stepper {
display: grid;
grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem;
align-items: center;
gap: .5rem;
button {
display: grid;
place-items: center;
width: 3.5rem;
height: 3.5rem;
min-height: 0;
padding: 0;
border: 1px solid #6d54ac;
border-radius: 50%;
color: #f5f0ff;
font: inherit;
font-size: 2rem;
line-height: 1;
background: #302553;
cursor: pointer;
&:disabled {
opacity: .4;
cursor: default;
}
}
}
.manual-report .manual-report__primary .manual-direction-panel {
width: 100%;
margin: 0;
border-radius: 1rem;
background: #1a1739;
}
.manual-direction-panel[data-state="measuring"] {
border-color: #a27cff;
}
.manual-direction-panel[data-state="captured"] {
border-color: #68dba1;
}
.manual-direction-panel[data-state="unavailable"] {
border-color: #d38b7a;
}
.manual-direction-panel__topline {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.manual-direction-panel__summary {
margin: .35rem 0 .8rem;
color: #f5f0ff;
font-weight: 700;
}
.manual-report .manual-direction-panel__status--accuracy {
display: flex;
align-items: center;
justify-content: space-between;
gap: .75rem;
margin: .75rem 0;
padding: .55rem .75rem;
border: 1px solid #5d4d92;
border-radius: .7rem;
color: #d9cfee;
background: #191630;
font-size: .85rem;
}
.manual-direction-panel__status--accuracy strong {
color: #f5edff;
font-size: 1rem;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.manual-direction-panel__open, .manual-direction-panel__close {
min-height: 2.75rem;
border: 1px solid #8d77d2;
border-radius: .7rem;
color: #e8dcff;
font: inherit;
font-weight: 750;
background: #302553;
cursor: pointer;
}
.manual-direction-panel__open {
padding: .5rem .85rem;
}
.manual-direction-panel__close {
min-width: 2.75rem;
font-size: 1.4rem;
}
.manual-report #manual-submit {
width: 100%;
max-width: 36rem;
min-height: 4.5rem;
margin-top: var(--manual-report-section-gap);
}
.manual-report__submit:disabled {
cursor: wait;
opacity: .72;
}
.manual-submission {
display: grid;
justify-items: center;
gap: .5rem;
max-width: 36rem;
margin-top: 1rem;
padding: 1.3rem;
border: 1px solid #4caa82;
border-radius: 1rem;
color: #eafff2;
text-align: center;
background: #10352e;
}
.manual-submission__icon {
display: grid;
width: 3.5rem;
height: 3.5rem;
place-items: center;
border: 2px solid #6ce4a8;
border-radius: 50%;
color: #eafff2;
font-size: 2rem;
background: #226c51;
}
.manual-submission strong {
font-size: 1.35rem;
}
.manual-submission p {
margin: 0;
line-height: 1.45;
}
.manual-submission__summary {
margin-top: .35rem !important;
color: #b2e8cf;
font-size: .9rem;
}
.manual-submission--error {
border-color: #d37c6a;
color: #fff0e8;
background: #3a1c2b;
.manual-submission__icon {
border-color: #ffac8c;
background: #9b493a;
}
}
.manual-report__submission:empty {
display: none;
}
.manual-report button:focus-visible, .manual-report input:focus-visible {
outline: 3px solid #c9b4ff;
outline-offset: 3px;
}
.manual-report__supporting {
max-width: 36rem;
margin-top: var(--manual-report-section-gap);
padding-top: 1.25rem;
border-top: 1px solid #584891;
h3 {
margin: 0;
color: #d8cffd;
font-size: 1rem;
}
.burst-listener {
width: 100%;
}
}
:root[data-theme="light"] .manual-report__quantity {
border-color: #d9b4d8;
background: #fff8fb;
#manual-occurrences {
border: 0 !important;
color: #321d42 !important;
background: transparent !important;
}
}
:root[data-theme="light"] .manual-report__stepper button,
:root[data-theme="light"] .manual-direction-panel__open,
:root[data-theme="light"] .manual-direction-panel__close {
color: #321d42;
border-color: #b68bb5;
background: #ead2eb;
}
:root[data-theme="light"] .manual-direction-panel__summary {
color: #321d42;
}
:root[data-theme="light"] .manual-report .manual-direction-panel__status--accuracy {
border-color: #cfaad1;
color: #694b68;
background: #fff8fb;
}
:root[data-theme="light"] .manual-direction-panel__status--accuracy strong {
color: #321d42;
}
:root[data-theme="light"] .manual-submission {
border-color: #54a67b;
color: #164d34;
background: #e8fff2;
}
:root[data-theme="light"] .manual-submission__icon {
color: #fff;
}
:root[data-theme="light"] .manual-submission__summary {
color: #2b6b48;
}
:root[data-theme="light"] .manual-submission--error {
border-color: #ca7d65;
color: #743520;
background: #fff0e8;
}
:root[data-theme="light"] .manual-report__supporting {
border-color: #d9b4d8;
h3 {
color: #492846;
}
}
@media (max-width: 42rem) {
.home-grid {
grid-template-columns: minmax(0, 1fr);
}
body:not(.dashboard-page) {
padding: max(1rem, env(safe-area-inset-top, 0px)) max(.5rem, env(safe-area-inset-right, 0px)) max(1rem, env(safe-area-inset-bottom, 0px)) max(.5rem, env(safe-area-inset-left, 0px));
}
.home-grid .manual-report, .dashboard-report, .dashboard-report .manual-report {
overflow: visible;
}
.manual-report {
padding: 1.25rem;
}
.dashboard-report .manual-report {
padding: 0;
}
.manual-report__header {
padding-right: 2.5rem;
}
.manual-report__header .report-clock {
width: calc(100% + 2.5rem);
max-width: none;
}
.manual-report form {
padding-bottom: calc(5rem + env(safe-area-inset-bottom, 0px));
}
.manual-report #manual-submit {
position: sticky;
bottom: calc(.5rem + env(safe-area-inset-bottom, 0px));
z-index: 10;
box-shadow: 0 .7rem 1.6rem #070a18b3;
}
body:has(#manual-occurrences:focus) .manual-report #manual-submit {
position: static;
}
.dashboard-intro {
margin-bottom: 1rem;
h1 {
font-size: clamp(2rem, 8vw, 2.8rem);
}
p:last-child {
margin-top: .75rem;
font-size: .95rem;
line-height: 1.4;
}
}
.dashboard-section {
margin-top: 1rem;
}
.dashboard-shell {
padding-bottom: calc(2rem + env(safe-area-inset-bottom, 0px));
}
.manual-report__stepper {
grid-template-columns: 3.5rem minmax(0, 1fr) 3.5rem;
}
}
@media (max-width: 23.5rem) {
.manual-report {
padding: 1rem;
}
.manual-report__quantity {
padding: .75rem;
}
.manual-report__stepper {
grid-template-columns: 3rem minmax(0, 1fr) 3rem;
gap: .25rem;
button {
width: 3rem;
height: 3rem;
}
}
}
.manual-report__heading-row {
display: flex;
align-items: center;
gap: .7rem;
}
.manual-report__fire {
flex: none;
font-size: clamp(1.8rem, 5vw, 2.5rem);
filter: drop-shadow(0 .2rem .65rem #ff703b88);
}
.manual-report__intro, .dashboard-report .manual-report__intro {
margin-bottom: .85rem;
}
.report-clock {
box-sizing: border-box;
width: 100%;
max-width: 36rem;
margin: 0 0 1rem;
padding: .65rem .95rem .7rem;
border: 1px solid #69539d;
border-radius: .85rem;
background: linear-gradient(115deg, #17162d, #10182c);
box-shadow: inset 0 1px #ffffff0a;
}
.report-clock__label {
color: #cbbce5;
font-size: .66rem;
font-weight: 750;
letter-spacing: .13em;
text-transform: uppercase;
}
.report-clock__display {
display: flex;
align-items: end;
justify-content: space-between;
gap: .75rem;
}
.report-clock__controls {
display: flex;
align-items: center;
gap: .4rem;
}
.report-clock__edit, .report-clock__reset, .report-clock__actions button {
min-height: 2.25rem;
padding: .35rem .65rem;
border: 1px solid #936ea8;
border-radius: .55rem;
color: #f5f0ff;
background: #302553;
font: inherit;
cursor: pointer;
}
.report-clock__edit { min-width: 2.25rem; font-size: 1.2rem; line-height: 1; }
.report-clock__date { display: block; margin-top: .25rem; color: #e9def8; font-size: .85rem; }
.report-clock__reset { margin-top: .6rem; }
.report-clock__editor { display: grid; gap: .5rem; margin-top: .8rem; padding-top: .8rem; border-top: 1px solid #69539d; color: #f5f0ff; }
.report-clock__fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(7rem, .6fr); gap: .6rem; }
.report-clock__fields > div { min-width: 0; }
@media (max-width: 30rem) {
.report-clock__fields { grid-template-columns: minmax(0, 1fr); }
}
.report-clock__editor label { display: block; margin-bottom: .3rem; font-weight: 650; }
.report-clock__editor input[type="date"], .report-clock__editor input[type="text"] {
box-sizing: border-box;
width: 100%;
min-height: 2.75rem;
padding: .45rem .65rem;
border: 1px solid #936ea8;
border-radius: .55rem;
color: #f5f0ff;
background: #211d3d;
color-scheme: dark;
font: inherit;
}
.report-clock__editor input[type="text"] { font-variant-numeric: tabular-nums; }
.report-clock__actions { display: flex; flex-wrap: wrap; gap: .5rem; }
.report-clock__error { margin: 0; color: #ffb9a9; }
.report-clock [hidden] { display: none !important; }
@media (max-width: 25rem) {
.report-clock__display { align-items: center; }
.report-clock__now { font-size: .6rem; }
}
.report-clock__time {
display: inline-flex;
align-items: center;
color: #ffbf72;
font-family: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;
font-size: clamp(2rem, 9vw, 2.45rem);
font-weight: 700;
line-height: 1.1;
letter-spacing: 0;
font-variant-numeric: tabular-nums;
text-shadow: 0 0 .7rem #ff963b55;
white-space: nowrap;
span {
display: inline-block;
}
#report-clock-hours, #report-clock-minutes {
width: 2ch;
}
}
.report-clock__colon {
width: 1ch;
flex: none;
margin-inline: -.08em;
line-height: 1;
text-align: center;
transform: translateY(-.06em);
animation: report-clock-blink 2s steps(1, end) infinite;
}
.report-clock__now {
display: inline-flex;
align-items: center;
gap: .4rem;
flex: none;
padding: .2rem .45rem;
border: 1px solid #93634d;
border-radius: 999px;
color: #ffd2a2;
font-size: .7rem;
font-weight: 750;
letter-spacing: .08em;
text-transform: uppercase;
}
.report-clock__dot {
width: .4rem;
height: .4rem;
border-radius: 50%;
background: #ffab5d;
}
@keyframes report-clock-blink {
50% {
opacity: 0;
}
}
.manual-direction-panel__open {
width: 100%;
text-align: left;
}
.manual-direction-panel--open .manual-compass {
width: 100%;
margin: .5rem auto 1rem;
}
.manual-direction-panel--open .manual-compass__dial {
width: min(100%, 12rem);
border-color: #8b67d4;
background: radial-gradient(circle, #302054 0 20%, #17132d 70%);
box-shadow: 0 0 0 .35rem #6640a228, 0 0 2rem #ac6aff35;
}
.manual-direction-panel--open .manual-compass__pointer {
border-bottom-color: #ff925f;
}
.manual-direction-panel--open .manual-compass__heading {
font-size: 1.1rem;
}
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit {
transition: transform .15s ease, box-shadow .15s ease, filter .15s ease;
}
.manual-report__stepper button:not(:disabled):active, .manual-direction-panel__open:active, .manual-report__submit:not(:disabled):active {
transform: scale(.97);
}
.manual-report__submit:not(:disabled):hover {
filter: brightness(1.05);
}
.manual-submission--success .manual-submission__icon {
animation: manual-confirm .35s ease-out both;
}
@keyframes manual-confirm {
from {
transform: scale(.75);
opacity: .3;
}
to {
transform: scale(1);
opacity: 1;
}
}
:root[data-theme="dark"] .home-grid .manual-report,
:root[data-theme="dark"] .dashboard-report {
border-color: #7256ab;
background: radial-gradient(circle at 88% 5%, #58254a55, transparent 13rem), linear-gradient(155deg, #151326, #0d1022 72%);
box-shadow: 0 1rem 3rem #02041399;
}
:root[data-theme="dark"] .manual-report__title {
color: #fff8f3;
}
:root[data-theme="dark"] .manual-report__intro {
color: #d6cce4;
}
:root[data-theme="dark"] .manual-report__quantity {
border-color: #514896;
background: linear-gradient(145deg, #19183a, #121834);
box-shadow: inset 0 0 0 1px #ffffff08;
}
:root[data-theme="dark"] .home-grid .manual-direction-panel,
:root[data-theme="dark"] .dashboard-report .manual-direction-panel {
border-color: #59499b;
background: linear-gradient(145deg, #211945, #151835);
}
:root[data-theme="dark"] .manual-report__supporting {
border-color: #493d7d;
background: linear-gradient(145deg, #15142f, #10162d);
}
:root[data-theme="dark"] .manual-report__stepper button {
box-shadow: 0 .25rem .7rem #07041655;
}
:root[data-theme="dark"] .manual-report__submit {
background: linear-gradient(110deg, #ffc276, #ff7654);
box-shadow: 0 .55rem 1.35rem #e2633a4d;
}
:root[data-theme="dark"] .manual-direction-panel[data-state="measuring"] {
border-color: #a27cff;
}
:root[data-theme="dark"] .manual-direction-panel[data-state="captured"] {
border-color: #68dba1;
}
:root[data-theme="dark"] .manual-direction-panel[data-state="unavailable"] {
border-color: #d38b7a;
}
:root[data-theme="light"] .report-clock {
border-color: #8b6bab;
background: linear-gradient(115deg, #221b37, #182039);
}
:root[data-theme="light"] .manual-direction-panel--open .manual-compass__dial {
background: radial-gradient(circle, #f8ebf8 0 25%, #e8d7e9 75%);
}
@media (prefers-reduced-motion: reduce) {
.manual-report__stepper button, .manual-direction-panel__open, .manual-direction-panel__close, .manual-report__submit {
transition: none;
}
.manual-submission--success .manual-submission__icon {
animation: none;
}
.report-clock__colon {
animation: none;
opacity: 1;
}
}
+4
View File
@@ -0,0 +1,4 @@
@use "settings" as settings;
// The project currently uses a system fallback stack; no web-font request is needed.
:root { --font-ui: #{settings.$font-ui}; }

Some files were not shown because too many files have changed in this diff Show More