Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Webhooks: include_shared delivers shared recordings' events to recipients (mailr spec W6)

Murtaza Nasirc4c54e9ea6cf
diff --git a/docs/admin-guide/webhooks.md b/docs/admin-guide/webhooks.md
index d3fae9ba..8f860aed 100644
--- a/docs/admin-guide/webhooks.md
+++ b/docs/admin-guide/webhooks.md
@@ -54,6 +54,8 @@ Bursts are merged: a `recording.updated` with the same `recording_id` and `field
as a delivery that has not been attempted yet replaces that delivery's `data`, so a notes
autosave sends one delivery with the latest state.
+**Shared recordings.** A webhook created with `"include_shared": true` (or changed with `PATCH`) also receives the `recording.*` events of completed recordings other users shared with its owner. Their `data` carries `owner_user_id`, and `external_refs` are the webhook owner's own. A reference a user adds to a recording shared with them is private and sends no event to the recording's owner. `recording.deleted` reaches only the owner's webhooks; a client that follows shared recordings learns about deletions from the changes feed (`scope=shared`).
+
Since v0.10.11-alpha, edits made in the web app fire `recording.updated` too. Before, only
`PATCH /api/v1/recordings/{id}` did, so receivers subscribed to this event get more of them.
@@ -281,7 +283,7 @@ or an API token. The OpenAPI schema documents every field.
| GET | `/api/v1/webhooks` | List the caller's webhooks. Returns `event_types` + `max_per_user` for UI rendering. |
| POST | `/api/v1/webhooks` | Create a webhook. Response includes the secret **once**; capture it. |
| GET | `/api/v1/webhooks/{id}` | Read one. Secret is never returned. |
-| PATCH | `/api/v1/webhooks/{id}` | Update name / url / events / enabled / allow_http. |
+| PATCH | `/api/v1/webhooks/{id}` | Update name / url / events / enabled / allow_http / include_shared. |
| DELETE | `/api/v1/webhooks/{id}` | Delete (cascades to deliveries). |
| POST | `/api/v1/webhooks/{id}/rotate-secret` | Generate a fresh HMAC secret. Returned once; the previous one stays valid for the grace period. |
| POST | `/api/v1/webhooks/{id}/test` | Queue a synthetic `webhook.test` delivery. |
diff --git a/src/api/webhooks.py b/src/api/webhooks.py
index a9fd5459..40521172 100644
--- a/src/api/webhooks.py
+++ b/src/api/webhooks.py
@@ -67,7 +67,7 @@ def list_webhooks():
def create_webhook():
"""Create a webhook.
- Body: ``{name, url, events, allow_http=false, enabled=true}``.
+ Body: ``{name, url, events, allow_http=false, enabled=true, include_shared=false}``.
The newly-minted HMAC secret is returned **once** in this response;
after that it is never exposed.
"""
@@ -109,6 +109,7 @@ def create_webhook():
url=url[:500],
allow_http=allow_http,
enabled=enabled,
+ include_shared=bool(data.get('include_shared', False)),
secret=generate_webhook_secret(),
)
try:
@@ -164,6 +165,8 @@ def update_webhook(webhook_id):
wh.event_list = events
except ValueError as e:
return jsonify({'error': str(e)}), 400
+ if 'include_shared' in data:
+ wh.include_shared = bool(data.get('include_shared'))
if 'enabled' in data:
enabled = bool(data.get('enabled'))
wh.enabled = enabled
diff --git a/src/init_db.py b/src/init_db.py
index 8e04c396..197ffe1f 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -724,6 +724,9 @@ def _run_migrations(app, engine):
app.logger.warning("New recordings will work correctly, but existing dates may need manual migration")
with _migration_section(app, failures, "webhook secret rotation grace"):
+ # mailr spec W6: recipients' webhooks for shared recordings (opt-in).
+ if add_column_if_not_exists(engine, 'webhook', 'include_shared', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added include_shared column to webhook table")
# mailr spec W2: the previous secret signs a second V2 value for a while.
if add_column_if_not_exists(engine, 'webhook', 'previous_secret', 'VARCHAR(120)'):
app.logger.info("Added previous_secret column to webhook table")
diff --git a/src/models/webhook.py b/src/models/webhook.py
index 3a966ebd..c670de42 100644
--- a/src/models/webhook.py
+++ b/src/models/webhook.py
@@ -75,6 +75,9 @@ class Webhook(db.Model):
# validates that the destination is not a private IP unless the
# admin has explicitly allowlisted intranet hosts.
allow_http = db.Column(db.Boolean, default=False, nullable=False)
+ # Also deliver recording.* events of recordings shared with the owner
+ # (mailr spec W6), with data.owner_user_id.
+ include_shared = db.Column(db.Boolean, default=False, nullable=False)
# HMAC signing secret. Treat as a credential: redact in API
# responses, surface to the user only on creation, allow rotation
@@ -157,6 +160,7 @@ class Webhook(db.Model):
'name': self.name,
'url': self.url,
'allow_http': bool(self.allow_http),
+ 'include_shared': bool(self.include_shared),
'events': self.event_list,
'enabled': bool(self.enabled),
'auto_paused': bool(self.auto_paused),
diff --git a/src/services/recording_changes.py b/src/services/recording_changes.py
index f3464ab2..a49b6276 100644
--- a/src/services/recording_changes.py
+++ b/src/services/recording_changes.py
@@ -95,7 +95,11 @@ def _child_recording_ids(session):
rid = getattr(obj, 'recording_id', None)
if rid is not None:
fields = ids.setdefault(rid, set())
- if field:
+ if field == 'external_refs':
+ # References are private: only the owner's own tell
+ # the owner's webhooks something changed.
+ fields.add(('external_refs', getattr(obj, 'user_id', None)))
+ elif field:
fields.add(field)
return ids
@@ -134,7 +138,10 @@ def _before_flush(session, flush_context, instances):
rec = session.get(Recording, rid)
if rec is not None and rec not in session.new:
rec.updated_at = now
- changes.setdefault(rid, set()).update(fields)
+ plain = {f for f in fields if isinstance(f, str)}
+ if any(isinstance(f, tuple) and f[1] == rec.user_id for f in fields):
+ plain.add('external_refs')
+ changes.setdefault(rid, set()).update(plain)
for obj in session.deleted:
if isinstance(obj, Recording):
diff --git a/src/services/webhook_dispatch.py b/src/services/webhook_dispatch.py
index 7f632bfa..7c8486e8 100644
--- a/src/services/webhook_dispatch.py
+++ b/src/services/webhook_dispatch.py
@@ -445,36 +445,71 @@ def _merge_pending_update(session, webhook_id, data):
return False
+def _shared_targets(session, event_type, data):
+ """(webhook, recipient id) for recipients of a shared recording whose
+ webhook asks for shared recordings (spec W6)."""
+ rid = data.get('recording_id') if isinstance(data, dict) else None
+ if not event_type.startswith('recording.') or not rid:
+ return []
+ from src import app as app_module
+ if not getattr(app_module, 'ENABLE_INTERNAL_SHARING', False):
+ return []
+ from src.models import InternalShare, Recording
+ recording = session.get(Recording, rid)
+ if recording is None or recording.status != 'COMPLETED':
+ return []
+ recipients = [uid for (uid,) in session.query(InternalShare.shared_with_user_id)
+ .filter(InternalShare.recording_id == rid)]
+ if not recipients:
+ return []
+ hooks = (session.query(Webhook)
+ .filter(Webhook.user_id.in_(recipients), Webhook.enabled.is_(True), Webhook.include_shared.is_(True))
+ .all())
+ return [(wh, wh.user_id) for wh in hooks if event_type in wh.event_list]
+
+
def enqueue_event(session, user_id, event_type, data):
"""Write one pending delivery per subscribed webhook through ``session``
- and commit it. Returns the number of deliveries written or merged."""
+ and commit it: the owner's webhooks, and recipients' webhooks that ask for
+ shared recordings. Returns the number of deliveries written or merged."""
subscriptions = session.query(Webhook).filter_by(user_id=user_id, enabled=True).all()
- matched = [w for w in subscriptions if event_type in w.event_list]
- if not matched:
+ targets = [(w, user_id) for w in subscriptions if event_type in w.event_list]
+ targets += _shared_targets(session, event_type, data)
+ if not targets:
return 0
- data = _with_updated_at(session, event_type, data, user_id)
event_id = str(uuid.uuid4())
first_attempt_at = datetime.utcnow()
created = 0
- for wh in matched:
- if event_type == 'recording.updated' and _merge_pending_update(session, wh.id, data):
+ per_user = {}
+ for wh, viewer in targets:
+ if viewer not in per_user:
+ viewer_data = _with_updated_at(session, event_type, data, viewer)
+ if viewer != user_id:
+ viewer_data = dict(viewer_data, owner_user_id=user_id)
+ per_user[viewer] = viewer_data
+ if _deliver_one(session, wh, viewer, event_type, per_user[viewer], event_id, first_attempt_at):
created += 1
- continue
- envelope = _build_envelope(event_id, event_type, user_id, data)
- session.add(WebhookDelivery(
- webhook_id=wh.id,
- event_id=event_id,
- event_type=event_type,
- payload=serialize_envelope(envelope),
- status='pending',
- next_retry_at=first_attempt_at,
- ))
- created += 1
if created:
session.commit()
return created
+def _deliver_one(session, wh, viewer, event_type, data, event_id, first_attempt_at):
+ """Queue (or merge) one delivery; True when a delivery was written or merged."""
+ if event_type == 'recording.updated' and _merge_pending_update(session, wh.id, data):
+ return True
+ envelope = _build_envelope(event_id, event_type, viewer, data)
+ session.add(WebhookDelivery(
+ webhook_id=wh.id,
+ event_id=event_id,
+ event_type=event_type,
+ payload=serialize_envelope(envelope),
+ status='pending',
+ next_retry_at=first_attempt_at,
+ ))
+ return True
+
+
# ---- Dispatcher: one pass over due deliveries -----------------------------
def _post_delivery(delivery: WebhookDelivery, webhook: Webhook) -> tuple:
diff --git a/tests/test_upgrade_mailr_api.py b/tests/test_upgrade_mailr_api.py
index 69993687..bd81a093 100644
--- a/tests/test_upgrade_mailr_api.py
+++ b/tests/test_upgrade_mailr_api.py
@@ -136,7 +136,8 @@ def test_webhook_rotation_grace_columns(tmp_path, fixture):
_upgrade(db_path)
con = sqlite3.connect(db_path)
- assert {"previous_secret", "previous_secret_expires_at"} <= _columns(con, "webhook")
+ assert {"previous_secret", "previous_secret_expires_at", "include_shared"} <= _columns(con, "webhook")
+ assert con.execute("SELECT include_shared FROM webhook WHERE id = 3").fetchone()[0] in (0, False)
row = con.execute("SELECT secret, previous_secret, previous_secret_expires_at FROM webhook WHERE id = 3").fetchone()
con.close()
assert row == ("s" * 40, None, None)
diff --git a/tests/test_webhooks_include_shared.py b/tests/test_webhooks_include_shared.py
new file mode 100644
index 00000000..5949d008
--- /dev/null
+++ b/tests/test_webhooks_include_shared.py
@@ -0,0 +1,124 @@
+"""Recipients' webhooks for shared recordings (mailr spec W6).
+
+A webhook with include_shared receives the recording.* events of recordings
+shared with its owner, with data.owner_user_id; without it, nothing.
+
+SHARED-DB: users, shares, refs, webhooks, deliveries and the recording are removed afterwards.
+"""
+
+import json
+import os
+import secrets
+import sys
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import (InternalShare, Recording, RecordingExternalRef, User, Webhook, WebhookDelivery)
+from src.services import webhook_dispatch as wd
+
+
+def world():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ owner = User(username=f"ws_{s}", email=f"ws_{s}@local.test", password="x")
+ guest = User(username=f"wsg_{s}", email=f"wsg_{s}@local.test", password="x")
+ db.session.add_all([owner, guest])
+ db.session.commit()
+ rec = Recording(user_id=owner.id, title="Sync", status="COMPLETED", original_filename="s.wav")
+ db.session.add(rec)
+ db.session.commit()
+ db.session.add(InternalShare(recording_id=rec.id, owner_id=owner.id, shared_with_user_id=guest.id))
+ db.session.add_all([RecordingExternalRef(recording_id=rec.id, user_id=owner.id, system="mailr", kind="event", ref="owner-ref"),
+ RecordingExternalRef(recording_id=rec.id, user_id=guest.id, system="mailr", kind="event", ref="guest-ref")])
+ db.session.commit() # before the webhooks exist
+ events = json.dumps(["recording.updated", "recording.summary.completed"])
+ hooks = {
+ "owner": Webhook(user_id=owner.id, name="o", url="https://example.com/o", secret="s" * 40, events=events),
+ "guest_in": Webhook(user_id=guest.id, name="g", url="https://example.com/g", secret="s" * 40, events=events,
+ include_shared=True),
+ "guest_out": Webhook(user_id=guest.id, name="g2", url="https://example.com/g2", secret="s" * 40, events=events),
+ }
+ db.session.add_all(hooks.values())
+ db.session.commit()
+ ids = dict(owner=owner.id, guest=guest.id, rec=rec.id, hooks={k: h.id for k, h in hooks.items()})
+ with patch("src.app.ENABLE_INTERNAL_SHARING", True):
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ WebhookDelivery.query.filter(WebhookDelivery.webhook_id.in_(ids["hooks"].values())).delete(synchronize_session=False)
+ Webhook.query.filter(Webhook.id.in_(ids["hooks"].values())).delete(synchronize_session=False)
+ RecordingExternalRef.query.filter_by(recording_id=ids["rec"]).delete()
+ InternalShare.query.filter_by(recording_id=ids["rec"]).delete()
+ Recording.query.filter_by(id=ids["rec"]).delete()
+ User.query.filter(User.id.in_([ids["owner"], ids["guest"]])).delete(synchronize_session=False)
+ db.session.commit()
+
+
+def _payloads(world, key):
+ with app.app_context():
+ return [json.loads(d.payload) for d in WebhookDelivery.query.filter_by(webhook_id=world["hooks"][key])]
+
+
+def test_a_recipient_webhook_gets_shared_events_when_asked(world):
+ with app.app_context():
+ wd.emit_webhook_event(user_id=world["owner"], event_type="recording.summary.completed",
+ data={"recording_id": world["rec"], "title": "Sync"})
+ owner = _payloads(world, "owner")
+ guest = _payloads(world, "guest_in")
+ assert len(owner) == 1 and "owner_user_id" not in owner[0]["data"]
+ assert [r["ref"] for r in owner[0]["data"]["external_refs"]] == ["owner-ref"]
+ assert len(guest) == 1 and guest[0]["data"]["owner_user_id"] == world["owner"]
+ assert guest[0]["user_id"] == world["guest"]
+ assert [r["ref"] for r in guest[0]["data"]["external_refs"]] == ["guest-ref"] # each sees only their own
+ assert _payloads(world, "guest_out") == []
+
+
+def test_an_edit_reaches_the_recipient_too(world):
+ with app.app_context():
+ r = db.session.get(Recording, world["rec"])
+ r.title = "Renamed"
+ db.session.commit()
+ assert [p["data"]["fields_changed"] for p in _payloads(world, "guest_in")] == [["title"]]
+
+
+def test_no_sharing_no_recipient_events(world):
+ with patch("src.app.ENABLE_INTERNAL_SHARING", False), app.app_context():
+ wd.emit_webhook_event(user_id=world["owner"], event_type="recording.summary.completed",
+ data={"recording_id": world["rec"], "title": "Sync"})
+ assert len(_payloads(world, "owner")) == 1 and _payloads(world, "guest_in") == []
+
+
+def test_include_shared_is_set_through_the_api(world):
+ from flask import g, has_app_context
+ from flask.testing import FlaskClient
+
+ class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(world["guest"])
+ resp = c.patch(f"/api/v1/webhooks/{world['hooks']['guest_out']}", json={"include_shared": True})
+ assert resp.status_code == 200 and resp.get_json()["include_shared"] is True
+
+
+def test_a_recipients_reference_tells_the_owner_nothing(world):
+ with app.app_context():
+ db.session.add(RecordingExternalRef(recording_id=world["rec"], user_id=world["guest"], system="mailr",
+ kind="conversation", ref="guest-2"))
+ db.session.commit()
+ assert _payloads(world, "owner") == [] and _payloads(world, "guest_in") == []
+ with app.app_context():
+ db.session.add(RecordingExternalRef(recording_id=world["rec"], user_id=world["owner"], system="mailr",
+ kind="conversation", ref="owner-2"))
+ db.session.commit()
+ assert [p["data"]["fields_changed"] for p in _payloads(world, "owner")] == [["external_refs"]]
+