Compare commits

...
33 Commits
Author SHA1 Message Date
Joren de Graaf 48be12c87c Ignore local database and uploaded media 2026-10-23 14:36:20 +02:00
Joren de Graaf cfc044a6b9 latest changes 2026-10-23 14:32:24 +02:00
Joren de Graaf 552b55eb2d latest changes incl grocery list 2026-10-22 10:27:11 +02:00
Joren de Graaf 30188dcb72 latest changes 2026-10-15 20:36:40 +02:00
Joren de Graaf 06c88eb98a latest changes 2026-10-15 12:50:21 +02:00
Joren de Graaf 7e22abe5d4 fix now card width 2026-10-14 18:17:27 +02:00
Joren de Graaf f68fb9e048 added scheduling 2026-10-10 16:03:14 +02:00
Joren de Graaf 51da498c0b added Arduino firmware concept files 2026-10-09 15:17:53 +02:00
Joren de Graaf aab64971a4 progressing with scss conversion 2026-10-07 13:03:22 +02:00
Joren de Graaf a27da78267 redesign clock card on manual submission 2026-10-07 09:46:19 +02:00
Joren de Graaf ac78e41328 manual submission redesign phase H - finetuning mobile 2026-10-06 20:27:54 +02:00
Joren de Graaf 2eb45139c1 manual submission redesign phase H - finetuning 2026-10-06 20:19:58 +02:00
Joren de Graaf fed8b0d20b manual submission redesign phase G 2026-10-06 20:04:21 +02:00
Joren de Graaf 5951f6aed8 manual submission redesign phase F 2026-10-06 19:57:14 +02:00
Joren de Graaf e2f1ddfd92 manual submission redesign phase E 2026-10-06 19:54:08 +02:00
Joren de Graaf 664f28ca31 manual submission redesign phase D - compiled 2026-10-06 19:51:27 +02:00
Joren de Graaf a4897d1733 manual submission redesign phase D 2026-10-06 19:50:52 +02:00
Joren de Graaf b8ba6a7d97 manual submission redesign phase C 2026-10-06 19:47:10 +02:00
Joren de Graaf 56733c93b9 manual submission redesign phase B 2026-10-06 19:44:24 +02:00
Joren de Graaf a2844e0dc1 manual submission redesign phase A 2026-10-06 19:39:57 +02:00
Joren de Graaf c8df34982b latest changes before manual submissions redesign 2026-10-06 19:31:30 +02:00
Joren de Graaf 037797aa89 browser audio detection phase 4 2026-10-02 21:45:24 +02:00
Joren de Graaf 20bdabdd8f browser audio detection phase 3 2026-10-02 21:34:38 +02:00
Joren de Graaf 5c0ca7bc47 browser audio detection phase 2 2026-10-02 16:57:12 +02:00
Joren de Graaf 9c466f8f55 browser audio processing phase 1 2026-10-02 16:44:15 +02:00
Joren de Graaf ab6cfc0bae sensors added to settings 2026-10-02 15:38:18 +02:00
Joren de Graaf 428caef29d mobile menu added 2026-10-02 13:13:38 +02:00
Joren de Graaf 5410fec8f2 added translations 2026-10-01 22:43:45 +02:00
Joren de Graaf 2c4cd61a63 add dashboard to home 2026-10-01 17:29:29 +02:00
Joren de Graaf 7d538b774d added light/dark mode toggle v1, unified menu 2026-10-01 17:14:19 +02:00
Joren de Graaf 8f838715dd added compass direction finding 2026-10-01 16:38:13 +02:00
Joren de Graaf 9ebf24e028 latest changes 2026-09-29 12:12:46 +02:00
Joren de Graaf 966d6602c2 initial commit 2026-09-26 20:59:01 +02:00
819 changed files with 80557 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# Frontend development server
VITE_HOST=127.0.0.1
VITE_PORT=5173
VITE_DEV_SERVER_URL=http://127.0.0.1:5173/
# Development-only Vite base; keep this aligned with VITE_DEV_SERVER_URL.
VITE_DEV_BASE_URL=/
VITE_USE_DEV_SERVER=true
# Django development process (override the whole command for uv, docker, etc.)
DJANGO_HOST=127.0.0.1
DJANGO_PORT=8000
# DJANGO_DEV_COMMAND=python manage.py runserver 127.0.0.1:8000
# Vite discovers every .js file beneath VITE_ENTRY_DIR by default.
VITE_ENTRY_DIR=frontend/src/entries
# Production build output and Django static namespace
VITE_OUT_DIR=vite_integration/static/vite
VITE_STATIC_PREFIX=vite
# Must match Django STATIC_URL plus VITE_STATIC_PREFIX (for example, /static/vite/).
VITE_BASE_URL=/static/vite/
+7
View File
@@ -0,0 +1,7 @@
vite_integration/static/vite/*
!vite_integration/static/vite/.gitkeep
node_modules/
# Local database and uploaded media
/db.sqlite3
/media/
+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.
+245
View File
@@ -0,0 +1,245 @@
# Ntfy blueprint for a Django tasks and health tracker
This is a portable version of this project's `/settings` integration. It gives each user a topic URL, a test button, an enable switch, and one function that task or health code can call. Replace `accounts` with the app that owns your user preferences. The examples assume an authenticated `/settings/` page and Django's standard CSRF and messages middleware.
## 1. Store preferences
In `accounts/models.py` (merge these fields into an existing per-user settings model if you have one):
```python
from django.conf import settings
from django.db import models
class NotificationSettings(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ntfy_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
```
Run `python manage.py makemigrations accounts` and `python manage.py migrate`.
## 2. Add the sender
Create `notifications/services.py` (and an empty `notifications/__init__.py` if needed):
```python
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
class NotificationError(Exception):
"""A delivery error safe to display to a user."""
def send_ntfy_notification(url, title, message, timeout=10):
request = Request(
url,
data=message.encode("utf-8"),
headers={"Content-Type": "text/plain; charset=utf-8", "Title": title},
method="POST",
)
try:
with urlopen(request, timeout=timeout) as response:
status = response.getcode()
except HTTPError as error:
raise NotificationError(f"ntfy server responded with HTTP {error.code}.") from error
except (TimeoutError, socket.timeout):
raise NotificationError("Connection to the ntfy server timed out.") from None
except URLError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
except OSError as error:
raise NotificationError("Could not connect to the ntfy server.") from error
if not 200 <= status < 300:
raise NotificationError(f"ntfy server responded with HTTP {status}.")
def send_notification(user, title, message):
from accounts.models import NotificationSettings
preferences = NotificationSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
return True
```
The URL is a destination and may contain a private topic name. Keep it out of logs and error messages. A user supplied server URL also lets the server make outbound requests; restrict destinations or allow only your trusted ntfy host if your deployment needs that boundary. Add authentication headers if your ntfy server requires them; this example uses a topic URL only.
## 3. Form, views, and routes
In `accounts/forms.py`:
```python
from django import forms
from .models import NotificationSettings
class NotificationSettingsForm(forms.ModelForm):
class Meta:
model = NotificationSettings
fields = ["ntfy_url", "ntfy_enabled"]
widgets = {"ntfy_url": forms.URLInput(attrs={"id": "ntfy-url", "placeholder": "https://ntfy.example.com/my-topic"})}
def clean_ntfy_url(self):
return self.cleaned_data["ntfy_url"].strip()
def clean(self):
data = super().clean()
if data.get("ntfy_enabled") and not data.get("ntfy_url"):
self.add_error("ntfy_url", "Enter a topic URL before enabling notifications.")
return data
```
In `accounts/views.py`:
```python
from hashlib import sha256
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.shortcuts import redirect, render
from django.utils import timezone
from django.views.decorators.http import require_POST
from notifications.services import NotificationError, send_ntfy_notification
from .forms import NotificationSettingsForm
from .models import NotificationSettings
def test_key(user):
return f"ntfy_tested_url_fingerprint:{user.pk}"
def fingerprint(url):
return sha256(url.encode("utf-8")).hexdigest()
@login_required
def settings_page(request):
preferences, _ = NotificationSettings.objects.get_or_create(user=request.user)
old_url = preferences.ntfy_url
form = NotificationSettingsForm(request.POST or None, instance=preferences)
if request.method == "POST" and form.is_valid():
url = form.cleaned_data["ntfy_url"]
just_tested = bool(url) and request.session.get(test_key(request.user)) == fingerprint(url)
previously_tested = url == old_url and preferences.ntfy_last_tested_at is not None
if form.cleaned_data["ntfy_enabled"] and not (just_tested or previously_tested):
form.add_error("ntfy_url", "Test this URL successfully before enabling notifications.")
else:
preferences = form.save(commit=False)
if not url:
preferences.ntfy_enabled = False
preferences.ntfy_last_tested_at = None
elif just_tested:
preferences.ntfy_last_tested_at = timezone.now()
elif url != old_url:
preferences.ntfy_last_tested_at = None
preferences.save()
request.session.pop(test_key(request.user), None)
messages.success(request, "Notification settings saved.")
return redirect("settings_page")
return render(request, "accounts/settings.html", {"form": form})
@login_required
@require_POST
def test_ntfy(request):
url = request.POST.get("ntfy_url", "").strip()
try:
URLValidator(schemes=["http", "https"])(url)
except ValidationError:
return render(request, "accounts/ntfy_test_result.html", {"error": "Enter a valid HTTP or HTTPS topic URL."}, status=400)
try:
send_ntfy_notification(url, "Tasks & Health", "Test notification sent successfully.")
except NotificationError as error:
return render(request, "accounts/ntfy_test_result.html", {"error": str(error)}, status=502)
request.session[test_key(request.user)] = fingerprint(url)
return render(request, "accounts/ntfy_test_result.html", {"success": True})
```
In `accounts/urls.py`, include these routes under `/settings/` in the project URLconf:
```python
from django.urls import path
from . import views
urlpatterns = [
path("", views.settings_page, name="settings_page"),
path("notifications/ntfy/test/", views.test_ntfy, name="ntfy_test"),
]
```
## 4. Settings UI
Put this section inside your existing `/settings/` template. It uses htmx for the inline test response; load htmx once in the page layout (or replace `hx-post` with a small `fetch` handler). Keep the CSRF input inside the form.
```html
<form method="post" action="{% url 'settings_page' %}">
{% csrf_token %}
<section aria-labelledby="ntfy-title">
<h2 id="ntfy-title">Notifications / ntfy</h2>
<p>Use a topic URL from your ntfy server. Test it before enabling notifications.</p>
<label for="ntfy-url">Topic URL</label>
{{ form.ntfy_url }} {{ form.ntfy_url.errors }}
<div class="check">
{{ form.ntfy_enabled }}
<label for="{{ form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label>
</div>
<button type="button" hx-post="{% url 'ntfy_test' %}"
hx-include="#ntfy-url, [name='csrfmiddlewaretoken']"
hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
<div id="ntfy-test-result" aria-live="polite"></div>
</section>
<button type="submit">Save settings</button>
</form>
<script>
document.querySelector("#ntfy-url").addEventListener("input", () => {
document.querySelector("#ntfy-test-result").replaceChildren();
});
</script>
```
`accounts/ntfy_test_result.html`:
```html
{% if success %}<div class="alert alert--success">✓ Test notification sent successfully.</div>
{% else %}<div class="alert alert--error">Could not send the test notification: {{ error }}</div>{% endif %}
```
Suggested CSS, scoped to your existing settings styles:
```css
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
.check { display: flex; gap: .6rem; align-items: center; }
.check label { margin: 0; }
.alert { margin-top: 1rem; padding: .75rem; border-radius: .55rem; }
.alert--success { color: #d1fae5; background: #14532d; }
.alert--error { color: #fee2e2; background: #7f1d1d; }
```
## 5. Trigger from tasks or health events
Call the provider agnostic `send_notification` after a meaningful state change. Put delivery on a background worker for normal operation, since the HTTP call can take up to ten seconds. Queue the job after the database commit so it cannot announce a rolled back change.
```python
from django.db import transaction
# After saving a task completion, missed deadline, check-in, or health alert:
user_id = task.user_id
task_id = task.pk
transaction.on_commit(lambda: enqueue_task_event_notification(user_id, task_id))
```
`enqueue_task_event_notification` is your existing Celery, RQ, or job queue entry point. In its worker, reload the user and task, confirm that the event still qualifies, then call `send_notification(user, "Task due", "Your task is due today.")`. Catch `NotificationError`, log a safe error without the topic URL, and retry according to your queue policy. Use an event ID or unique job key if duplicate delivery matters. If you have no worker yet, a management command run by cron can drain a small notification outbox instead.
Typical mapping for this app:
| App event | Suggested message | Trigger location |
| --- | --- | --- |
| Task due | “Your task is due today.” | Scheduled due-date job |
| Task completed | “Task completed.” | Completion service, after commit |
| Check-in missed | “Your daily check-in is still open.” | Scheduled reminder job |
| Health threshold crossed | “A tracked value crossed your chosen threshold.” | Threshold evaluator, after commit |
Avoid including sensitive health measurements in the notification unless the user explicitly opts in. Define the event's recipient and idempotency rule in the app service, rather than in the ntfy sender.
## 6. Minimum verification
Test an invalid URL, a failed test, a successful test followed by save, a changed URL requiring a new test, and disabled settings suppressing sends. Mock `urlopen` or `send_ntfy_notification`; do not send real notifications in tests. Check one actual device delivery manually with a private topic before enabling event triggers.
Source implementation in this repo: `members/views.py`, `members/forms.py`, `members/models.py`, `members/templates/members/user_settings.html`, `notifications/services.py`, and `fireworks_detect/signals.py`. The source app groups Pending events by minute with `PendingNotificationBatch` and a scheduled command; use that pattern if your tracker needs digest notifications.
+163
View File
@@ -0,0 +1,163 @@
# Portable Django + Vite integration
This repository originally used only Django native static files. The Vite integration below is now wired into the rendered public pages and custom Admin pages: shared assets live in `frontend/src/`, while Django still owns template rendering and its native static files.
## What is included
- `vite_integration/`: reusable Django app and `{% vite_asset %}` tag
- `frontend/src/entries/`: one Vite entry module per rendered page, with shared `styles/` and `scripts/` modules
- `vite.config.mjs`: Vite output, manifest, host, port, and entry configuration
- `package.json`: `dev`, `django`, `vite`, and `build` scripts
- `scripts/dev-django.mjs`: configurable backend process for `concurrently`
- `.env.vite.example`: documented development and production variables
Vite builds into `vite_integration/static/vite/`. Because this is a Django app static directory, Django's staticfiles finders and `collectstatic` discover the manifest and built assets automatically.
## Prerequisites
- Python and the Django environment for the project
- Node.js 20+ and npm
- A configured Django `STATIC_URL` and `STATIC_ROOT` for production
## Install in this repository
```sh
cp .env.vite.example .env.vite
npm install
set -a; . ./.env.vite; set +a
npm run dev
```
`npm run dev` starts Django and Vite together using `concurrently`. It runs `python manage.py runserver 127.0.0.1:8000` and Vite on `127.0.0.1:5173` by default. Change the variables before starting it, or set `DJANGO_DEV_COMMAND` to replace the backend command completely.
## Add an entry point to a template
Choose an entry point and include it once in the relevant base template:
```django
{% load vite %}
{% vite_asset "frontend/src/entries/site.js" %}
```
The tag renders Vite's HMR client and the entry point when `VITE_USE_DEV_SERVER=true`. Otherwise it reads Vite's manifest and renders the fingerprinted CSS and JavaScript under Django's static URL. See `vite_integration/templates/vite_integration/example_assets.html` for the same snippet.
## Production
```sh
set -a; . ./.env.vite; set +a
VITE_USE_DEV_SERVER=false npm run build
VITE_USE_DEV_SERVER=false python manage.py collectstatic --noinput
```
Build before `collectstatic`. The generated `vite/.vite/manifest.json` and `vite/assets/*` are collected with all other Django static files. Do not use the Vite development server in production.
## Reuse in a fresh Django project
Copy these files and directories:
```text
vite_integration/
frontend/src/
scripts/dev-django.mjs
vite.config.mjs
package.json
.env.vite.example
```
Create `frontend/src/entries/site.js` (or another entry beneath `VITE_ENTRY_DIR`) that imports the page CSS and JavaScript. Then add `vite_integration` to `INSTALLED_APPS`, add the template tag to a base template, configure `STATIC_URL`/`STATIC_ROOT`, install npm packages, and use the development or production commands above. The integration contains no application names, routes, or backend URLs.
## Configuration values to customize
| Variable/setting | Default | Purpose |
| --- | --- | --- |
| `DJANGO_DEV_COMMAND` | `python manage.py runserver <host>:<port>` | Complete backend development command |
| `DJANGO_HOST`, `DJANGO_PORT` | `127.0.0.1`, `8000` | Default backend bind address |
| `VITE_HOST`, `VITE_PORT` | `127.0.0.1`, `5173` | Vite bind address and port |
| `VITE_DEV_SERVER_URL` | `http://127.0.0.1:5173/` | URL Django templates use for HMR |
| `VITE_DEV_BASE_URL` | `/` | Development-only Vite base path |
| `VITE_USE_DEV_SERVER` | `false` | Enables HMR tags; set only for development |
| `VITE_ENTRY_DIR` | `frontend/src/entries` | Directory Vite scans for page entry points |
| `VITE_ENTRY` | unset | Optional comma-separated explicit entry point list |
| `VITE_OUT_DIR` | `vite_integration/static/vite` | Build output relative to project root |
| `VITE_STATIC_PREFIX` | `vite` | Django static namespace for built files |
| `VITE_BASE_URL` | `/static/vite/` | Public base URL emitted by Vite |
| `VITE_MANIFEST_PATH` | staticfiles finder | Optional explicit manifest location |
Django settings override environment variables with the same names. `VITE_BASE_URL` must equal the public `STATIC_URL` followed by `VITE_STATIC_PREFIX` (for example, `/static/vite/`). A `.env.vite` file is not automatically read by Django; export/source it in the process manager, shell, container, or deployment configuration.
## Troubleshooting
- **Vite manifest not found:** run `npm run build` before `collectstatic`; check that `VITE_OUT_DIR` ends below a Django app `static/` directory and that its final segment matches `VITE_STATIC_PREFIX`.
- **Browser cannot reach HMR:** set `VITE_DEV_SERVER_URL` to the browser-reachable Vite address, and use matching `VITE_HOST`/`VITE_PORT`. For containers or remote browsers this is often `0.0.0.0` for the host plus a public hostname for the URL.
- **A page fails in development:** set `VITE_USE_DEV_SERVER=true` only while `npm run vite` or `npm run dev` is running.
- **Assets return 404 after deployment:** rerun both the build and `collectstatic`; ensure the web server serves `STATIC_ROOT` at `STATIC_URL`.
## Interface translations
English text in templates and Python is the source language. Dutch translations live in `locale/nl/LC_MESSAGES/django.po`; the compiled `django.mo` is used at runtime. Logged-in users choose their language at `/settings/`. Visitors use the language switcher in the public navigation, which saves Django's standard language cookie. URLs and stored status or source codes do not change with the language.
Update translations after changing user-facing source text:
```bash
python manage.py makemessages -l nl --ignore=node_modules --ignore=staticfiles --ignore='*.orig'
# Edit locale/nl/LC_MESSAGES/django.po
python manage.py compilemessages
```
The small amount of JavaScript UI text is translated by Django in `templates/js_translations.html` and read from `window.BOOMCAST_I18N`. After changing JavaScript, run `npm run build` and `python manage.py collectstatic --noinput` for production. Classifier class names, API keys, sensor tokens, H3 values and stored source/status values remain language-neutral.
## Browser Processing Beta
The administrator setting `browser_processing_beta_enabled` is off by default.
When enabled, the upload form shows **Process recording in this browser (Beta)**,
which also starts off. With the user toggle off, ordinary audio uses the
existing server upload and classifier. With it on, selected audio is checked
locally and selected video is converted to 16 kHz mono WAV before the local
check. Files the user submits still run through the server classifier.
Switching back to server mode cancels browser work and clears the local gate.
The server upload endpoint currently accepts audio, so a video selected in
server mode requires an audio file or browser mode.
Browser assets are loaded only after the user enables the toggle and selects a
file. Regenerate the self-hosted model using [the YAMNet build guide](scripts/BROWSER_YAMNET.md),
then run `npm run build` and `python manage.py collectstatic --noinput`.
# Pending event notifications
Users can test and enable an ntfy topic in Settings. New Pending events are
counted by source (manual or sensor) in one-minute batches per enabled user.
Run `python manage.py send_pending_notifications` once per minute with the
application's Python environment and working directory. For example, a cron
entry can use `* * * * * cd /path/to/django && /path/to/python manage.py send_pending_notifications`.
It sends completed minute batches,
then removes them; failed deliveries remain queued for the next run.
For a systemd user timer on the laptop, install the units in
[`deploy/systemd/`](deploy/systemd/) and start the timer:
```sh
cd /home/jorenmartijn/python/django
/usr/bin/python3 -m venv /home/jorenmartijn/python/.venv-notifications
/home/jorenmartijn/python/.venv-notifications/bin/python -m pip install -r requirements.txt
/home/jorenmartijn/python/.venv-notifications/bin/python manage.py check
mkdir -p ~/.config/systemd/user
cp deploy/systemd/send-pending-notifications.service deploy/systemd/send-pending-notifications.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now send-pending-notifications.timer
systemctl --user list-timers send-pending-notifications.timer
```
The service runs `/home/jorenmartijn/python/.venv-notifications/bin/python` with this
project as its working directory. To keep the user timer running after logout,
run `sudo loginctl enable-linger jorenmartijn` once on the laptop. Check a run
with `journalctl --user -u send-pending-notifications.service -n 30`.
### 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,7 @@
[Unit]
Description=Send batched Pending event ntfy notifications
[Service]
Type=oneshot
WorkingDirectory=/home/jorenmartijn/python/django
ExecStart=/home/jorenmartijn/python/.venv-notifications/bin/python /home/jorenmartijn/python/django/manage.py send_pending_notifications
@@ -0,0 +1,11 @@
[Unit]
Description=Send Pending event ntfy summaries every minute
[Timer]
OnCalendar=*-*-* *:*:00
AccuracySec=1s
Persistent=true
Unit=send-pending-notifications.service
[Install]
WantedBy=timers.target
@@ -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"}'
```
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+265
View File
@@ -0,0 +1,265 @@
import json
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.contrib import admin, messages
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, format_html_join
from django.utils.translation import gettext as _, gettext_lazy, ngettext
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")
list_filter = ("rule_type", "enabled")
search_fields = ("value",)
@admin.register(BrowserProcessingSettings)
class BrowserProcessingSettingsAdmin(admin.ModelAdmin):
list_display = ("beta_status",)
readonly_fields = ("beta_status",)
fieldsets = (
(gettext_lazy("Browser-side media processing (Beta)"), {
"fields": ("beta_status", "browser_processing_beta_enabled"),
"description": gettext_lazy(
"Enables experimental client-side video audio extraction and YAMNet pre-classification. "
"Browser compatibility may vary. Disabling this restores the normal server-side submission flow."
),
}),
)
@admin.display(description=gettext_lazy("Beta status"))
def beta_status(self, obj):
if obj and obj.browser_processing_beta_enabled:
return format_html('<strong style="color:#166534">{}</strong>', _("Enabled"))
return format_html('<strong style="color:#991b1b">{}</strong>', _("Disabled — normal submission"))
def has_add_permission(self, request):
return super().has_add_permission(request) and not BrowserProcessingSettings.objects.exists()
def has_delete_permission(self, request, obj=None):
return False
class ClassificationAdmin(admin.ModelAdmin):
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", "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"))
def direction_display(self, obj):
return obj.direction_display
@admin.display(description=gettext_lazy("Classifier response"))
def pretty_classifier_response(self, obj):
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
@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):
custom_urls = [
path(
"<path:object_id>/classify/",
self.admin_site.admin_view(self.classify_record),
name="fireworks_detect_pendingevent_classify",
),
]
return custom_urls + super().get_urls()
def classify_record(self, request, object_id):
if request.method != "POST":
return HttpResponseNotAllowed(["POST"])
pending = get_object_or_404(PendingEvent, pk=object_id)
if not self.has_change_permission(request, pending):
raise PermissionDenied
change_url = reverse("admin:fireworks_detect_pendingevent_change", args=[pending.pk])
if not pending.audio_file:
self.message_user(request, _("This Pending event has no attached audio to classify."), messages.ERROR)
return redirect(change_url)
try:
if pending.audio_file.size > classifier_views.MAX_AUDIO_SIZE:
self.message_user(request, _("The attached audio exceeds the 25 MiB limit."), messages.ERROR)
return redirect(change_url)
with pending.audio_file.open("rb") as audio:
body, content_type = classifier_views._encode_audio_multipart(audio)
classifier_request = Request(
classifier_views.CLASSIFIER_URL,
data=body,
headers={"Content-Type": content_type, "Accept": "application/json"},
method="POST",
)
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 a JSON object")
except HTTPError as error:
self.message_user(request, _("The classifier returned HTTP %(code)s.") % {"code": error.code}, messages.ERROR)
return redirect(change_url)
except (URLError, TimeoutError, OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError):
self.message_user(request, _("The classifier could not be reached or returned invalid JSON."), messages.ERROR)
return redirect(change_url)
previous_response = pending.classifier_response if isinstance(pending.classifier_response, dict) else {}
pending.classifier_response = {**previous_response, **payload}
pending.save(update_fields=["classifier_response"])
self.message_user(request, _("Classification saved. This event remains Pending."), messages.SUCCESS)
return redirect(change_url)
def has_add_permission(self, request):
return False
@admin.action(description=gettext_lazy("Approve selected samples and move them to Events"))
def approve_selected(self, request, queryset):
approved = 0
for pending in queryset:
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)
@admin.action(description=gettext_lazy("Deny selected samples and delete their uploaded audio"))
def deny_selected(self, request, queryset):
denied = 0
for pending in queryset:
pending.deny()
denied += 1
self.message_user(request, ngettext("%(count)d sample denied and removed.", "%(count)d samples denied and removed.", denied) % {"count": denied}, messages.WARNING)
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
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")
list_filter = ("is_active", "owner", "archived_at")
search_fields = ("name", "token_prefix", "owner__username", "owner__email")
readonly_fields = ("token_prefix", "last_heartbeat", "last_submission", "created_at", "archived_at")
actions = ("issue_api_token",)
fieldsets = (
(gettext_lazy("Sensor"), {"fields": ("name", "owner", "is_active", "created_at", "archived_at")}),
(gettext_lazy("API token"), {"fields": ("token_prefix",), "description": gettext_lazy("Save the sensor first, select it in the list, then choose ‘Issue or rotate API token’. The complete token is shown once only; its salted hash is the only value stored.")}),
(gettext_lazy("Heartbeat"), {"fields": ("last_heartbeat", "last_submission"), "description": gettext_lazy("Devices should POST to /fireworks/heartbeat/ with Authorization: Bearer <token>. Green means seen within 5 minutes; amber within 15; red is older or never seen.")}),
)
@admin.display(description=gettext_lazy("Heartbeat"))
def heartbeat_light(self, obj):
status, label = obj.heartbeat_status()
colour = {"online": "#22c55e", "delayed": "#f59e0b"}.get(status, "#ef4444")
return format_html('<span style="display:inline-flex;align-items:center;gap:6px"><span style="width:10px;height:10px;border-radius:50%;background:{}"></span>{}</span>', colour, label)
@admin.action(description=gettext_lazy("Issue or rotate API token (shown once)"))
def issue_api_token(self, request, queryset):
if queryset.count() != 1:
self.message_user(request, _("Select exactly one sensor to issue a token."), messages.ERROR)
return
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
+52
View File
@@ -0,0 +1,52 @@
import json
from django.contrib import admin, messages
from django.utils.html import format_html
from .models import Event, PendingEvent
class ClassificationAdmin(admin.ModelAdmin):
list_display = ("original_filename", "primary_label", "primary_score", "duration", "created_at")
list_filter = ("created_at",)
search_fields = ("original_filename",)
readonly_fields = ("audio_file", "original_filename", "created_at", "pretty_classifier_response")
fields = ("audio_file", "original_filename", "created_at")
change_form_template = "admin/fireworks_detect/classification_change_form.html"
@admin.display(description="Classifier response")
def pretty_classifier_response(self, obj):
return format_html("<pre>{}</pre>", json.dumps(obj.classifier_response, indent=2, sort_keys=True))
@admin.register(PendingEvent)
class PendingEventAdmin(ClassificationAdmin):
actions = ("approve_selected", "deny_selected")
def has_add_permission(self, request):
return False
@admin.action(description="Approve selected samples and move them to Events")
def approve_selected(self, request, queryset):
approved = 0
for pending in queryset:
pending.approve()
approved += 1
self.message_user(request, f"{approved} sample(s) approved and moved to Events.", messages.SUCCESS)
@admin.action(description="Deny selected samples and delete their uploaded audio")
def deny_selected(self, request, queryset):
denied = 0
for pending in queryset:
pending.deny()
denied += 1
self.message_user(request, f"{denied} sample(s) denied and removed.", messages.WARNING)
@admin.register(Event)
class EventAdmin(ClassificationAdmin):
readonly_fields = ClassificationAdmin.readonly_fields + ("approved_at",)
fields = ClassificationAdmin.fields + ("approved_at",)
def has_add_permission(self, request):
return False
+8
View File
@@ -0,0 +1,8 @@
from django.apps import AppConfig
class FireworksDetectConfig(AppConfig):
name = 'fireworks_detect'
def ready(self):
from . import signals # noqa: F401
+84
View File
@@ -0,0 +1,84 @@
"""Public, advisory configuration for the optional browser processing beta."""
import json
from pathlib import Path
from django.templatetags.static import static
from django.urls import reverse
from .models import BrowserProcessingSettings, ClassificationRule
POLICY_VERSION = 1
SPEECH_LABEL_TERMS = (
"speech", "conversation", "narration", "monologue", "babbling", "whisper",
"speaking", "speech synthesizer",
)
GATE_RESULTS = {"whitelist_match", "speech_only", "no_match", "unavailable", "error"}
RELEVANCE_THRESHOLD = 0.5
SPEECH_THRESHOLD = 0.5
MODEL_VERSION = "google-yamnet-1"
def browser_config():
"""Keep template configuration in one small, non-secret object."""
return {
"browserProcessingBeta": BrowserProcessingSettings.enabled(),
"policyUrl": reverse("fireworks_detect:browser_policy"),
"policyVersion": POLICY_VERSION,
}
def browser_policy():
enabled = BrowserProcessingSettings.enabled()
policy = {
"version": POLICY_VERSION,
"browser_processing_beta_enabled": enabled,
"whitelist": [],
"privacy_sensitive_speech": [],
"thresholds": {},
"model_version": MODEL_VERSION,
"model_url": "",
"class_map_url": "",
}
if not enabled:
return policy
rules = ClassificationRule.objects.filter(enabled=True).order_by("value")
policy["whitelist"] = list(rules.filter(rule_type=ClassificationRule.RuleType.WHITELIST).values_list("value", flat=True))
class_map_path = Path(__file__).parent / "static/browser-yamnet/yamnet_class_map.json"
class_names = json.loads(class_map_path.read_text(encoding="utf-8"))
speech_classes = {name for name in class_names if any(term in name.lower() for term in SPEECH_LABEL_TERMS)}
speech_classes.update(value for value in rules.filter(rule_type=ClassificationRule.RuleType.BLACKLIST).values_list("value", flat=True)
if any(term in value.lower() for term in SPEECH_LABEL_TERMS))
policy["privacy_sensitive_speech"] = sorted(speech_classes)
policy["thresholds"] = {"relevance": RELEVANCE_THRESHOLD, "speech": SPEECH_THRESHOLD}
policy["model_url"] = static("browser-yamnet/model.json")
policy["class_map_url"] = static("browser-yamnet/yamnet_class_map.json")
return policy
def advisory_browser_metadata(post_data):
"""Parse bounded diagnostics; never use this to authorize or classify audio."""
raw = post_data.get("browser_processing_metadata", "")
if not raw or len(raw) > 1024:
return {}
try:
submitted = json.loads(raw)
except (TypeError, ValueError):
return {}
if not isinstance(submitted, dict):
return {}
metadata = {}
for key in ("browser_processing_used", "browser_override"):
if type(submitted.get(key)) is bool:
metadata[key] = submitted[key]
version = submitted.get("browser_processing_version")
if type(version) is int and 0 < version <= POLICY_VERSION:
metadata["browser_processing_version"] = version
gate_result = submitted.get("browser_gate_result")
if isinstance(gate_result, str) and gate_result in GATE_RESULTS:
metadata["browser_gate_result"] = gate_result
speech = submitted.get("browser_speech_detected")
if type(speech) is bool:
metadata["browser_speech_detected"] = speech
return metadata
+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"
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from .views import classification_blacklist, classification_whitelist
app_name = "classification_rules"
urlpatterns = [
path("whitelist/", classification_whitelist, name="whitelist"),
path("blacklist/", classification_blacklist, name="blacklist"),
]
+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
+42
View File
@@ -0,0 +1,42 @@
import h3
from django.conf import settings
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
def h3_resolution():
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
return resolution
def cell_from_coordinates(latitude, longitude):
if latitude is None or longitude is None:
return None
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
def cell_boundary(cell):
try:
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
except (ValueError, h3.H3Error):
return None
def cell_center(cell):
"""Return the centre of an H3 cell without exposing its source coordinate."""
try:
latitude, longitude = h3.cell_to_latlng(cell)
return [latitude, longitude]
except (ValueError, h3.H3Error):
return None
def cell_disk(cell, distance=1):
try:
return sorted(h3.grid_disk(cell, distance))
except (ValueError, h3.H3Error):
return []
+33
View File
@@ -0,0 +1,33 @@
import h3
from django.conf import settings
H3_RESOLUTION_SETTING = "FIREWORKS_H3_RESOLUTION"
def h3_resolution():
resolution = getattr(settings, H3_RESOLUTION_SETTING, 9)
if isinstance(resolution, bool) or not isinstance(resolution, int) or not 0 <= resolution <= 15:
raise ValueError(f"{H3_RESOLUTION_SETTING} must be an integer between 0 and 15.")
return resolution
def cell_from_coordinates(latitude, longitude):
if latitude is None or longitude is None:
return None
return h3.latlng_to_cell(float(latitude), float(longitude), h3_resolution())
def cell_boundary(cell):
try:
return [[latitude, longitude] for latitude, longitude in h3.cell_to_boundary(cell)]
except (ValueError, h3.H3Error):
return None
def cell_disk(cell, distance=1):
try:
return sorted(h3.grid_disk(cell, distance))
except (ValueError, h3.H3Error):
return []
+1
View File
@@ -0,0 +1 @@
"""Management commands for fireworks detection."""
@@ -0,0 +1 @@
"""Fireworks detection management commands."""
@@ -0,0 +1,25 @@
from django.core.management.base import BaseCommand
from fireworks_detect.h3_utils import cell_from_coordinates, h3_resolution
from fireworks_detect.models import Event, PendingEvent
class Command(BaseCommand):
help = "Populate H3 cells for coordinate-bearing Pending and approved events."
def handle(self, *args, **options):
updated = 0
for model in (PendingEvent, Event):
for record in model.objects.exclude(latitude__isnull=True).exclude(longitude__isnull=True):
h3_cell = cell_from_coordinates(record.latitude, record.longitude)
if record.h3_cell == h3_cell:
continue
record.h3_cell = h3_cell
record.save(update_fields=["h3_cell"])
updated += 1
self.stdout.write(
self.style.SUCCESS(
f"Updated {updated} record(s) at H3 resolution {h3_resolution()}."
)
)
@@ -0,0 +1,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,47 @@
# Generated by Django 6.1.1 on 2026-09-26 13:34
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('original_filename', models.CharField(max_length=255)),
('classifier_response', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('approved_at', models.DateTimeField(auto_now_add=True)),
],
options={
'verbose_name': 'Event',
'verbose_name_plural': 'Events',
'ordering': ['-created_at'],
'abstract': False,
},
),
migrations.CreateModel(
name='PendingEvent',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('audio_file', models.FileField(upload_to='fireworks_audio/%Y/%m/%d')),
('original_filename', models.CharField(max_length=255)),
('classifier_response', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
],
options={
'verbose_name': 'Pending event',
'verbose_name_plural': 'Pending',
'ordering': ['-created_at'],
'abstract': False,
},
),
]
@@ -0,0 +1,40 @@
# Generated by Django 6.1.1 on 2026-09-26 14:16
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Sensor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='A recognisable device name, e.g. Garden ESP32.', max_length=100, unique=True)),
('is_active', models.BooleanField(default=True)),
('token_prefix', models.CharField(blank=True, editable=False, max_length=15)),
('token_hash', models.CharField(blank=True, editable=False, max_length=256)),
('last_heartbeat', models.DateTimeField(blank=True, editable=False, null=True)),
('last_submission', models.DateTimeField(blank=True, editable=False, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='event',
name='sensor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_records', to='fireworks_detect.sensor'),
),
migrations.AddField(
model_name='pendingevent',
name='sensor',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_records', to='fireworks_detect.sensor'),
),
]
@@ -0,0 +1,35 @@
# Generated by Django 6.1.1 on 2026-09-29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0002_sensor_event_sensor_pendingevent_sensor"),
]
operations = [
migrations.CreateModel(
name="ClassificationRule",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("value", models.CharField(max_length=255)),
(
"rule_type",
models.CharField(
choices=[("whitelist", "Whitelist"), ("blacklist", "Blacklist")],
max_length=10,
),
),
("enabled", models.BooleanField(default=True)),
],
options={
"ordering": ["value"],
},
),
migrations.AddConstraint(
model_name="classificationrule",
constraint=models.UniqueConstraint(fields=("value", "rule_type"), name="unique_classification_rule"),
),
]
@@ -0,0 +1,63 @@
# Generated by Django 6.1.1 on 2026-09-29 20:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0003_classificationrule'),
]
operations = [
migrations.AddField(
model_name='event',
name='location',
field=models.CharField(blank=True, max_length=255),
),
migrations.AddField(
model_name='event',
name='occurrences',
field=models.PositiveIntegerField(default=1),
),
migrations.AddField(
model_name='event',
name='source_type',
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
),
migrations.AddField(
model_name='event',
name='visually_confirmed',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='pendingevent',
name='location',
field=models.CharField(blank=True, max_length=255),
),
migrations.AddField(
model_name='pendingevent',
name='occurrences',
field=models.PositiveIntegerField(default=1),
),
migrations.AddField(
model_name='pendingevent',
name='source_type',
field=models.CharField(choices=[('sensor', 'Sensor'), ('manual', 'Manual report')], default='sensor', max_length=10),
),
migrations.AddField(
model_name='pendingevent',
name='visually_confirmed',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='event',
name='audio_file',
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
),
migrations.AlterField(
model_name='pendingevent',
name='audio_file',
field=models.FileField(blank=True, upload_to='fireworks_audio/%Y/%m/%d'),
),
]
@@ -0,0 +1,33 @@
# Generated by Django 6.1.1 on 2026-09-29 21:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0004_event_location_event_occurrences_event_source_type_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='latitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='event',
name='longitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='latitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='longitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True),
),
]
@@ -0,0 +1,23 @@
# Generated by Django 6.1.1 on 2026-09-29 21:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0005_event_latitude_event_longitude_pendingevent_latitude_and_more'),
]
operations = [
migrations.AddField(
model_name='event',
name='h3_cell',
field=models.CharField(blank=True, db_index=True, max_length=20),
),
migrations.AddField(
model_name='pendingevent',
name='h3_cell',
field=models.CharField(blank=True, db_index=True, max_length=20),
),
]
@@ -0,0 +1,43 @@
# Generated by Django 6.1.1 on 2026-09-30 07:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0006_event_h3_cell_pendingevent_h3_cell'),
]
operations = [
migrations.AddField(
model_name='event',
name='direction_accuracy_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='direction_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='event',
name='direction_source',
field=models.CharField(blank=True, max_length=32),
),
migrations.AddField(
model_name='pendingevent',
name='direction_accuracy_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='direction_degrees',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='pendingevent',
name='direction_source',
field=models.CharField(blank=True, max_length=32),
),
]
@@ -0,0 +1,23 @@
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0007_event_direction_accuracy_degrees_and_more"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name="sensor",
name="owner",
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="sensors", to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name="sensor",
name="archived_at",
field=models.DateTimeField(blank=True, editable=False, null=True),
),
]
@@ -0,0 +1,24 @@
# Generated by Django 6.1.1 on 2026-10-02 14:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fireworks_detect', '0008_sensor_owner_sensor_archived_at'),
]
operations = [
migrations.CreateModel(
name='BrowserProcessingSettings',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('browser_processing_beta_enabled', models.BooleanField(default=False)),
],
options={
'verbose_name': 'Browser-side media processing (Beta)',
'verbose_name_plural': 'Browser-side media processing (Beta)',
},
),
]
@@ -0,0 +1,16 @@
from django.db import migrations
def create_disabled_settings(apps, schema_editor):
Settings = apps.get_model("fireworks_detect", "BrowserProcessingSettings")
Settings.objects.get_or_create(pk=1, defaults={"browser_processing_beta_enabled": False})
class Migration(migrations.Migration):
dependencies = [
("fireworks_detect", "0009_browserprocessingsettings"),
]
operations = [
migrations.RunPython(create_disabled_settings, migrations.RunPython.noop),
]
@@ -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)),
],
),
]

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