Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add ASR Voice Recorder webhook integration
cybersadere45f7c43c894
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex 7393ed05..650a97fc 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -229,6 +229,63 @@ curl -X POST \https://speakr.example.com/api/v1/recordings/upload```+### ASR Voice Recorder Upload++```http+POST /api/v1/integrations/asr-voice-recorder/upload+```++This adapter accepts the multipart webhook format sent by the Android **ASR Voice Recorder** app and queues the completed recording through Speakr's normal upload and transcription pipeline. Unlike other API endpoints, authentication comes from the required multipart `secret` field because the recorder cannot set a custom Authorization header.++**Form Fields:**++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `file` | file | for uploads | Completed audio recording; omitted by ASR's connection test |+| `secret` | string | yes | A personal Speakr API token |+| `file_name` | string | no | Original filename override; sanitized by Speakr |+| `date` | integer | no | Recording time as Unix epoch seconds or milliseconds |+| `duration` | number | no | Accepted for compatibility but ignored; Speakr measures duration from the media |+| `note` | string | no | Stored as the recording's notes |++A session cookie or normal API Authorization header does not replace `secret` on this endpoint. Create a dedicated, expiring token for the recorder because Speakr API tokens currently provide full access to their owner's account. The endpoint limits each source IP by both request count and total declared upload size; HTTP 429 means ASR should retry later. Multi-worker deployments using Flask-Limiter's in-memory storage should also enforce an aggregate upload rate at the reverse proxy.++When saving the webhook destination, ASR first sends an authenticated connection test without a file or recording metadata. Speakr returns HTTP 200 with `{"status":"ok","connection_test":true}` and does not create a recording. Completed deliveries still require the `file` field.++**Response:**++```json+// 200 OK+{+ "id": 123,+ "title": "Recording - interview.m4a",+ "status": "PENDING",+ "original_filename": "interview.m4a",+ "notes": "Interview recorded with an external microphone",+ "idempotent_replay": false+}+```++If ASR retries the same completed file with matching filename, note, and recording date for the same user, Speakr returns the existing recording with `idempotent_replay: true` instead of queueing another transcription. Identical audio submitted with different metadata remains a distinct recording. Simultaneous first deliveries are not a strict exactly-once guarantee.++**ASR Voice Recorder configuration:**++- Webhook URL: `https://speakr.example.com/api/v1/integrations/asr-voice-recorder/upload`+- Secret: the dedicated Speakr API token+- Method/body: ASR supplies the multipart POST automatically+- Expected success status: HTTP 200++A manual protocol check can be made with placeholder credentials:++```bash+curl -X POST \+ -F "secret=YOUR_DEDICATED_TOKEN" \+ -F "[email protected]" \+ -F "file_name=recording.m4a" \+ -F "note=Mobile recorder upload" \+ https://speakr.example.com/api/v1/integrations/asr-voice-recorder/upload+```+### List Recordings```httpdiff --git a/docs/user-guide/api-tokens.md b/docs/user-guide/api-tokens.mdindex bc983083..b42029c5 100644--- a/docs/user-guide/api-tokens.md+++ b/docs/user-guide/api-tokens.md@@ -66,6 +66,29 @@ For simple integrations (less secure - token visible in logs):curl "https://your-speakr-instance.com/api/v1/recordings?token=YOUR_TOKEN_HERE"```+## ASR Voice Recorder Integration++The Android **ASR Voice Recorder** app can automatically send each completed recording to Speakr through its webhook cloud service.++1. Create a token named something descriptive, such as **ASR Voice Recorder**.+2. Give it an expiration appropriate for the phone's expected use rather than choosing no expiration.+3. In ASR Voice Recorder, add a webhook destination with this URL:++ ```text+ https://speakr.example.com/api/v1/integrations/asr-voice-recorder/upload+ ```++4. Paste the Speakr token into ASR's **Secret** field.+5. Save the destination. Speakr accepts ASR's authenticated connection test without creating a recording.+6. Record a short test and confirm the recording appears in the token owner's Speakr library.++The integration stores ASR's note as Speakr notes, preserves the supplied recording date, measures the media duration itself, and returns HTTP 200 so ASR marks the connection test or completed delivery successful. Safe retries of the same completed file reuse the existing Speakr recording.++!!! warning "Dedicated token strongly recommended"+ ASR stores the token on the Android device, and Speakr API tokens currently provide full access to the owner's account. Use a separate expiring token for this integration. Revoke it immediately if the phone is lost, the recorder is uninstalled, or the integration is no longer used. Never place the real token in screenshots, support posts, configuration examples, or source control.++This endpoint is intentionally different from normal API authentication: ASR sends the token in its multipart `secret` field because it cannot add a Bearer or API-token header. Session cookies and normal API headers do not substitute for the Secret field.+## Available API EndpointsSpeakr provides a comprehensive REST API with endpoints for recordings, tags, speakers, processing operations, and more.@@ -84,6 +107,7 @@ Speakr provides a comprehensive REST API with endpoints for recordings, tags, sp| `/api/v1/recordings/<id>/summary` | GET | Get AI-generated summary || `/api/v1/recordings/<id>/transcribe` | POST | Queue transcription || `/api/v1/recordings/<id>/summarize` | POST | Queue summarization |+| `/api/v1/integrations/asr-voice-recorder/upload` | POST | Receive a completed ASR Voice Recorder file || `/api/v1/tags` | GET | List your tags || `/api/v1/speakers` | GET | List your speakers || `/api/v1/users/me` | GET | Get the current user's profile and group memberships |diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex eae76cff..465b9032 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -16,7 +16,9 @@ All endpoints require token authentication via:import osimport reimport json-from datetime import datetime, date, timedelta+import math+from datetime import datetime, date, timedelta, timezone+from functools import wrapsfrom src.utils.dates import to_utc_naivefrom typing import Optional@@ -24,6 +26,8 @@ from typing import Optionalfrom flask import Blueprint, jsonify, request, current_app, send_file, redirectfrom flask_login import login_required, current_userfrom sqlalchemy import func, extract, or_, and_+from werkzeug.exceptions import RequestEntityTooLarge+from werkzeug.utils import secure_filenamefrom src.database import dbfrom src.models import Recording, User, Tag, RecordingTag, Speaker, Event@@ -33,8 +37,12 @@ from src.models.transcription_usage import TranscriptionUsagefrom src.services.token_tracking import TokenTrackerfrom src.services.transcription_tracking import transcription_trackerfrom src.file_exporter import format_transcription_with_template-from src.api.recordings import upload_file as _upload_file_ui+from src.api.recordings import (+ ingest_uploaded_recording,+ upload_file as _upload_file_ui,+)from src.services.storage import get_storage_service+from src.utils.token_auth import load_user_from_token_value# Create blueprint with /api/v1 prefixapi_v1_bp = Blueprint('api_v1', __name__, url_prefix='/api/v1')@@ -67,6 +75,25 @@ def init_api_v1_helpers(**kwargs):chunking_service = kwargs.get('chunking_service')+def rate_limit(limit_string, **limit_options):+ """Apply an endpoint limit after the app injects Flask-Limiter."""+ def decorator(f):+ state = {'limited': None}++ @wraps(f)+ def wrapper(*args, **kwargs):+ if limiter is not None and getattr(limiter, 'enabled', True):+ if state['limited'] is None:+ state['limited'] = limiter.limit(limit_string, **limit_options)(f)+ return state['limited'](*args, **kwargs)+ return f(*args, **kwargs)++ wrapper._rate_limit = limit_string+ wrapper._rate_limit_options = limit_options+ return wrapper+ return decorator++def format_bytes(bytes_value: int) -> str:"""Format bytes to human-readable string."""if bytes_value is None:@@ -86,7 +113,7 @@ OPENAPI_SPEC = {"openapi": "3.0.3","info": {"title": "Speakr API",- "description": "REST API for Speakr - Audio transcription and note-taking application.\n\n## Authentication\nAll endpoints require token authentication via one of:\n- `Authorization: Bearer <token>`\n- `X-API-Token: <token>`\n- `API-Token: <token>`\n- `?token=<token>` query parameter\n\nGenerate tokens in Settings > API Tokens.",+ "description": "REST API for Speakr - Audio transcription and note-taking application.\n\n## Authentication\nMost endpoints require token authentication via one of:\n- `Authorization: Bearer <token>`\n- `X-API-Token: <token>`\n- `API-Token: <token>`\n- `?token=<token>` query parameter\n\nThe ASR Voice Recorder integration is the one exception: its required multipart `secret` field contains the personal Speakr API token because that client cannot set custom authorization headers. Generate tokens in Settings > API Tokens.","version": "1.0.0"},"servers": [{"url": "/api/v1", "description": "API v1"}],@@ -342,6 +369,47 @@ OPENAPI_SPEC = {"responses": {"202": {"description": "Upload accepted and queued"}}}},+ "/integrations/asr-voice-recorder/upload": {+ "post": {+ "tags": ["Integrations"],+ "summary": "Receive a completed ASR Voice Recorder recording",+ "description": (+ "Accepts ASR Voice Recorder's multipart webhook format and queues the "+ "recording through Speakr's normal transcription pipeline. It also accepts "+ "ASR's authenticated, fileless connection test without creating a recording. "+ "The required `secret` field must contain a personal Speakr API token. Session "+ "cookies and the API's normal authentication headers do not authenticate this endpoint."+ ),+ "security": [],+ "requestBody": {+ "required": True,+ "content": {+ "multipart/form-data": {+ "schema": {+ "type": "object",+ "required": ["secret"],+ "properties": {+ "file": {"type": "string", "format": "binary", "description": "Required for a completed recording upload; omitted by ASR's connection test"},+ "file_name": {"type": "string", "description": "Optional original filename override"},+ "secret": {"type": "string", "format": "password", "writeOnly": True, "description": "A personal Speakr API token"},+ "date": {"type": "integer", "format": "int64", "description": "Recording time as Unix epoch seconds or milliseconds"},+ "duration": {"type": "number", "description": "Accepted for ASR compatibility but ignored; Speakr measures the media duration"},+ "note": {"type": "string", "description": "Stored as the recording notes"},+ },+ }+ }+ },+ },+ "responses": {+ "200": {"description": "Connection test passed, recording accepted, or an idempotent retry matched an existing recording"},+ "400": {"description": "Upload metadata was provided without a file, or the multipart request is invalid"},+ "401": {"description": "Missing, invalid, expired, or revoked API token"},+ "413": {"description": "Upload exceeds the configured size limit"},+ "429": {"description": "Too many upload attempts"},+ "500": {"description": "Upload or queueing failed"},+ },+ }+ },"/tags": {"get": {"tags": ["Tags"], "summary": "List tags", "responses": {"200": {"description": "List of tags"}}},"post": {"tags": ["Tags"], "summary": "Create tag", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["name"], "properties": {"name": {"type": "string"}, "color": {"type": "string"}, "custom_prompt": {"type": "string"}, "default_language": {"type": "string"}, "default_min_speakers": {"type": "integer"}, "default_max_speakers": {"type": "integer"}}}}}}, "responses": {"201": {"description": "Tag created"}}}@@ -2820,6 +2888,99 @@ def update_auto_summarization():})+def _normalize_asr_filename(file_name, uploaded_file):+ raw_name = (file_name or uploaded_file.filename or '').strip()+ raw_name = re.split(r'[/\\]+', raw_name)[-1]+ normalized = secure_filename(raw_name)+ if not normalized:+ normalized = secure_filename(uploaded_file.filename or '') or 'recording.bin'++ stem, extension = os.path.splitext(normalized)+ extension = extension[:20]+ max_stem = max(1, 180 - len(extension))+ return f'{stem[:max_stem]}{extension}'+++def _asr_meeting_date(raw_date):+ if raw_date is None or str(raw_date).strip() == '':+ return None+ try:+ timestamp = float(raw_date)+ if not math.isfinite(timestamp) or timestamp < 0:+ return None+ # ASR documents only "epoch time". Accept both common units.+ if timestamp > 100_000_000_000:+ timestamp /= 1000+ parsed = datetime.fromtimestamp(timestamp, tz=timezone.utc)+ return parsed.isoformat().replace('+00:00', 'Z')+ except (ValueError, TypeError, OSError, OverflowError):+ return None+++_ASR_RATE_UNITS_PER_MINUTE = 520+_ASR_MIN_REQUEST_COST = 52+++def _asr_upload_rate_cost():+ """Bound both requests and declared MiB with one pre-parse IP bucket."""+ content_length = request.content_length+ if content_length is None:+ return _ASR_RATE_UNITS_PER_MINUTE+ declared_mib = max(1, math.ceil(content_length / (1024 * 1024)))+ return max(_ASR_MIN_REQUEST_COST, declared_mib)+++@api_v1_bp.route('/integrations/asr-voice-recorder/upload', methods=['POST'])+@rate_limit(f'{_ASR_RATE_UNITS_PER_MINUTE} per minute', cost=_asr_upload_rate_cost)+def upload_from_asr_voice_recorder():+ """Accept an ASR Voice Recorder connection test or completed upload."""+ try:+ # ASR sends its token inside the multipart body, so Flask must parse+ # the request before authentication can complete. Apply the regular+ # audio-file ceiling to this route before parsing instead of the+ # larger global video ceiling. The small allowance covers multipart+ # headers and metadata around a file at the configured limit.+ from src.models import SystemSetting+ regular_limit_mb = max(1, int(SystemSetting.get_setting('max_file_size_mb', 250)))+ request.max_content_length = regular_limit_mb * 1024 * 1024 + 64 * 1024++ secret = request.form.get('secret', '')+ owner = load_user_from_token_value(secret)+ if owner is None:+ return jsonify({'error': 'Authentication failed'}), 401++ uploaded_file = request.files.get('file')+ if uploaded_file is None:+ upload_fields = ('file_name', 'date', 'duration', 'note')+ has_upload_metadata = any(request.form.get(field) for field in upload_fields)+ if not has_upload_metadata:+ return jsonify({'status': 'ok', 'connection_test': True}), 200+ return jsonify({'error': 'No file provided'}), 400++ form = {}+ note = request.form.get('note')+ if note is not None:+ form['notes'] = note+ meeting_date = _asr_meeting_date(request.form.get('date'))+ if meeting_date:+ form['meeting_date'] = meeting_date++ return ingest_uploaded_recording(+ owner=owner,+ uploaded_file=uploaded_file,+ form=form,+ original_filename=_normalize_asr_filename(+ request.form.get('file_name'),+ uploaded_file,+ ),+ processing_source='asr_voice_recorder',+ success_status=200,+ reuse_duplicate=True,+ )+ except RequestEntityTooLarge:+ return jsonify({'error': 'File too large'}), 413++@api_v1_bp.route('/recordings/upload', methods=['POST'])@login_requireddef upload_recording():diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 769a1df7..28a84e37 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -11,6 +11,7 @@ import mimetypesimport timeimport threadingimport subprocess+import uuidfrom datetime import datetime, timedelta, timezonefrom src.services.job_queue import job_queuefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_response@@ -2370,19 +2371,41 @@ def share_target():@recordings_bp.route('/upload', methods=['POST'])@login_requireddef upload_file():+ return ingest_uploaded_recording(+ owner=current_user,+ uploaded_file=request.files.get('file'),+ form=request.form,+ )+++def ingest_uploaded_recording(+ *,+ owner,+ uploaded_file,+ form,+ original_filename=None,+ processing_source='upload',+ success_status=202,+ reuse_duplicate=False,+):+ """Run an uploaded file through Speakr's standard ingestion pipeline."""try:- if 'file' not in request.files:+ if uploaded_file is None:return jsonify({'error': 'No file provided'}), 400- file = request.files['file']- if file.filename == '':+ file = uploaded_file+ if not original_filename:+ original_filename = file.filename+ if not original_filename:return jsonify({'error': 'No file selected'}), 400- original_filename = file.filenamesafe_filename = secure_filename(original_filename)storage = get_storage_service()staging_dir = storage.get_staging_dir()- filepath = os.path.join(staging_dir, f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{safe_filename}")+ filepath = os.path.join(+ staging_dir,+ f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex}_{safe_filename}",+ )# Per-upload override for VIDEO_RETENTION. When True, the# processing pipeline extracts audio and discards the video stream@@ -2391,7 +2414,7 @@ def upload_file():# only the extracted audio needs to fit that limit. Sent by the# frontend either explicitly (toggle) or implicitly when# VIDEO_RETENTION is off and the queued file is video.- keep_audio_only_flag = request.form.get('keep_audio_only', 'false').lower() == 'true'+ keep_audio_only_flag = form.get('keep_audio_only', 'false').lower() == 'true'effective_audio_only = keep_audio_only_flag or not VIDEO_RETENTION# Detect "this looks like a video" by extension up front so the@@ -2472,23 +2495,80 @@ def upload_file():# so hashing after conversion would miss duplicates.file_hash = Noneduplicate_warning = None+ existing = Nonetry:file_hash = compute_file_sha256(filepath)- existing = Recording.query.filter_by(- user_id=current_user.id, file_hash=file_hash- ).first()- if existing:- duplicate_warning = {- 'existing_recording_id': existing.id,- 'existing_title': existing.title,- 'existing_created_at': existing.created_at.isoformat() if existing.created_at else None- }- current_app.logger.info(- f"Duplicate file detected for user {current_user.id}: "- f"hash={file_hash[:12]}... matches recording {existing.id}"+ duplicate_query = Recording.query.filter_by(+ user_id=owner.id,+ file_hash=file_hash,+ )+ if reuse_duplicate:+ duplicate_query = duplicate_query.filter_by(+ processing_source=processing_source,+ original_filename=original_filename,+ notes=form.get('notes'),)+ replay_meeting_date = None+ raw_meeting_date = form.get('meeting_date')+ if raw_meeting_date:+ try:+ replay_meeting_date = to_utc_naive(+ datetime.fromisoformat(raw_meeting_date.replace('Z', '+00:00'))+ )+ except (ValueError, TypeError):+ pass+ if replay_meeting_date is not None:+ duplicate_query = duplicate_query.filter_by(meeting_date=replay_meeting_date)+ else:+ duplicate_query = duplicate_query.filter(+ Recording.created_at >= datetime.utcnow() - timedelta(days=1)+ )+ existing = duplicate_query.first()except Exception as e:- current_app.logger.warning(f"Could not compute file hash: {e}")+ current_app.logger.warning(f"Could not compute file hash or check duplicates: {e}")++ if existing and reuse_duplicate:+ # The existing recording already owns the durable media object, so+ # the retry's staging copy is never needed for job recovery. Remove+ # it before enqueueing to avoid leaking one full file each time a+ # temporarily unavailable queue makes ASR retry the delivery.+ try:+ if os.path.exists(filepath):+ os.remove(filepath)+ except OSError:+ pass++ existing_job = ProcessingJob.query.filter_by(+ recording_id=existing.id,+ job_type='transcribe',+ ).first()+ if existing.status in ('PENDING', 'QUEUED') and existing_job is None:+ recovery_params = resolve_transcription_params(owner=owner)+ job_queue.enqueue(+ user_id=owner.id,+ recording_id=existing.id,+ job_type='transcribe',+ params=recovery_params,+ is_new_upload=True,+ )+ current_app.logger.info(+ f"Idempotent upload replay for user {owner.id}: "+ f"hash={file_hash[:12]}... matches recording {existing.id}"+ )+ response_data = existing.to_dict(viewer_user=owner)+ response_data['idempotent_replay'] = True+ return jsonify(response_data), success_status++ if existing:+ duplicate_warning = {+ 'existing_recording_id': existing.id,+ 'existing_title': existing.title,+ 'existing_created_at': existing.created_at.isoformat() if existing.created_at else None+ }+ current_app.logger.info(+ f"Duplicate file detected for user {owner.id}: "+ f"hash={file_hash[:12]}... matches recording {existing.id}"+ )# --- Convert files only when chunking is needed ---filename_lower = original_filename.lower()@@ -2527,12 +2607,29 @@ def upload_file():# Video retention/passthrough: skip conversion for videos, processing pipeline handles extractionhas_video = codec_info.get('has_video', False) if codec_info else False+ # The extension is only a pre-probe size hint. Once ffprobe proves the+ # upload is audio-only, do not let a video-looking filename grant the+ # larger video upload ceiling.+ if codec_info is not None and is_likely_video_by_ext and not has_video:+ is_likely_video_by_ext = False+ if should_enforce_size_limit and original_file_size > regular_limit_mb * 1024 * 1024:+ effective_limit_mb = regular_limit_mb+ raise RequestEntityTooLarge()+# Fallback: if probe failed but VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR is on, check file extension# to avoid silently discarding video from files we couldn't probeif codec_info is None and (VIDEO_RETENTION or VIDEO_PASSTHROUGH_ASR) and not has_video:video_extensions = {'.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v', '.wmv', '.flv', '.ts', '.mts'}file_ext = os.path.splitext(original_filename)[1].lower()if file_ext in video_extensions:+ # A failed probe cannot justify the larger video ceiling: an+ # arbitrary blob or audio file can also carry a video-looking+ # extension. Require positive video detection for oversized+ # uploads; smaller files can continue through conversion.+ if should_enforce_size_limit and original_file_size > regular_limit_mb * 1024 * 1024:+ effective_limit_mb = regular_limit_mb+ is_likely_video_by_ext = False+ raise RequestEntityTooLarge()has_video = Truecurrent_app.logger.info(f"Probe failed but file extension '{file_ext}' indicates video — "@@ -2648,21 +2745,21 @@ def upload_file():current_app.logger.warning(f"Could not determine duration for upload {original_filename}: {e}")# Get notes from the form- notes = request.form.get('notes')+ notes = form.get('notes')# Get optional user-provided title and meeting_date- user_title = request.form.get('title')- user_meeting_date = request.form.get('meeting_date')+ user_title = form.get('title')+ user_meeting_date = form.get('meeting_date')# Get file's lastModified timestamp from client (milliseconds since epoch)- file_last_modified = request.form.get('file_last_modified')+ file_last_modified = form.get('file_last_modified')# Get selected tags if provided (multiple tags support)selected_tags = []tag_index = 0while True:tag_id_key = f'tag_ids[{tag_index}]'- tag_id = request.form.get(tag_id_key)+ tag_id = form.get(tag_id_key)if not tag_id:break@@ -2670,36 +2767,36 @@ def upload_file():tag = Tag.query.filter_by(id=tag_id).first()if tag:# Allow tag if it's user's own tag OR it's a group tag where user is a member- if tag.user_id == current_user.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=current_user.id).first()):+ if tag.user_id == owner.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=owner.id).first()):selected_tags.append(tag)tag_index += 1# For backward compatibility with single tag uploadsif not selected_tags:- single_tag_id = request.form.get('tag_id')+ single_tag_id = form.get('tag_id')if single_tag_id:# Check if tag belongs to user OR is a group tag where user is a membertag = Tag.query.filter_by(id=single_tag_id).first()- if tag and (tag.user_id == current_user.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=current_user.id).first())):+ if tag and (tag.user_id == owner.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=owner.id).first())):selected_tags.append(tag)# Get folder_id if providedselected_folder = None- folder_id = request.form.get('folder_id')+ folder_id = form.get('folder_id')if folder_id:folder = Folder.query.filter_by(id=folder_id).first()if folder:# Allow folder if it's user's own folder OR it's a group folder where user is a member- if folder.user_id == current_user.id or (folder.group_id and GroupMembership.query.filter_by(group_id=folder.group_id, user_id=current_user.id).first()):+ if folder.user_id == owner.id or (folder.group_id and GroupMembership.query.filter_by(group_id=folder.group_id, user_id=owner.id).first()):selected_folder = folder# Get ASR advanced options if provided- language = request.form.get('language', '')- min_speakers = request.form.get('min_speakers') or None- max_speakers = request.form.get('max_speakers') or None- hotwords = request.form.get('hotwords', '').strip() or None- initial_prompt = request.form.get('initial_prompt', '').strip() or None- transcription_model = request.form.get('transcription_model', '').strip() or None+ language = form.get('language', '')+ min_speakers = form.get('min_speakers') or None+ max_speakers = form.get('max_speakers') or None+ hotwords = form.get('hotwords', '').strip() or None+ initial_prompt = form.get('initial_prompt', '').strip() or None+ transcription_model = form.get('transcription_model', '').strip() or None# Per-recording prompt-template variables. Sent as a JSON string from# the upload form so multiple values fit in a single form field. The@@ -2707,7 +2804,7 @@ def upload_file():# size caps so an arbitrary JSON blob cannot bloat the column.from src.utils.prompt_variables import sanitize_variable_valuesprompt_variables = None- raw_prompt_variables = request.form.get('prompt_variables')+ raw_prompt_variables = form.get('prompt_variables')if raw_prompt_variables:try:parsed_vars = json.loads(raw_prompt_variables)@@ -2748,7 +2845,7 @@ def upload_file():},tags=selected_tags,folder=selected_folder,- owner=current_user,+ owner=owner,)# Create initial database entry@@ -2799,12 +2896,12 @@ def upload_file():file_size=final_file_size,status='PENDING',meeting_date=meeting_date,- user_id=current_user.id,+ user_id=owner.id,mime_type=mime_type,audio_duration_seconds=audio_duration_seconds,notes=notes,folder_id=selected_folder.id if selected_folder else None,- processing_source='upload', # Track that this was manually uploaded+ processing_source=processing_source,file_hash=file_hash,prompt_variables=prompt_variables,# Per-upload override: record the effective audio-only flag so@@ -2852,7 +2949,7 @@ def upload_file():current_app.logger.info(f"Queueing transcription for recording {recording.id} with params: {job_params}")job_queue.enqueue(- user_id=current_user.id,+ user_id=owner.id,recording_id=recording.id,job_type='transcribe',params=job_params,@@ -2866,7 +2963,7 @@ def upload_file():try:from src.services.webhook_dispatch import emit_webhook_eventemit_webhook_event(- user_id=current_user.id,+ user_id=owner.id,event_type='recording.created',data={'recording_id': recording.id,@@ -2878,12 +2975,19 @@ def upload_file():except Exception as e:current_app.logger.warning(f"Webhook emit (recording.created) failed: {e}")- response_data = recording.to_dict(viewer_user=current_user)+ response_data = recording.to_dict(viewer_user=owner)if duplicate_warning:response_data['duplicate_warning'] = duplicate_warning- return jsonify(response_data), 202+ if reuse_duplicate:+ response_data['idempotent_replay'] = False+ return jsonify(response_data), success_statusexcept RequestEntityTooLarge:+ try:+ if 'filepath' in locals() and filepath and os.path.exists(filepath):+ os.remove(filepath)+ except OSError:+ pass# Report the effective limit that fired (regular vs audio-only)# so the frontend can show the right message. effective_limit_mb# is set at the top of the function before the size check.diff --git a/src/app.py b/src/app.pyindex 9ff875fc..6c4e411d 100644--- a/src/app.py+++ b/src/app.py@@ -626,6 +626,18 @@ def csrf_token_aware_check():csrf.protect()[email protected](RequestEntityTooLarge)+def handle_request_entity_too_large(_error):+ """Keep oversized requests JSON-shaped even when parsing fails early."""+ limit_mb = float(app.config['MAX_CONTENT_LENGTH']) / (1024 * 1024)+ return jsonify({+ 'error': f'File too large. Maximum size is {limit_mb:.0f} MB.',+ 'max_size_mb': limit_mb,+ 'effective_limit_mb': limit_mb,+ 'audio_only_mode': False,+ }), 413++# Add context processor to make 'now' available to all templates@app.context_processordef inject_now():diff --git a/src/utils/token_auth.py b/src/utils/token_auth.pyindex c6999390..993889eb 100644--- a/src/utils/token_auth.py+++ b/src/utils/token_auth.py@@ -70,43 +70,40 @@ def hash_token(token):return hashlib.sha256(token.encode()).hexdigest()-def load_user_from_token():- """- Load a user from an API token in the request.-- This function is used by Flask-Login's request_loader to authenticate- users via API tokens instead of sessions.+def load_user_from_token_value(token):+ """Validate a plaintext API token and return its associated user.- Returns:- User: The authenticated user, or None if authentication fails+ The caller controls where the token came from. Keeping this separate from+ request extraction lets narrow integrations authenticate an explicit field+ without making that field a global token source for every route."""- # Extract token from request- token = extract_token_from_request()if not token:return None- # Hash the token to look up in databasetoken_hash = hash_token(token)-- # Find the token in the databaseapi_token = APIToken.query.filter_by(token_hash=token_hash).first()-- # Validate token- if not api_token:- return None-- if not api_token.is_valid():+ if not api_token or not api_token.is_valid():return None- # Update last used timestampapi_token.last_used_at = datetime.utcnow()from src.database import dbdb.session.commit()-- # Return the associated userreturn api_token.user+def load_user_from_token():+ """+ Load a user from an API token in the request.++ This function is used by Flask-Login's request_loader to authenticate+ users via API tokens instead of sessions.++ Returns:+ User: The authenticated user, or None if authentication fails+ """+ return load_user_from_token_value(extract_token_from_request())++def load_user_from_token_headers_only():"""Validate a header-only API token against the database.@@ -119,18 +116,6 @@ def load_user_from_token_headers_only():Returns the authenticated User, or None."""- token = extract_token_from_request(headers_only=True)- if not token:- return None-- token_hash = hash_token(token)- api_token = APIToken.query.filter_by(token_hash=token_hash).first()- if not api_token or not api_token.is_valid():- return None-- api_token.last_used_at = datetime.utcnow()- from src.database import db- db.session.commit()- return api_token.user+ return load_user_from_token_value(extract_token_from_request(headers_only=True))diff --git a/tests/test_asr_voice_recorder_upload.py b/tests/test_asr_voice_recorder_upload.pynew file mode 100644index 00000000..8fd0f8c5--- /dev/null+++ b/tests/test_asr_voice_recorder_upload.py@@ -0,0 +1,462 @@+"""Integration coverage for the ASR Voice Recorder upload adapter."""++import io+import json+import os+import secrets+import uuid+from contextlib import contextmanager+from datetime import datetime, timedelta, timezone+from unittest.mock import MagicMock, patch++import pytest++from src.app import app, db+from src.api import api_v1+from src.models import APIToken, ProcessingJob, Recording, User+from src.utils.ffprobe import FFProbeError+from src.utils.token_auth import hash_token++app.config["WTF_CSRF_ENABLED"] = False+++class _StoredObject:+ def __init__(self, locator):+ self.locator = locator+++class _Storage:+ def __init__(self, staging_dir):+ self.staging_dir = staging_dir+ self.uploaded = []++ def get_staging_dir(self):+ os.makedirs(self.staging_dir, exist_ok=True)+ return self.staging_dir++ def build_recording_key(self, original_filename, recording_id=None, *, now=None):+ return f"recordings/asr/{recording_id}/{original_filename}"++ def upload_local_file(self, local_path, key, *, content_type=None, delete_source=False):+ self.uploaded.append((local_path, key))+ return _StoredObject(f"local://{key}")+++def _user(prefix="asr"):+ 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 _token(user, *, expired=False, revoked=False):+ plaintext = f"asr-{secrets.token_urlsafe(24)}"+ token = APIToken(+ user_id=user.id,+ token_hash=hash_token(plaintext),+ name="ASR Voice Recorder",+ revoked=revoked,+ expires_at=(datetime.utcnow() - timedelta(minutes=1)) if expired else None,+ )+ db.session.add(token)+ db.session.commit()+ return token, plaintext+++def _login(client, user):+ with client.session_transaction() as session:+ session["_user_id"] = str(user.id)+ session["_fresh"] = True+++def _cleanup_user(user):+ ProcessingJob.query.filter_by(user_id=user.id).delete(synchronize_session=False)+ Recording.query.filter_by(user_id=user.id).delete(synchronize_session=False)+ APIToken.query.filter_by(user_id=user.id).delete(synchronize_session=False)+ db.session.delete(user)+ db.session.commit()+++@contextmanager+def _upload_mocks(staging_dir):+ storage = _Storage(staging_dir)++ def convert(filepath, **kwargs):+ result = MagicMock()+ result.output_path = filepath+ result.was_converted = False+ result.was_compressed = False+ result.original_codec = "aac"+ result.final_codec = "aac"+ result.size_reduction_percent = 0+ return result++ def enqueue(**kwargs):+ job = ProcessingJob(+ user_id=kwargs["user_id"],+ recording_id=kwargs["recording_id"],+ job_type=kwargs["job_type"],+ status="completed",+ params=json.dumps(kwargs.get("params") or {}),+ is_new_upload=kwargs.get("is_new_upload", False),+ )+ db.session.add(job)+ db.session.commit()+ return job.id++ with patch("src.api.recordings.get_storage_service", return_value=storage), \+ patch("src.api.recordings.get_codec_info", return_value={"has_video": False, "audio_codec": "aac"}), \+ patch("src.api.recordings.convert_if_needed", side_effect=convert), \+ patch("src.api.recordings.get_duration", return_value=12.5), \+ patch("src.api.recordings.get_creation_date", return_value=None), \+ patch("src.services.job_queue.job_queue.enqueue", side_effect=enqueue) as enqueue_mock, \+ patch("src.services.webhook_dispatch.emit_webhook_event") as webhook_mock:+ yield storage, enqueue_mock, webhook_mock+++def _post(client, secret=None, payload=b"audio-bytes", filename="voice.m4a", **fields):+ data = dict(fields)+ if secret is not None:+ data["secret"] = secret+ data["file"] = (io.BytesIO(payload), filename)+ return client.post(+ "/api/v1/integrations/asr-voice-recorder/upload",+ data=data,+ content_type="multipart/form-data",+ )++[email protected](autouse=True)+def _disable_rate_limiter_for_isolated_requests():+ original = api_v1.limiter+ api_v1.limiter = None+ try:+ yield+ finally:+ api_v1.limiter = original+++def test_missing_invalid_expired_and_revoked_secrets_share_one_error(tmp_path):+ with app.app_context():+ user = _user("asr_auth")+ _, expired = _token(user, expired=True)+ _, revoked = _token(user, revoked=True)+ client = app.test_client()+ try:+ for secret in (None, "not-a-token", expired, revoked):+ response = _post(client, secret=secret)+ assert response.status_code == 401+ assert response.get_json() == {"error": "Authentication failed"}+ assert Recording.query.filter_by(user_id=user.id).count() == 0+ finally:+ _cleanup_user(user)+++def test_oversized_body_is_rejected_before_multipart_authentication():+ with app.app_context():+ client = app.test_client()+ with patch("src.models.SystemSetting.get_setting", return_value=1):+ response = client.post(+ "/api/v1/integrations/asr-voice-recorder/upload",+ data={+ "secret": "not-a-token",+ "file": (io.BytesIO(b"x" * (2 * 1024 * 1024)), "large.m4a"),+ },+ content_type="multipart/form-data",+ )+ assert response.status_code == 413+ assert response.get_json() == {"error": "File too large"}+++def test_session_or_header_cannot_replace_multipart_secret(tmp_path):+ with app.app_context():+ user = _user("asr_no_fallback")+ _, token = _token(user)+ client = app.test_client()+ _login(client, user)+ try:+ session_response = _post(client, secret=None)+ header_response = client.post(+ "/api/v1/integrations/asr-voice-recorder/upload",+ headers={"Authorization": f"Bearer {token}"},+ data={"file": (io.BytesIO(b"audio"), "voice.m4a")},+ content_type="multipart/form-data",+ )+ assert session_response.status_code == 401+ assert header_response.status_code == 401+ finally:+ _cleanup_user(user)+++def test_valid_secret_controls_owner_and_maps_asr_fields(tmp_path, caplog):+ with app.app_context():+ session_user = _user("asr_session")+ token_user = _user("asr_owner")+ token_record, token = _token(token_user)+ client = app.test_client()+ _login(client, session_user)+ try:+ with _upload_mocks(str(tmp_path)) as (storage, enqueue, webhook):+ response = _post(+ client,+ secret=token,+ file_name="../../Interview\r\nOne.m4a",+ note="Recorded through the RODE receiver",+ date="1700000000",+ duration="999999",+ )++ assert response.status_code == 200, response.data+ payload = response.get_json()+ recording = db.session.get(Recording, payload["id"])+ assert recording.user_id == token_user.id+ assert recording.user_id != session_user.id+ assert recording.original_filename == "Interview_One.m4a"+ assert recording.notes == "Recorded through the RODE receiver"+ assert recording.meeting_date == datetime.fromtimestamp(1700000000, tz=timezone.utc).replace(tzinfo=None)+ assert recording.audio_duration_seconds == 12.5+ assert recording.processing_source == "asr_voice_recorder"+ assert payload["idempotent_replay"] is False+ assert len(storage.uploaded) == 1+ assert enqueue.call_count == 1+ assert webhook.call_count == 1+ db.session.refresh(token_record)+ assert token_record.last_used_at is not None+ assert token not in response.get_data(as_text=True)+ assert token not in caplog.text+ finally:+ _cleanup_user(session_user)+ _cleanup_user(token_user)+++def test_date_accepts_epoch_milliseconds(tmp_path):+ with app.app_context():+ user = _user("asr_date_ms")+ _, token = _token(user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)):+ response = _post(client, secret=token, date="1700000000000")+ recording = db.session.get(Recording, response.get_json()["id"])+ assert recording.meeting_date == datetime.fromtimestamp(1700000000, tz=timezone.utc).replace(tzinfo=None)+ finally:+ _cleanup_user(user)+++def test_identical_retry_reuses_recording_without_new_job_or_event(tmp_path):+ with app.app_context():+ user = _user("asr_retry")+ _, token = _token(user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)) as (storage, enqueue, webhook):+ first = _post(client, secret=token, payload=b"same-recording")+ second = _post(client, secret=token, payload=b"same-recording")++ assert first.status_code == 200+ assert second.status_code == 200+ first_payload = first.get_json()+ second_payload = second.get_json()+ assert first_payload["id"] == second_payload["id"]+ assert first_payload["idempotent_replay"] is False+ assert second_payload["idempotent_replay"] is True+ assert Recording.query.filter_by(user_id=user.id).count() == 1+ assert len(storage.uploaded) == 1+ assert enqueue.call_count == 1+ assert webhook.call_count == 1+ finally:+ _cleanup_user(user)+++def test_failed_replay_job_recovery_cleans_retry_staging_file(tmp_path):+ with app.app_context():+ user = _user("asr_recovery_cleanup")+ _, token = _token(user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)) as (_, enqueue, _):+ first = _post(client, secret=token, payload=b"recovery-audio")+ recording = db.session.get(Recording, first.get_json()["id"])+ ProcessingJob.query.filter_by(recording_id=recording.id).delete()+ recording.status = "PENDING"+ db.session.commit()++ for name in os.listdir(tmp_path):+ os.remove(os.path.join(tmp_path, name))++ enqueue.side_effect = RuntimeError("queue unavailable")+ replay = _post(client, secret=token, payload=b"recovery-audio")++ assert replay.status_code == 500+ assert os.listdir(tmp_path) == []+ finally:+ _cleanup_user(user)+++def test_same_bytes_with_different_metadata_are_distinct_recordings(tmp_path):+ with app.app_context():+ user = _user("asr_distinct")+ _, token = _token(user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)):+ first = _post(+ client,+ secret=token,+ payload=b"same-audio",+ file_name="first.m4a",+ note="First occurrence",+ date="1700000000",+ )+ second = _post(+ client,+ secret=token,+ payload=b"same-audio",+ file_name="second.m4a",+ note="Second occurrence",+ date="1700003600",+ )+ assert first.get_json()["id"] != second.get_json()["id"]+ assert Recording.query.filter_by(user_id=user.id).count() == 2+ finally:+ _cleanup_user(user)+++def test_same_bytes_are_independent_between_users(tmp_path):+ with app.app_context():+ first_user = _user("asr_first")+ second_user = _user("asr_second")+ _, first_token = _token(first_user)+ _, second_token = _token(second_user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)):+ first = _post(client, secret=first_token, payload=b"shared-bytes")+ second = _post(client, secret=second_token, payload=b"shared-bytes")+ assert first.get_json()["id"] != second.get_json()["id"]+ assert Recording.query.filter_by(user_id=first_user.id).count() == 1+ assert Recording.query.filter_by(user_id=second_user.id).count() == 1+ finally:+ _cleanup_user(first_user)+ _cleanup_user(second_user)+++def test_authenticated_connection_probe_without_file_returns_200():+ with app.app_context():+ user = _user("asr_connection_test")+ _, token = _token(user)+ client = app.test_client()+ try:+ response = client.post(+ "/api/v1/integrations/asr-voice-recorder/upload",+ data={"secret": token, "source": "com.nll.asr"},+ content_type="multipart/form-data",+ )+ assert response.status_code == 200+ assert response.get_json() == {"status": "ok", "connection_test": True}+ assert Recording.query.filter_by(user_id=user.id).count() == 0+ finally:+ _cleanup_user(user)+++def test_missing_file_after_valid_auth_returns_400():+ with app.app_context():+ user = _user("asr_missing_file")+ _, token = _token(user)+ client = app.test_client()+ try:+ response = client.post(+ "/api/v1/integrations/asr-voice-recorder/upload",+ data={"secret": token, "file_name": "missing.m4a"},+ content_type="multipart/form-data",+ )+ assert response.status_code == 400+ assert response.get_json() == {"error": "No file provided"}+ finally:+ _cleanup_user(user)+++def test_unprobeable_video_named_upload_uses_audio_limit_and_cleans_staging(tmp_path):+ with app.app_context():+ user = _user("asr_unprobeable")+ _, token = _token(user)+ client = app.test_client()+ storage = _Storage(str(tmp_path))++ def setting(name, default=None):+ if name == "max_file_size_mb":+ return 1+ if name == "max_audio_only_video_size_mb":+ return 4+ return default++ try:+ with patch("src.api.recordings.get_storage_service", return_value=storage), \+ patch("src.api.recordings.SystemSetting.get_setting", side_effect=setting), \+ patch("src.api.recordings.get_codec_info", side_effect=FFProbeError("unprobeable")), \+ patch("src.api.recordings.VIDEO_RETENTION", True), \+ patch("src.api.recordings.chunking_service", None):+ response = _post(+ client,+ secret=token,+ payload=b"x" * (2 * 1024 * 1024),+ file_name="not-really-video.mp4",+ filename="not-really-video.mp4",+ )++ assert response.status_code == 413+ assert list(tmp_path.iterdir()) == []+ assert Recording.query.filter_by(user_id=user.id).count() == 0+ finally:+ _cleanup_user(user)+++def test_normal_api_upload_still_returns_202(tmp_path):+ with app.app_context():+ user = _user("asr_normal_api")+ _, token = _token(user)+ client = app.test_client()+ try:+ with _upload_mocks(str(tmp_path)):+ response = client.post(+ "/api/v1/recordings/upload",+ headers={"Authorization": f"Bearer {token}"},+ data={"file": (io.BytesIO(b"normal-upload"), "normal.m4a")},+ content_type="multipart/form-data",+ )+ assert response.status_code == 202+ assert "idempotent_replay" not in response.get_json()+ finally:+ _cleanup_user(user)+++def test_asr_upload_rate_cost_bounds_requests_and_declared_bytes_before_parsing():+ for declared_mib, expected_cost in ((5, 52), (100, 100)):+ with app.test_request_context(+ "/api/v1/integrations/asr-voice-recorder/upload",+ method="POST",+ environ_overrides={"CONTENT_LENGTH": str(declared_mib * 1024 * 1024)},+ ):+ assert api_v1._asr_upload_rate_cost() == expected_cost++ with app.test_request_context(+ "/api/v1/integrations/asr-voice-recorder/upload",+ method="POST",+ ):+ assert api_v1._asr_upload_rate_cost() == api_v1._ASR_RATE_UNITS_PER_MINUTE+++def test_openapi_documents_asr_multipart_contract():+ operation = api_v1.OPENAPI_SPEC["paths"]["/integrations/asr-voice-recorder/upload"]["post"]+ schema = operation["requestBody"]["content"]["multipart/form-data"]["schema"]+ assert operation["security"] == []+ assert schema["required"] == ["secret"]+ assert set(schema["properties"]) == {"file", "file_name", "secret", "date", "duration", "note"}+ assert operation["responses"]["200"]["description"]+ assert api_v1.upload_from_asr_voice_recorder._rate_limit == "520 per minute"+ assert api_v1.upload_from_asr_voice_recorder._rate_limit_options["cost"] is api_v1._asr_upload_rate_costdiff --git a/tests/test_cov_recordings_write.py b/tests/test_cov_recordings_write.pyindex 8cd74e12..9d543faf 100644--- a/tests/test_cov_recordings_write.py+++ b/tests/test_cov_recordings_write.py@@ -23,6 +23,8 @@ import uuidfrom contextlib import contextmanagerfrom unittest.mock import patch, MagicMock+import pytest+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from src.app import app, db@@ -555,6 +557,27 @@ def test_upload_too_large_returns_413():_cleanup(user)+def test_upload_global_request_limit_returns_json_413_before_csrf():+ with app.app_context():+ user = _mk_user("up_global_big")+ client = app.test_client()+ _login(client, user)+ original_limit = app.config["MAX_CONTENT_LENGTH"]+ original_csrf = app.config["WTF_CSRF_ENABLED"]+ try:+ app.config["MAX_CONTENT_LENGTH"] = 1024+ app.config["WTF_CSRF_ENABLED"] = True+ resp = _do_upload(client, payload=b"x" * 8192)+ finally:+ app.config["MAX_CONTENT_LENGTH"] = original_limit+ app.config["WTF_CSRF_ENABLED"] = original_csrf+ assert resp.status_code == 413+ body = resp.get_json()+ assert body["max_size_mb"] == pytest.approx(1024 / (1024 * 1024))+ assert body["audio_only_mode"] is False+ _cleanup(user)++def test_upload_requires_login():with app.app_context():client = app.test_client() # not logged indiff --git a/tests/test_video_retention.py b/tests/test_video_retention.pyindex ae55f082..3056a245 100644--- a/tests/test_video_retention.py+++ b/tests/test_video_retention.py@@ -129,11 +129,10 @@ class TestUploadHandlerVideoRetention(unittest.TestCase):cls.content = f.read()def test_upload_handler_parses_keep_audio_only_form_field(self):- """The new per-upload `keep_audio_only` form field is parsed at- the top of the upload handler. Without this parse, the override- is silently ignored."""+ """The shared upload core parses the `keep_audio_only` form field.+ Without this parse, the per-upload override is silently ignored."""self.assertIn(- "request.form.get('keep_audio_only', 'false').lower() == 'true'",+ "form.get('keep_audio_only', 'false').lower() == 'true'",self.content,)self.assertIn('keep_audio_only_flag', self.content)