Skip to content

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

Python

Add PWA Web Share Target receiver with frontend feedback handler (#285)

Murtaza Nasirfd811ae7b54a
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 03a7d649..f6d931a0 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2056,6 +2056,103 @@ def toggle_highlight(recording_id):
+@recordings_bp.route('/share-target', methods=['POST', 'GET'])
+@login_required
+def share_target():
+ """PWA Web Share Target receiver (issue #285).
+
+ Android Chrome / iOS Safari 16.4+ POST a multipart/form-data body to
+ this endpoint when the user picks Speakr from the native share sheet.
+ The file arrives under the field name declared in the manifest
+ (``shared_audio``). Any text/title/url params the share sheet sent
+ become the recording's notes.
+
+ CSRF is exempted at app startup (the share sheet has no way to
+ round-trip a CSRF token). Authentication still happens via the
+ session cookie carried by the browser; unauthenticated visitors hit
+ @login_required and are bounced to the login page.
+
+ Implementation: save the file to ``UPLOAD_FOLDER``, create a Recording
+ row applying the same user / folder / tag defaults as ``upload_file``
+ where they are unambiguous (no tags / folder context in a share),
+ then enqueue a transcription job through the existing job queue.
+ Redirect the browser to the SPA so the user lands on the recordings
+ list with the new row visible.
+ """
+ if request.method == 'GET':
+ # Some platforms pre-flight with GET. Just land the user on the SPA.
+ return redirect(url_for('recordings.index'))
+
+ shared = request.files.get('shared_audio') or request.files.get('file')
+ if not shared or not getattr(shared, 'filename', ''):
+ return redirect(url_for('recordings.index') + '?share_target_error=missing_file')
+
+ original_filename = shared.filename
+ safe_filename = secure_filename(original_filename) or 'shared-recording.webm'
+ timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
+ filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], f"{timestamp}_{safe_filename}")
+
+ try:
+ shared.save(filepath)
+ except RequestEntityTooLarge:
+ return redirect(url_for('recordings.index') + '?share_target_error=too_large')
+ except Exception as save_err:
+ current_app.logger.warning(f"share-target file save failed: {save_err}")
+ return redirect(url_for('recordings.index') + '?share_target_error=save_failed')
+
+ file_size = os.path.getsize(filepath)
+
+ # Build the recording row. Tags and folder cannot be inferred from a
+ # share sheet, so we leave them empty; the user can adjust from the
+ # recording detail view. Title comes from the share sheet's title field
+ # if present, else from the filename stem.
+ share_title = (request.form.get('title') or os.path.splitext(safe_filename)[0]).strip() or 'Shared recording'
+
+ notes_parts = []
+ for key in ('title', 'text', 'url'):
+ val = (request.form.get(key) or '').strip()
+ if val:
+ notes_parts.append(val)
+ share_notes = '\n\n'.join(notes_parts) if notes_parts else None
+
+ recording = Recording(
+ audio_path=filepath,
+ original_filename=original_filename,
+ title=share_title,
+ status='PENDING',
+ user_id=current_user.id,
+ notes=share_notes,
+ file_size=file_size,
+ )
+ db.session.add(recording)
+ db.session.commit()
+
+ # Enqueue transcription with user's defaults. Mirrors the precedence
+ # chain in upload_file for the fields that apply when no tag/folder
+ # context is available.
+ job_params = {
+ 'language': current_user.transcription_language,
+ 'hotwords': current_user.transcription_hotwords,
+ 'initial_prompt': current_user.transcription_initial_prompt,
+ }
+ try:
+ job_queue.enqueue(
+ user_id=current_user.id,
+ recording_id=recording.id,
+ job_type='transcribe',
+ params=job_params,
+ is_new_upload=True,
+ )
+ except Exception as queue_err:
+ current_app.logger.warning(f"share-target enqueue failed for recording {recording.id}: {queue_err}")
+ recording.status = 'FAILED'
+ recording.transcription = f"Processing failed: {queue_err}"
+ db.session.commit()
+ return redirect(url_for('recordings.index') + '?share_target_error=queue_failed')
+
+ return redirect(url_for('recordings.index') + f'?share_target=ok&recording_id={recording.id}')
+
+
@recordings_bp.route('/upload', methods=['POST'])
@login_required
def upload_file():
diff --git a/src/app.py b/src/app.py
index 1fe902f5..7ff0df65 100644
--- a/src/app.py
+++ b/src/app.py
@@ -670,6 +670,13 @@ app.register_blueprint(push_bp)
app.register_blueprint(api_v1_bp)
csrf.exempt(api_v1_bp) # API v1 uses token auth, not CSRF
+# PWA Web Share Target (issue #285): the native share sheet cannot round-trip
+# a CSRF token, so the share-target endpoint is exempted. Authentication still
+# happens via the session cookie carried by the browser; @login_required
+# bounces unauthenticated visitors to /login.
+from src.api.recordings import share_target as _share_target_view
+csrf.exempt(_share_target_view)
+
# File monitor and scheduler initialization functions below
# Startup functions (extracted to src/config/startup.py)
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 5e1344be..f2b62f89 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -2386,6 +2386,36 @@ document.addEventListener('DOMContentLoaded', async () => {
uiComposable.initializeColorScheme();
uiComposable.initializeSidebar();
+ // PWA Web Share Target feedback (issue #285). When the user
+ // shares audio from the native share sheet, the backend
+ // redirects to /?share_target=ok or /?share_target_error=...;
+ // surface a toast and strip the flag from the URL so refresh
+ // does not re-show it.
+ try {
+ const params = new URLSearchParams(window.location.search);
+ const shareOk = params.get('share_target');
+ const shareErr = params.get('share_target_error');
+ if (shareOk === 'ok') {
+ showToast(t('toasts.shareTargetReceived') || 'Shared audio received and queued for transcription', 'fa-share');
+ } else if (shareErr) {
+ const errMsgKey = `errors.shareTarget_${shareErr}`;
+ const errMsg = (t(errMsgKey) !== errMsgKey ? t(errMsgKey) : null)
+ || t('errors.shareTargetGeneric')
+ || `Share failed: ${shareErr}`;
+ setGlobalError(errMsg);
+ }
+ if (shareOk || shareErr) {
+ params.delete('share_target');
+ params.delete('share_target_error');
+ params.delete('recording_id');
+ const cleanQuery = params.toString();
+ const newUrl = window.location.pathname + (cleanQuery ? `?${cleanQuery}` : '') + window.location.hash;
+ window.history.replaceState({}, '', newUrl);
+ }
+ } catch (e) {
+ console.warn('[App] share-target query handling failed:', e);
+ }
+
// Check for recoverable recording from IndexedDB
try {
const recoverable = await audioComposable.checkForRecoverableRecording();
diff --git a/static/manifest.json b/static/manifest.json
index 2b527d77..1a1eddc8 100644
--- a/static/manifest.json
+++ b/static/manifest.json
@@ -87,7 +87,7 @@
}
],
"share_target": {
- "action": "/#upload",
+ "action": "/share-target",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
@@ -97,7 +97,7 @@
"files": [
{
"name": "shared_audio",
- "accept": ["audio/*"]
+ "accept": ["audio/*", "video/mp4", "video/quicktime", "video/x-matroska", "video/webm"]
}
]
}
diff --git a/tests/test_share_target.py b/tests/test_share_target.py
new file mode 100644
index 00000000..cd5bd814
--- /dev/null
+++ b/tests/test_share_target.py
@@ -0,0 +1,159 @@
+"""Regression tests for the PWA Web Share Target endpoint (issue #285).
+
+The endpoint is what Android Chrome / iOS Safari 16.4+ POST to when the
+user picks Speakr from the native share sheet. We verify:
+
+- the manifest declares /share-target as the action
+- a missing file redirects with share_target_error=missing_file
+- a valid POST creates a Recording row owned by the current user
+- the endpoint is CSRF-exempt (the share sheet has no CSRF token)
+- the endpoint is login-required (unauthenticated visits bounce to login)
+"""
+
+import io
+import json
+import os
+import sys
+import uuid
+from pathlib import Path
+from unittest.mock import patch
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import User, Recording
+
+
+def _setup_user(prefix):
+ suffix = uuid.uuid4().hex[:8]
+ user = User(
+ username=f"{prefix}_{suffix}",
+ email=f"{prefix}_{suffix}@local.test",
+ password="x",
+ )
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def _login(client, user):
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+
+
+def test_manifest_share_target_action():
+ """The PWA manifest must point share_target.action at /share-target."""
+ manifest_path = Path(__file__).parent.parent / "static" / "manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ assert manifest["share_target"]["action"] == "/share-target"
+ assert manifest["share_target"]["method"] == "POST"
+ assert manifest["share_target"]["enctype"] == "multipart/form-data"
+ files = manifest["share_target"]["params"]["files"]
+ assert any(f["name"] == "shared_audio" for f in files)
+
+
+def test_share_target_missing_file_redirects_with_error_flag():
+ with app.app_context():
+ user = _setup_user("share_missing")
+ client = app.test_client()
+ _login(client, user)
+ resp = client.post("/share-target", data={}, follow_redirects=False)
+ assert resp.status_code == 302
+ assert "share_target_error=missing_file" in resp.headers.get("Location", "")
+ db.session.delete(user)
+ db.session.commit()
+
+
+def test_share_target_creates_recording_and_enqueues_job():
+ with app.app_context():
+ user = _setup_user("share_ok")
+ client = app.test_client()
+ _login(client, user)
+
+ captured = {}
+
+ def fake_enqueue(*args, **kwargs):
+ captured.update(kwargs)
+ return 999
+
+ with patch("src.services.job_queue.job_queue.enqueue", side_effect=fake_enqueue), \
+ patch("src.api.recordings.os.path.getsize", return_value=12345):
+ resp = client.post(
+ "/share-target",
+ data={
+ "title": "Shared from Recorder app",
+ "text": "Meeting notes",
+ "shared_audio": (io.BytesIO(b"fake-audio-bytes"), "shared.webm"),
+ },
+ content_type="multipart/form-data",
+ follow_redirects=False,
+ )
+ assert resp.status_code == 302, resp.data
+ location = resp.headers.get("Location", "")
+ assert "share_target=ok" in location, location
+ assert "recording_id=" in location, location
+
+ recordings = Recording.query.filter_by(user_id=user.id).all()
+ assert len(recordings) == 1
+ rec = recordings[0]
+ assert rec.title == "Shared from Recorder app"
+ assert rec.notes and "Meeting notes" in rec.notes
+ assert rec.status == "PENDING"
+ assert captured.get("user_id") == user.id
+ assert captured.get("recording_id") == rec.id
+ assert captured.get("job_type") == "transcribe", (
+ f"share-target must use the same job_type as upload_file (transcribe), "
+ f"got {captured.get('job_type')!r}"
+ )
+ assert captured.get("is_new_upload") is True, "share-target uploads should be flagged as new uploads"
+ # Clean up the saved file artefact if present
+ if rec.audio_path and os.path.exists(rec.audio_path):
+ try:
+ os.remove(rec.audio_path)
+ except OSError:
+ pass
+ db.session.delete(rec)
+ db.session.delete(user)
+ db.session.commit()
+
+
+def test_share_target_requires_login():
+ """Unauthenticated POSTs hit @login_required and redirect to /login."""
+ with app.app_context():
+ client = app.test_client()
+ resp = client.post(
+ "/share-target",
+ data={"shared_audio": (io.BytesIO(b"x"), "x.webm")},
+ content_type="multipart/form-data",
+ follow_redirects=False,
+ )
+ assert resp.status_code == 302
+ loc = resp.headers.get("Location", "")
+ assert "/login" in loc or "next=" in loc, loc
+
+
+def test_share_target_is_csrf_exempt():
+ """The share sheet has no CSRF token; the route must be exempted."""
+ from src.app import csrf
+ # Flask-WTF stores exempt names on the protect instance
+ exempt_set = getattr(csrf, "_exempt_views", set())
+ # Match by qualified function name
+ assert any("share_target" in name for name in exempt_set), \
+ f"share_target view should be CSRF-exempt; current exempts: {exempt_set}"
+
+
+def teardown_module(module):
+ with app.app_context():
+ for u in User.query.filter(User.username.like("share_%")).all():
+ db.session.delete(u)
+ db.session.commit()
+
+
+if __name__ == "__main__":
+ test_manifest_share_target_action()
+ test_share_target_missing_file_redirects_with_error_flag()
+ test_share_target_creates_recording_and_enqueues_job()
+ test_share_target_requires_login()
+ test_share_target_is_csrf_exempt()
+ print("All share-target tests passed.")