Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

New API for showing/renaming user devices.

blueheron7864fdde7f86914
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index a4b8cab..f087385 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -30,7 +30,7 @@ from mwmbl.database import Database
from mwmbl.indexer.batch_cache import BatchCache
from mwmbl.indexer.index_batches import index_documents
from mwmbl.indexer.indexdb import BatchInfo, BatchStatus, IndexDatabase
-from mwmbl.models import ApiKey
+from mwmbl.models import ApiKey, Device
from mwmbl.redis_url_queue import RedisURLQueue
from mwmbl.settings import (
APPLICATION_KEY,
@@ -120,6 +120,12 @@ def _register_routes(r: Router | NinjaAPI, batch_cache: BatchCache, queued_batch
"status": "ok",
}
+ user = _get_user_from_batch(batch)
+ if user is None:
+ return r.create_response(
+ request, "Invalid API key or insufficient scope (crawl scope required).", status=401
+ )
+
user_id_hash = _get_user_id_hash(batch)
urls = [item.url for item in batch.items]
@@ -149,12 +155,16 @@ def _register_routes(r: Router | NinjaAPI, batch_cache: BatchCache, queued_batch
batch_cache.store(hashed_batch, batch_url)
# Record the batch as being local so that we don't retrieve it again when the server restarts
- infos = [BatchInfo(batch_url, user_id_hash, BatchStatus.LOCAL)]
+ infos = [BatchInfo(batch_url, user_id_hash, BatchStatus.LOCAL, device_name=batch.device_name)]
with Database() as db:
index_db = IndexDatabase(db.connection)
index_db.record_batches(infos)
+ # Update or create Device records for this batch
+ if batch.device_name:
+ Device.objects.update_or_create(user=user, hostname=batch.device_name, defaults={})
+
return {
"status": "ok",
"public_user_id": user_id_hash,
@@ -392,6 +402,23 @@ def create_router(batch_cache: BatchCache, queued_batches: RedisURLQueue, versio
return api
+def _get_user_from_batch(batch: Union[Batch, NewBatchRequest, DatasetRequest]):
+ """Validate the API key from batch.user_id and return the user."""
+ raw_key = batch.user_id
+ key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
+ api_key = (
+ ApiKey.objects.filter(
+ key=key_hash,
+ scopes__contains=[ApiKey.Scope.CRAWL],
+ )
+ .select_related("user")
+ .first()
+ )
+ if api_key is None:
+ return None
+ return api_key.user
+
+
def _get_user_id_hash(batch: Union[Batch, NewBatchRequest, DatasetRequest]):
return hashlib.sha3_256(batch.user_id.encode("utf8")).hexdigest()
diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.py
index f330227..858fb93 100644
--- a/mwmbl/crawler/batch.py
+++ b/mwmbl/crawler/batch.py
@@ -124,6 +124,10 @@ class Batch(Schema):
items: list[Item] = Field(
description="List of crawled URLs and their results. Maximum 100 items per batch.",
)
+ device_name: str = Field(
+ description="The crawler's device name (platform.uname().node).",
+ example="my-device",
+ )
class NewBatchRequest(Schema):
diff --git a/mwmbl/indexer/indexdb.py b/mwmbl/indexer/indexdb.py
index b616e04..81f1b10 100644
--- a/mwmbl/indexer/indexdb.py
+++ b/mwmbl/indexer/indexdb.py
@@ -4,6 +4,7 @@ Database interface for batches of crawled data.
from dataclasses import dataclass
from enum import Enum
+from typing import Optional
from psycopg2.extras import execute_values
@@ -20,6 +21,7 @@ class BatchInfo:
url: str
user_id_hash: str
status: BatchStatus
+ device_name: Optional[str] = None
class IndexDatabase:
@@ -31,7 +33,8 @@ class IndexDatabase:
CREATE TABLE IF NOT EXISTS batches (
url VARCHAR PRIMARY KEY,
user_id_hash VARCHAR NOT NULL,
- status INT NOT NULL
+ status INT NOT NULL,
+ device_name VARCHAR
)
"""
@@ -40,11 +43,11 @@ class IndexDatabase:
def record_batches(self, batch_infos: list[BatchInfo]):
sql = """
- INSERT INTO batches (url, user_id_hash, status) values %s
+ INSERT INTO batches (url, user_id_hash, status, device_name) values %s
ON CONFLICT (url) DO NOTHING
"""
- data = [(info.url, info.user_id_hash, info.status.value) for info in batch_infos]
+ data = [(info.url, info.user_id_hash, info.status.value, info.device_name) for info in batch_infos]
with self.connection.cursor() as cursor:
execute_values(cursor, sql, data)
diff --git a/mwmbl/migrations/0038_apikey_last_used_device.py b/mwmbl/migrations/0038_apikey_last_used_device.py
new file mode 100644
index 0000000..2d59631
--- /dev/null
+++ b/mwmbl/migrations/0038_apikey_last_used_device.py
@@ -0,0 +1,39 @@
+# Generated by Django 5.2.13 on 2026-09-17 16:25
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0037_repair_domain_submission_statuses"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="apikey",
+ name="last_used",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.CreateModel(
+ name="Device",
+ fields=[
+ ("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
+ ("hostname", models.CharField(max_length=255)),
+ ("friendly_name", models.CharField(blank=True, default="", max_length=255)),
+ ("first_seen", models.DateTimeField(auto_now_add=True)),
+ ("last_seen", models.DateTimeField(auto_now=True)),
+ (
+ "user",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE, related_name="devices", to=settings.AUTH_USER_MODEL
+ ),
+ ),
+ ],
+ options={
+ "indexes": [models.Index(fields=["user", "hostname"], name="mwmbl_devic_user_id_6458c1_idx")],
+ "unique_together": {("user", "hostname")},
+ },
+ ),
+ ]
diff --git a/mwmbl/migrations/0039_batches_device_name.py b/mwmbl/migrations/0039_batches_device_name.py
new file mode 100644
index 0000000..b7b9544
--- /dev/null
+++ b/mwmbl/migrations/0039_batches_device_name.py
@@ -0,0 +1,20 @@
+# Generated by Django 5.2.13 on 2026-09-17
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0038_apikey_last_used_device"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ """
+ ALTER TABLE batches ADD COLUMN device_name VARCHAR;
+ """,
+ """
+ ALTER TABLE batches DROP COLUMN device_name;
+ """,
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index e3fa928..eb8ffeb 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -272,6 +272,22 @@ class MarketingConsent(models.Model):
]
+class Device(models.Model):
+ """A crawler device linked to a user."""
+
+ user = models.ForeignKey(MwmblUser, on_delete=models.CASCADE, related_name="devices")
+ hostname = models.CharField(max_length=255) # device name from crawler (platform.uname().node)
+ friendly_name = models.CharField(max_length=255, blank=True, default="") # user-defined name
+ first_seen = models.DateTimeField(auto_now_add=True)
+ last_seen = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["user", "hostname"]),
+ ]
+ unique_together = ("user", "hostname")
+
+
class SearchResultVote(models.Model):
VOTE_TYPES = {
"upvote": "User upvoted this result",
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 0e36126..9d46ab2 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -23,6 +23,7 @@ from mwmbl.exceptions import InvalidRequest
from mwmbl.models import (
AgreementType,
ApiKey,
+ Device,
DomainEvidence,
DomainSubmission,
MarketingConsent,
@@ -52,6 +53,7 @@ from mwmbl.platform.schemas import (
CheckoutResponse,
ConfirmEmail,
CreateApiKeyRequest,
+ DeviceResponse,
DomainSubmissionSchema,
ForgotPasswordRequest,
MarketingConsentListResponse,
@@ -65,6 +67,7 @@ from mwmbl.platform.schemas import (
ResetPasswordRequest,
SubmissionDetailSchema,
SubscriptionResponse,
+ UpdateDeviceRequest,
UpdateDomainSubmission,
UpdateSpendLimitRequest,
UserProfileResponse,
@@ -1106,6 +1109,58 @@ def delete_api_key(request, key_id: int):
return {"status": "ok", "message": "API key revoked."}
+# ---------------------------------------------------------------------------
+# Devices
+# ---------------------------------------------------------------------------
+
+
+ "/devices/",
+ auth=JWTAuth(),
+ response=list[DeviceResponse],
+ summary="List devices",
+ description=("List all devices belonging to the authenticated user. Requires a verified account."),
+ tags=["Devices"],
+)
+def list_devices(request) -> list[DeviceResponse]:
+ check_email_verified(request)
+ devices = Device.objects.filter(user=request.user).order_by("-first_seen")
+ return [
+ DeviceResponse(
+ id=d.id,
+ hostname=d.hostname,
+ friendly_name=d.friendly_name or None,
+ first_seen=d.first_seen,
+ last_seen=d.last_seen,
+ )
+ for d in devices
+ ]
+
+
+ "/devices/{device_id}",
+ auth=JWTAuth(),
+ response=DeviceResponse,
+ summary="Update device friendly name",
+ description=("Update the friendly name of a device owned by the authenticated user. Requires a verified account."),
+ tags=["Devices"],
+)
+def update_device(request, device_id: int, body: UpdateDeviceRequest):
+ check_email_verified(request)
+ device = Device.objects.filter(id=device_id, user=request.user).first()
+ if device is None:
+ raise InvalidRequest("Device not found.", status=404)
+ device.friendly_name = body.friendly_name
+ device.save(update_fields=["friendly_name"])
+ return DeviceResponse(
+ id=device.id,
+ hostname=device.hostname,
+ friendly_name=device.friendly_name or None,
+ first_seen=device.first_seen,
+ last_seen=device.last_seen,
+ )
+
+
# ---------------------------------------------------------------------------
# User profile
# ---------------------------------------------------------------------------
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index 9293f79..104f6a6 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -138,6 +138,22 @@ class MarketingConsentListResponse(Schema):
)
+class DeviceResponse(Schema):
+ id: int
+ hostname: str
+ friendly_name: Optional[str] = None
+ first_seen: datetime
+ last_seen: datetime
+
+
+class UpdateDeviceRequest(Schema):
+ friendly_name: str = Field(
+ max_length=255,
+ description="The new friendly name for the device.",
+ example="My Laptop",
+ )
+
+
class Registration(Schema):
email: str = Field(description="Email address for the new account. Must be unique.")
password: str = Field(description="Password for the new account.")