first commit

This commit is contained in:
Joren de Graaf
2026-10-04 17:09:22 +02:00
commit 1d4407462a
140 changed files with 7893 additions and 0 deletions
View File
+6
View File
@@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Sensor
@admin.register(Sensor)
class SensorAdmin(admin.ModelAdmin):
list_display=['name','owner','is_active','last_heartbeat','last_submission']
readonly_fields=['token_prefix','token_hash','last_heartbeat','last_submission','created_at']
+32
View File
@@ -0,0 +1,32 @@
# Generated by Django 6.1.1 on 2026-10-04 14:20
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Sensor',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('is_active', models.BooleanField(default=True)),
('archived_at', models.DateTimeField(blank=True, null=True)),
('token_prefix', models.CharField(blank=True, db_index=True, editable=False, max_length=15)),
('token_hash', models.CharField(blank=True, editable=False, max_length=256)),
('last_heartbeat', models.DateTimeField(blank=True, null=True)),
('last_submission', models.DateTimeField(blank=True, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sensors', to=settings.AUTH_USER_MODEL)),
],
),
]
View File
+26
View File
@@ -0,0 +1,26 @@
import secrets
from django.conf import settings
from django.contrib.auth.hashers import make_password,check_password
from django.db import models
from django.utils import timezone
class Sensor(models.Model):
name=models.CharField(max_length=100)
owner=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='sensors')
is_active=models.BooleanField(default=True)
archived_at=models.DateTimeField(null=True,blank=True)
token_prefix=models.CharField(max_length=15,blank=True,editable=False,db_index=True)
token_hash=models.CharField(max_length=256,blank=True,editable=False)
last_heartbeat=models.DateTimeField(null=True,blank=True)
last_submission=models.DateTimeField(null=True,blank=True)
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self): return self.name
def issue_token(self):
token='bc_'+secrets.token_urlsafe(32);self.token_prefix=token[:15];self.token_hash=make_password(token);self.save(update_fields=['token_prefix','token_hash']);return token
def token_matches(self,token): return self.is_active and not self.archived_at and bool(self.token_hash) and check_password(token,self.token_hash)
@property
def heartbeat_status(self):
if not self.last_heartbeat: return 'never seen'
age=(timezone.now()-self.last_heartbeat).total_seconds()
return 'online' if age<=300 else 'delayed' if age<=900 else 'offline'
def archive(self):
self.is_active=False;self.archived_at=timezone.now();self.token_hash='';self.token_prefix='';self.save()
+8
View File
@@ -0,0 +1,8 @@
from devices.models import Sensor
def authenticate_sensor(request):
header=request.headers.get('Authorization','')
token=header.removeprefix('Bearer ').strip() if header.startswith('Bearer ') else request.headers.get('X-Sensor-Token','')
if not token: return None
for sensor in Sensor.objects.filter(token_prefix=token[:15],is_active=True,archived_at__isnull=True):
if sensor.token_matches(token): return sensor
return None
+1
View File
@@ -0,0 +1 @@
{% extends 'base.html' %}{% block content %}<section class="page-head"><a href="/settings/sensors/">← Sensors</a><h1>{{ sensor.name }}</h1><p>{{ sensor.heartbeat_status }}</p></section>{% if token %}<div class="card" role="status"><h2>Copy your new token now</h2><code>{{ token }}</code></div>{% endif %}<div class="card"><p>Last heartbeat: {{ sensor.last_heartbeat|default:'Never' }}</p><p>Last submission: {{ sensor.last_submission|default:'Never' }}</p><form method="post" hx-post="{% url 'sensor_detail' sensor.pk %}" hx-target="#content" hx-select="#content" hx-swap="outerHTML">{% csrf_token %}<input name="name" value="{{ sensor.name }}"><button name="action" value="rename">Rename</button><button name="action" value="toggle">{% if sensor.is_active %}Disable{% else %}Enable{% endif %}</button><button name="action" value="rotate">Rotate token</button><button name="action" value="archive">Archive</button></form></div>{% endblock %}
+1
View File
@@ -0,0 +1 @@
{% extends 'base.html' %}{% block content %}<section class="page-head"><h1>Sensors</h1><p>Manage your recording devices.</p></section><nav class="subnav"><a href="/settings/">General</a><a href="/settings/notifications/">Notifications</a><a href="/settings/sensors/">Sensors</a></nav>{% if token %}<div class="card" role="status"><h2>Copy your token now</h2><code>{{ token }}</code><p>It will not be shown again.</p></div>{% endif %}<form class="card form" method="post" hx-post="/settings/sensors/" hx-target="#content" hx-select="#content" hx-swap="outerHTML">{% csrf_token %}<h2>Add sensor</h2><label>Name <input name="name" required maxlength="100"></label><button class="button">Create sensor</button></form><div id="sensor-list" class="activity-list" hx-get="/settings/sensors/" hx-trigger="every 60s" hx-target="#sensor-list" hx-select="#sensor-list" hx-swap="outerHTML">{% for sensor in sensors %}<a class="card activity-row" href="{% url 'sensor_detail' sensor.pk %}"><strong>{{ sensor.name }}</strong><span>{{ sensor.heartbeat_status }}</span></a>{% empty %}<p>No sensors yet.</p>{% endfor %}</div>{% endblock %}
View File
+22
View File
@@ -0,0 +1,22 @@
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from devices.models import Sensor
from events.models import Event
class SensorApiTests(TestCase):
def setUp(self):
self.user=get_user_model().objects.create_user('owner')
self.sensor=Sensor.objects.create(name='Garden',owner=self.user)
self.token=self.sensor.issue_token()
def test_invalid_and_archived_tokens_rejected(self):
self.assertEqual(self.client.post('/api/v1/sensors/heartbeat/',HTTP_AUTHORIZATION='Bearer wrong').status_code,401)
self.sensor.archive()
self.assertEqual(self.client.post('/api/v1/sensors/heartbeat/',HTTP_AUTHORIZATION=f'Bearer {self.token}').status_code,401)
@patch('devices.views.classify',return_value={'predictions':[]})
def test_submission_creates_pending_sensor_event(self,classify):
audio=SimpleUploadedFile('clip.wav',b'RIFF',content_type='audio/wav')
response=self.client.post('/api/v1/sensors/events/',{'audio_file':audio},HTTP_AUTHORIZATION=f'Bearer {self.token}')
self.assertEqual(response.status_code,201)
self.assertEqual(Event.objects.get().source,'sensor')
self.assertEqual(Event.objects.get().status,'pending')
+15
View File
@@ -0,0 +1,15 @@
from django.contrib.auth import get_user_model
from django.test import TestCase
from devices.models import Sensor
from devices.services.authentication import authenticate_sensor
from django.test import RequestFactory
class SensorTokenTests(TestCase):
def test_token_hashed_and_archive_revokes(self):
user=get_user_model().objects.create_user('owner')
sensor=Sensor.objects.create(name='Garden',owner=user)
token=sensor.issue_token()
self.assertNotIn(token,sensor.token_hash)
request=RequestFactory().post('/',HTTP_AUTHORIZATION=f'Bearer {token}')
self.assertEqual(authenticate_sensor(request),sensor)
sensor.archive()
self.assertIsNone(authenticate_sensor(request))
+50
View File
@@ -0,0 +1,50 @@
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from .models import Sensor
from .services.authentication import authenticate_sensor
from analysis.services.classifier import classify,ClassifierError
from events.models import Event
from notifications.services import notify_event
@login_required
def sensors(request):
token=None
if request.method=='POST':
name=request.POST.get('name','').strip()[:100]
if name:
sensor=Sensor.objects.create(name=name,owner=request.user);token=sensor.issue_token()
return render(request,'devices/sensors.html',{'sensors':Sensor.objects.filter(owner=request.user,archived_at__isnull=True),'token':token})
@login_required
def sensor_detail(request,pk):
sensor=get_object_or_404(Sensor,pk=pk,owner=request.user);token=None
if request.method=='POST':
action=request.POST.get('action')
if action=='rotate': token=sensor.issue_token()
elif action=='archive': sensor.archive();return redirect('sensors')
elif action=='toggle': sensor.is_active=not sensor.is_active;sensor.save(update_fields=['is_active'])
elif action=='rename': sensor.name=request.POST.get('name','').strip()[:100] or sensor.name;sensor.save(update_fields=['name'])
return render(request,'devices/detail.html',{'sensor':sensor,'token':token})
@csrf_exempt
def heartbeat(request):
if request.method!='POST': return JsonResponse({'error':'POST required'},status=405)
sensor=authenticate_sensor(request)
if not sensor: return JsonResponse({'error':'Unauthorized'},status=401)
sensor.last_heartbeat=timezone.now();sensor.save(update_fields=['last_heartbeat'])
return JsonResponse({'status':'ok'})
@csrf_exempt
def submit_event(request):
if request.method!='POST': return JsonResponse({'error':'POST required'},status=405)
sensor=authenticate_sensor(request)
if not sensor: return JsonResponse({'error':'Unauthorized'},status=401)
audio=request.FILES.get('audio_file') or request.FILES.get('file')
if not audio: return JsonResponse({'error':'Audio required'},status=400)
try: result=classify(audio)
except ClassifierError as exc: return JsonResponse({'error':str(exc)},status=502)
with transaction.atomic():
event=Event.objects.create(source=Event.Source.SENSOR,sensor=sensor,audio_file=audio,original_filename=audio.name,classifier_response=result,occurred_at=timezone.now())
sensor.last_heartbeat=timezone.now();sensor.last_submission=sensor.last_heartbeat;sensor.save(update_fields=['last_heartbeat','last_submission'])
transaction.on_commit(lambda:notify_event(event))
return JsonResponse({'id':event.pk,'status':event.status},status=201)