Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: per-user archive that hides a recording from the main list without deleting anything, and a Delete audio action that keeps the transcript; the audio-deleted state is now filtered as audio_removed (#394)
Murtaza Nasir64157f514f42
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex cca1dbd3..357c1660 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -139,6 +139,7 @@ OPENAPI_SPEC = {"participants": {"type": "string"},"is_inbox": {"type": "boolean"},"is_highlighted": {"type": "boolean"},+ "is_archived": {"type": "boolean", "description": "Hidden from the main list in the web app; nothing is deleted"},"deletion_exempt": {"type": "boolean", "description": "If true, recording is exempt from auto-deletion"},"prompt_variables": {"type": "object", "description": "Per-recording {{name}} substitutions used when summarising"},"folder_id": {"type": "integer", "nullable": True},@@ -230,6 +231,7 @@ OPENAPI_SPEC = {{"name": "sort_by", "in": "query", "schema": {"type": "string", "enum": ["created_at", "meeting_date", "title", "file_size"]}},{"name": "sort_order", "in": "query", "schema": {"type": "string", "enum": ["asc", "desc"]}},{"name": "tag_id", "in": "query", "schema": {"type": "integer"}},+ {"name": "archived", "in": "query", "schema": {"type": "boolean"}, "description": "true: only archived recordings; false: only unarchived. Omitted: both, as before."},{"name": "folder_id", "in": "query", "schema": {"type": "string"}, "description": "Filter by folder. Pass an integer folder id to list recordings in that folder, or the literal 'none' to list recordings not in any folder. Omit for no filter."},{"name": "q", "in": "query", "schema": {"type": "string"}, "description": "Search query"}],@@ -251,7 +253,7 @@ OPENAPI_SPEC = {"tags": ["Recordings"],"summary": "Update recording","parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}],- "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"title": {"type": "string"}, "participants": {"type": "string"}, "notes": {"type": "string"}, "summary": {"type": "string"}, "meeting_date": {"type": "string"}, "is_inbox": {"type": "boolean"}, "is_highlighted": {"type": "boolean"}, "folder_id": {"type": "integer", "nullable": True, "description": "Move recording to this folder, or null to remove from any folder. Caller must have access to the target folder."}}}}}},+ "requestBody": {"content": {"application/json": {"schema": {"type": "object", "properties": {"title": {"type": "string"}, "participants": {"type": "string"}, "notes": {"type": "string"}, "summary": {"type": "string"}, "meeting_date": {"type": "string"}, "is_inbox": {"type": "boolean"}, "is_highlighted": {"type": "boolean"}, "is_archived": {"type": "boolean"}, "folder_id": {"type": "integer", "nullable": True, "description": "Move recording to this folder, or null to remove from any folder. Caller must have access to the target folder."}}}}}},"responses": {"200": {"description": "Updated recording"}, "403": {"description": "No access to target folder"}, "404": {"description": "Recording or folder not found"}}},"delete": {@@ -280,6 +282,9 @@ OPENAPI_SPEC = {"get": {"tags": ["Recordings"], "summary": "Get notes", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Notes markdown"}}},"put": {"tags": ["Recordings"], "summary": "Replace notes", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["notes"], "properties": {"notes": {"type": "string"}}}}}}, "responses": {"200": {"description": "Updated"}}}},+ "/recordings/{id}/delete-audio": {+ "post": {"tags": ["Recordings"], "summary": "Delete audio, keep transcript", "description": "Deletes the media file and keeps the transcript, summary and notes. Same permission as deleting the recording. 409 if the audio is already removed or the recording is still processing.", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Audio removed"}, "403": {"description": "Permission denied"}, "404": {"description": "Recording not found"}, "409": {"description": "Already removed or still processing"}}}+ },"/recordings/{id}/status": {"get": {"tags": ["Recordings"], "summary": "Get processing status", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "Status with queue position"}}}},@@ -329,7 +334,7 @@ OPENAPI_SPEC = {}},"/recordings/batch": {- "patch": {"tags": ["Batch"], "summary": "Batch update recordings", "description": "Apply the same set of updates to multiple recordings in one call. Supported fields inside `updates`: `is_inbox`, `is_highlighted`, `add_tag_ids` (array of tag ids to add), `remove_tag_ids` (array of tag ids to remove), `folder_id` (move all to this folder, or null to remove from any folder).", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["recording_ids", "updates"], "properties": {"recording_ids": {"type": "array", "items": {"type": "integer"}}, "updates": {"type": "object", "properties": {"is_inbox": {"type": "boolean"}, "is_highlighted": {"type": "boolean"}, "add_tag_ids": {"type": "array", "items": {"type": "integer"}}, "remove_tag_ids": {"type": "array", "items": {"type": "integer"}}, "folder_id": {"type": "integer", "nullable": True, "description": "Target folder id, or null to remove all selected recordings from their folders. Caller must have access."}}}}}}}}, "responses": {"200": {"description": "Batch results"}, "403": {"description": "No access to target folder"}, "404": {"description": "Target folder not found"}}},+ "patch": {"tags": ["Batch"], "summary": "Batch update recordings", "description": "Apply the same set of updates to multiple recordings in one call. Supported fields inside `updates`: `is_inbox`, `is_highlighted`, `is_archived`, `add_tag_ids` (array of tag ids to add), `remove_tag_ids` (array of tag ids to remove), `folder_id` (move all to this folder, or null to remove from any folder).", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["recording_ids", "updates"], "properties": {"recording_ids": {"type": "array", "items": {"type": "integer"}}, "updates": {"type": "object", "properties": {"is_inbox": {"type": "boolean"}, "is_highlighted": {"type": "boolean"}, "is_archived": {"type": "boolean"}, "add_tag_ids": {"type": "array", "items": {"type": "integer"}}, "remove_tag_ids": {"type": "array", "items": {"type": "integer"}}, "folder_id": {"type": "integer", "nullable": True, "description": "Target folder id, or null to remove all selected recordings from their folders. Caller must have access."}}}}}}}}, "responses": {"200": {"description": "Batch results"}, "403": {"description": "No access to target folder"}, "404": {"description": "Target folder not found"}}},"delete": {"tags": ["Batch"], "summary": "Batch delete recordings", "requestBody": {"content": {"application/json": {"schema": {"type": "object", "required": ["recording_ids"], "properties": {"recording_ids": {"type": "array", "items": {"type": "integer"}}}}}}}, "responses": {"200": {"description": "Batch results"}}}},"/recordings/batch/transcribe": {@@ -817,6 +822,7 @@ def list_recordings():q: Search query (title, participants)inbox: Filter by inbox status (true/false)starred: Filter by starred status (true/false)+ archived: Filter by archive status (true/false); omitted returns both"""# Parse query parameterspage = request.args.get('page', 1, type=int)@@ -831,6 +837,7 @@ def list_recordings():search_query = request.args.get('q', '').strip()inbox_filter = request.args.get('inbox')starred_filter = request.args.get('starred')+ archived_filter = request.args.get('archived')# Base query - user's recordings.# Eager-load folder and tag-association+Tag so the list builder@@ -911,6 +918,12 @@ def list_recordings():is_starred = starred_filter.lower() == 'true'query = query.filter(Recording.is_highlighted == is_starred)+ # Archive filter (#394). The API keeps returning archived recordings by+ # default so existing integrations see no change.+ if archived_filter is not None:+ is_archived = archived_filter.lower() == 'true'+ query = query.filter(db.func.coalesce(Recording.is_archived, False) == is_archived)+# Sortingsort_columns = {'created_at': Recording.created_at,@@ -944,6 +957,7 @@ def list_recordings():'participants': r.participants,'is_inbox': r.is_inbox,'is_highlighted': r.is_highlighted,+ 'is_archived': bool(r.is_archived),'audio_available': r.audio_deleted_at is None,'audio_duration': r.get_audio_duration(),'has_transcription': bool(r.transcription),@@ -1011,6 +1025,7 @@ def get_recording(recording_id):'mime_type': recording.mime_type,'is_inbox': recording.is_inbox,'is_highlighted': recording.is_highlighted,+ 'is_archived': bool(recording.is_archived),'audio_available': recording.audio_deleted_at is None,'audio_duration': recording.get_audio_duration(),'processing_time_seconds': recording.processing_time_seconds,@@ -1247,6 +1262,9 @@ def update_recording(recording_id):if 'is_highlighted' in data:recording.is_highlighted = bool(data['is_highlighted'])changed_fields.append('is_highlighted')+ if 'is_archived' in data:+ recording.is_archived = bool(data['is_archived'])+ changed_fields.append('is_archived')if 'folder_id' in data:new_folder_id = data['folder_id']if new_folder_id is None:@@ -1301,6 +1319,7 @@ def update_recording(recording_id):'meeting_date': recording.meeting_date.isoformat() if recording.meeting_date else None,'is_inbox': recording.is_inbox,'is_highlighted': recording.is_highlighted,+ 'is_archived': bool(recording.is_archived),'folder_id': recording.folder_id}})@@ -1385,6 +1404,28 @@ def delete_recording(recording_id):return jsonify({'success': True, 'message': 'Recording deleted'})+@api_v1_bp.route('/recordings/<int:recording_id>/delete-audio', methods=['POST'])+@login_required+def delete_recording_audio(recording_id):+ """Delete a recording's media file and keep its transcript, summary and notes."""+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404+ if recording.user_id != current_user.id:+ return jsonify({'error': 'Permission denied - only owner can delete'}), 403+ USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'+ if not USERS_CAN_DELETE and not current_user.is_admin:+ return jsonify({'error': 'Deletion not allowed'}), 403+ if recording.audio_deleted_at:+ return jsonify({'error': 'The audio has already been removed'}), 409+ if recording.status not in ('COMPLETED', 'FAILED'):+ return jsonify({'error': 'Wait until processing has finished before removing the audio'}), 409++ from src.services.retention import remove_recording_audio+ remove_recording_audio(recording)+ return jsonify({'success': True, 'audio_deleted_at': recording.audio_deleted_at.isoformat()})++# =============================================================================# Recording Status# =============================================================================@@ -2703,6 +2744,8 @@ def batch_update_recordings():recording.is_inbox = bool(updates['is_inbox'])if 'is_highlighted' in updates:recording.is_highlighted = bool(updates['is_highlighted'])+ if 'is_archived' in updates:+ recording.is_archived = bool(updates['is_archived'])if 'folder_id' in updates:# `target_folder_id` already validated above (None to remove,# or a valid folder id the caller has access to).diff --git a/src/api/recordings.py b/src/api/recordings.pyindex d7f20f60..0f57b07f 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -1406,8 +1406,9 @@ def index(recording_id=None, label_name=None):# Pass the ASR config, inquire mode config, and user language preference to the templateuser_language = current_user.ui_language if current_user.is_authenticated and current_user.ui_language else 'en'- # Calculate if archive toggle should be shown (only when audio-only deletion mode is active)- enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'+ # The "Audio removed" filter matters when retention removes audio; users+ # who can delete recordings can also remove audio by hand.+ enable_audio_removed_filter = (ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only') or USERS_CAN_DELETE or current_user.is_admin# Get connector capabilities (new architecture)# Defaults to USE_ASR_ENDPOINT for backwards compatibility@@ -1476,7 +1477,7 @@ def index(recording_id=None, label_name=None):connector_supports_hotwords=connector_supports_hotwords,connector_supports_initial_prompt=connector_supports_initial_prompt,inquire_mode_enabled=ENABLE_INQUIRE_MODE,- enable_archive_toggle=enable_archive_toggle,+ enable_audio_removed_filter=enable_audio_removed_filter,enable_internal_sharing=ENABLE_INTERNAL_SHARING,user_language=user_language,is_team_admin=is_team_admin,@@ -1551,7 +1552,10 @@ def get_recordings_paginated():page = request.args.get('page', 1, type=int)per_page = min(request.args.get('per_page', 25, type=int), 100) # Cap at 100 per pagesearch_query = request.args.get('q', '').strip()+ # 'archived' is the user's own archive (#394); 'audio_removed' is the+ # state left when the media file was deleted and the transcript kept.show_archived = request.args.get('archived', '').lower() == 'true'+ show_audio_removed = request.args.get('audio_removed', '').lower() == 'true'show_shared = request.args.get('shared', '').lower() == 'true'show_starred = request.args.get('starred', '').lower() == 'true'show_inbox = request.args.get('inbox', '').lower() == 'true'@@ -1586,11 +1590,19 @@ def get_recordings_paginated():if status_filter:stmt = stmt.where(Recording.status == status_filter)- # Apply archived filter (AND with other filters)- if show_archived:- # Only show recordings where audio has been deleted+ # Audio removed filter (AND with other filters)+ if show_audio_removed:stmt = stmt.where(Recording.audio_deleted_at.is_not(None))+ # Archive: the archived view shows only archived recordings; the main+ # list hides them, except in search results, so archiving never makes+ # a recording unfindable.+ from src.services.recording_state import archived_condition+ if show_archived:+ stmt = stmt.where(archived_condition(Recording, current_user.id))+ elif not search_query:+ stmt = stmt.where(db.not_(archived_condition(Recording, current_user.id)))+# Apply shared filter (AND with other filters)if show_shared:# Only show recordings shared with current user (not owned by them)@@ -1933,6 +1945,8 @@ def get_recordings_paginated():user_inbox, user_highlighted = get_user_recording_status(recording, current_user)rec_dict['is_inbox'] = user_inboxrec_dict['is_highlighted'] = user_highlighted+ from src.services.recording_state import get_user_archived+ rec_dict['is_archived'] = get_user_archived(recording, current_user)# Add edit permission info (uses has_recording_access which checks group admin status)rec_dict['can_edit'] = has_recording_access(recording, current_user, require_edit=True)@@ -2091,6 +2105,9 @@ def save_metadata():is_inbox=data.get('is_inbox'),is_highlighted=data.get('is_highlighted'))+ if 'is_archived' in data:+ from src.services.recording_state import set_user_archived+ set_user_archived(recording, current_user, data.get('is_archived'))db.session.commit()@@ -2202,6 +2219,60 @@ def toggle_highlight(recording_id):+@recordings_bp.route('/recording/<int:recording_id>/toggle_archive', methods=['POST'])+@login_required+def toggle_archive(recording_id):+ """Archive or unarchive a recording for the current user (#394)."""+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404+ # Like inbox and star, archiving is personal and needs only view access.+ if not has_recording_access(recording, current_user, require_edit=False):+ return jsonify({'error': 'You do not have permission to view this recording'}), 403+ from src.services.recording_state import get_user_archived, set_user_archived+ new_value = set_user_archived(recording, current_user, not get_user_archived(recording, current_user))+ return jsonify({'success': True, 'is_archived': new_value})+ except Exception as e:+ db.session.rollback()+ current_app.logger.error(f"Error toggling archive for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500+++@recordings_bp.route('/recording/<int:recording_id>/delete_audio', methods=['POST'])+@login_required+def delete_recording_audio(recording_id):+ """Delete a recording's media file and keep the transcript, summary and notes.++ Same permission as deleting the recording. The recording then shows as+ "Audio removed", exactly like audio-only retention leaves it.+ """+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to delete this recording'}), 403+ if not USERS_CAN_DELETE and not current_user.is_admin:+ return jsonify({'error': 'Only administrators can delete recordings'}), 403+ if recording.audio_deleted_at:+ return jsonify({'error': 'The audio has already been removed.'}), 409+ if recording.status not in ('COMPLETED', 'FAILED'):+ return jsonify({'error': 'Wait until processing has finished before removing the audio.'}), 409++ from src.services.retention import remove_recording_audio+ remove_recording_audio(recording)+ current_app.logger.info(f"User {current_user.id} removed the audio of recording {recording_id}")++ recording_dict = recording.to_dict(viewer_user=current_user)+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)+ return jsonify({'success': True, 'recording': recording_dict})+ except Exception as e:+ db.session.rollback()+ current_app.logger.error(f"Error removing audio for recording {recording_id}: {e}", exc_info=True)+ return jsonify({'error': 'An unexpected error occurred.'}), 500++@recordings_bp.route('/share-target', methods=['POST', 'GET'])@login_requireddef share_target():@@ -4577,14 +4648,14 @@ def bulk_toggle():return jsonify({'error': 'Missing request body'}), 400recording_ids = data.get('recording_ids', [])- field = data.get('field') # 'inbox' or 'highlight'+ field = data.get('field') # 'inbox', 'highlight' or 'archive'value = data.get('value') # True or Falseif not recording_ids or field is None or value is None:return jsonify({'error': 'Missing recording_ids, field, or value'}), 400- if field not in ['inbox', 'highlight']:- return jsonify({'error': 'Field must be "inbox" or "highlight"'}), 400+ if field not in ['inbox', 'highlight', 'archive']:+ return jsonify({'error': 'Field must be "inbox", "highlight" or "archive"'}), 400if len(recording_ids) > 100:return jsonify({'error': 'Cannot update more than 100 recordings at once'}), 400@@ -4609,6 +4680,9 @@ def bulk_toggle():# Use set_user_recording_status which handles both owners and shared usersif field == 'inbox':set_user_recording_status(recording, current_user, is_inbox=value)+ elif field == 'archive':+ from src.services.recording_state import set_user_archived+ set_user_archived(recording, current_user, value)else:set_user_recording_status(recording, current_user, is_highlighted=value)diff --git a/src/api/system.py b/src/api/system.pyindex e44eeb41..473fe674 100644--- a/src/api/system.py+++ b/src/api/system.py@@ -243,8 +243,9 @@ def get_config():except:pass # If not authenticated, use default- # Calculate if archive toggle should be shown (only when audio-only deletion mode is active)- enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'+ # The "Audio removed" filter matters when retention removes audio, or+ # when the user can remove audio by hand (same right as deleting).+ enable_audio_removed_filter = (ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only') or can_delete# Get connector capabilities (new architecture)# Defaults to USE_ASR_ENDPOINT for backwards compatibility@@ -302,7 +303,7 @@ def get_config():'connector_supports_hotwords': connector_supports_hotwords,'connector_supports_initial_prompt': connector_supports_initial_prompt,'enable_internal_sharing': ENABLE_INTERNAL_SHARING,- 'enable_archive_toggle': enable_archive_toggle,+ 'enable_audio_removed_filter': enable_audio_removed_filter,'show_usernames_in_ui': SHOW_USERNAMES_IN_UI,'can_delete_recordings': can_delete,'users_can_delete_enabled': USERS_CAN_DELETE,diff --git a/src/app.py b/src/app.pyindex 27e23e75..4aa1d02a 100644--- a/src/app.py+++ b/src/app.py@@ -351,6 +351,8 @@ def enrich_recording_dict_with_user_status(recording_dict, recording, user):user_inbox, user_highlighted = get_user_recording_status(recording, user)recording_dict['is_inbox'] = user_inboxrecording_dict['is_highlighted'] = user_highlighted+ from src.services.recording_state import get_user_archived+ recording_dict['is_archived'] = get_user_archived(recording, user)return recording_dictdiff --git a/src/init_db.py b/src/init_db.pyindex f5e796ff..1a6ef183 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -440,6 +440,13 @@ def _run_migrations(app, engine):if add_column_if_not_exists(engine, 'folder', 'default_initial_prompt', 'TEXT'):app.logger.info("Added default_initial_prompt column to folder table")+ # Archive hides a recording from the main list without deleting+ # anything. Per user, like inbox and star (#394).+ if add_column_if_not_exists(engine, 'recording', 'is_archived', 'BOOLEAN DEFAULT 0'):+ app.logger.info("Added is_archived column to recording table")+ if add_column_if_not_exists(engine, 'shared_recording_state', 'is_archived', 'BOOLEAN DEFAULT 0'):+ app.logger.info("Added is_archived column to shared_recording_state table")+# Configurable AI title instructions at every level (#400)for table in ('user', 'tag', 'folder'):if add_column_if_not_exists(engine, table, 'title_prompt', 'TEXT'):diff --git a/src/models/recording.py b/src/models/recording.pyindex 2f2533d8..6bf1be6e 100644--- a/src/models/recording.py+++ b/src/models/recording.py@@ -40,6 +40,7 @@ class Recording(db.Model):original_filename = db.Column(db.String(500), nullable=True) # Store the original uploaded filenameis_inbox = db.Column(db.Boolean, default=True) # New recordings are marked as inbox by defaultis_highlighted = db.Column(db.Boolean, default=False) # Recordings can be highlighted by the user+ is_archived = db.Column(db.Boolean, default=False) # Hidden from the main list, nothing deleted (#394)mime_type = db.Column(db.String(100), nullable=True)audio_duration_seconds = db.Column(db.Float, nullable=True) # Cached audio duration to avoid materializing remote storage during serializationcompleted_at = db.Column(db.DateTime, nullable=True)@@ -364,6 +365,7 @@ class Recording(db.Model):'mime_type': self.mime_type, # cheap column read; lets the sidebar mark video recordings without opening them'is_inbox': self.is_inbox,'is_highlighted': self.is_highlighted,+ 'is_archived': bool(self.is_archived),'audio_deleted_at': self.audio_deleted_at.isoformat() if self.audio_deleted_at else None,'audio_available': self.audio_deleted_at is None,# True only when a playable audio file actually exists yet. A merge@@ -449,6 +451,7 @@ class Recording(db.Model):'user_id': self.user_id,'is_inbox': self.is_inbox,'is_highlighted': self.is_highlighted,+ 'is_archived': bool(self.is_archived),'mime_type': self.mime_type,'audio_deleted_at': self.audio_deleted_at.isoformat() if self.audio_deleted_at else None,'audio_available': self.audio_deleted_at is None,diff --git a/src/models/sharing.py b/src/models/sharing.pyindex 9c986b1e..b8d34353 100644--- a/src/models/sharing.py+++ b/src/models/sharing.py@@ -211,6 +211,7 @@ class SharedRecordingState(db.Model):personal_notes = db.Column(db.Text, nullable=True) # Private notes only this user can seeis_inbox = db.Column(db.Boolean, default=True) # User's personal inbox statusis_highlighted = db.Column(db.Boolean, default=False) # User's personal highlight/favorite status+ is_archived = db.Column(db.Boolean, default=False) # User's personal archive status (#394)last_viewed = db.Column(db.DateTime, default=datetime.utcnow)created_at = db.Column(db.DateTime, default=datetime.utcnow)diff --git a/src/services/recording_state.py b/src/services/recording_state.pynew file mode 100644index 00000000..12e25c11--- /dev/null+++ b/src/services/recording_state.py@@ -0,0 +1,55 @@+"""Per-user archive state (#394).++Archive works like inbox and star: the owner's value lives on the recording,+and each user a recording is shared with keeps their own value on their+SharedRecordingState row, so archiving a shared recording never hides it for+anyone else.+"""++from sqlalchemy import select++from src.database import db+from src.models.sharing import SharedRecordingState+++def _state(recording, user):+ return SharedRecordingState.query.filter_by(recording_id=recording.id, user_id=user.id).first()+++def get_user_archived(recording, user):+ if recording.user_id == user.id:+ return bool(recording.is_archived)+ state = _state(recording, user)+ return bool(state and state.is_archived)+++def set_user_archived(recording, user, value):+ value = bool(value)+ if recording.user_id == user.id:+ recording.is_archived = value+ else:+ state = _state(recording, user)+ if not state:+ state = SharedRecordingState(recording_id=recording.id, user_id=user.id,+ is_inbox=True, is_highlighted=False)+ db.session.add(state)+ state.is_archived = value+ db.session.commit()+ return value+++def archived_condition(recording_model, user_id):+ """SQL condition: the recording is archived for this user.++ NULL counts as not archived, so rows written before the column existed+ can never disappear from the list.+ """+ shared_archived = select(SharedRecordingState.recording_id).where(+ db.and_(SharedRecordingState.user_id == user_id,+ db.func.coalesce(SharedRecordingState.is_archived, False) == True) # noqa: E712+ ).scalar_subquery()+ return db.or_(+ db.and_(recording_model.user_id == user_id,+ db.func.coalesce(recording_model.is_archived, False) == True), # noqa: E712+ recording_model.id.in_(shared_archived),+ )diff --git a/src/services/retention.py b/src/services/retention.pyindex 21ac17c9..b2ae982d 100644--- a/src/services/retention.py+++ b/src/services/retention.py@@ -154,20 +154,9 @@ def process_auto_deletion():# Determine deletion modeif DELETION_MODE == 'audio_only':# Delete only the audio file, keep transcription- storage = get_storage_service()- if recording.audio_path and storage.exists(recording.audio_path):- current_app.logger.info(f"Recording {recording.id} is past retention ({retention_days} days), deleting audio")- storage.delete(recording.audio_path, missing_ok=True)- current_app.logger.info(f"Auto-deleted audio file: {recording.audio_path}")- recording.audio_deleted_at = datetime.utcnow()- db.session.commit()+ current_app.logger.info(f"Recording {recording.id} is past retention ({retention_days} days), removing audio")+ if remove_recording_audio(recording):stats['deleted_audio_only'] += 1- else:- # Audio already deleted or doesn't exist - just mark timestamp- if not recording.audio_deleted_at:- recording.audio_deleted_at = datetime.utcnow()- db.session.commit()- current_app.logger.debug(f"Recording {recording.id} audio file not found, marked as deleted")else: # full_recording mode# Check if this is completing a previous audio_only deletion@@ -221,3 +210,23 @@ def process_auto_deletion():# Use environment variables from .env+def remove_recording_audio(recording):+ """Delete a recording's media file and keep everything else.++ The transcript, summary, notes, tags and shares stay; the recording shows+ as "Audio removed" and can no longer be played or reprocessed. Used by+ audio-only retention and by the manual "Delete audio" action.++ Returns True when a stored file was deleted, False when there was none+ (the recording is marked either way). Commits.+ """+ storage = get_storage_service()+ deleted = False+ if recording.audio_path and storage.exists(recording.audio_path):+ storage.delete(recording.audio_path, missing_ok=True)+ current_app.logger.info(f"Removed audio file for recording {recording.id}: {recording.audio_path}")+ deleted = True+ if not recording.audio_deleted_at:+ recording.audio_deleted_at = datetime.utcnow()+ db.session.commit()+ return deleteddiff --git a/tests/test_archive_and_audio_removal.py b/tests/test_archive_and_audio_removal.pynew file mode 100644index 00000000..473d4254--- /dev/null+++ b/tests/test_archive_and_audio_removal.py@@ -0,0 +1,256 @@+"""Archive (#394) and manual audio removal.++Archive hides a recording from the main list without deleting anything, per+user like inbox and star. Search still finds archived recordings. "Delete+audio" removes only the media file and leaves the recording in the same+"Audio removed" state that audio-only retention produces.++SHARED-DB: assertions are scoped to the recordings each test creates.+"""++import json+import os+import sys+import uuid+from unittest.mock import patch, MagicMock++import pytest+from flask import g+from flask.testing import FlaskClient++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+from src.models.sharing import InternalShare, SharedRecordingState++app.config["WTF_CSRF_ENABLED"] = False+++_created = []+++def ctx():+ """App context, and removal of every recording the test created: later+ files (test_cov_admin) assume no eligible completed recordings exist."""+ with app.app_context():+ yield+ db.session.rollback()+ for rec_id in _created:+ InternalShare.query.filter_by(recording_id=rec_id).delete()+ SharedRecordingState.query.filter_by(recording_id=rec_id).delete()+ Recording.query.filter_by(id=rec_id).delete()+ db.session.commit()+ _created.clear()+++def _user():+ suffix = uuid.uuid4().hex[:8]+ u = User(username=f"ar_{suffix}", email=f"ar_{suffix}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ return u+++def _rec(user, title=None, status="COMPLETED"):+ r = Recording(user_id=user.id, title=title or f"arch_{uuid.uuid4().hex[:10]}", status=status,+ audio_path="local://recordings/x.mp3", original_filename="x.mp3",+ transcription=json.dumps([{"speaker": "A", "sentence": "hello", "start_time": 0, "end_time": 1}]),+ summary="A summary")+ db.session.add(r)+ db.session.commit()+ _created.append(r.id)+ return r+++class _Client(FlaskClient):+ """Each test holds one app context open across requests, and Flask-Login+ caches the loaded user on g for that context. Clear it so a request from+ one user's client never runs as the user of an earlier request."""++ def open(self, *args, **kwargs):+ g.pop('_login_user', None)+ return super().open(*args, **kwargs)+++def _client(user):+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(user.id)+ sess["_fresh"] = True+ return c+++def _ids(client, **params):+ params.setdefault('per_page', 100)+ body = client.get('/api/recordings', query_string=params).get_json()+ return {r['id'] for r in body['recordings']}+++def _share(rec, owner, other):+ db.session.add(InternalShare(recording_id=rec.id, owner_id=owner.id, shared_with_user_id=other.id))+ db.session.commit()+++# --------------------------------------------------------------------- archive++def test_archived_recordings_leave_the_main_list_and_come_back(ctx):+ user = _user()+ kept, archived = _rec(user), _rec(user)+ c = _client(user)+ r = c.post(f'/recording/{archived.id}/toggle_archive')+ assert r.get_json()['is_archived'] is True++ assert kept.id in _ids(c) and archived.id not in _ids(c)+ assert _ids(c, archived='true') & {kept.id, archived.id} == {archived.id}++ c.post(f'/recording/{archived.id}/toggle_archive')+ assert archived.id in _ids(c)+++def test_search_still_finds_archived_recordings(ctx):+ user = _user()+ rec = _rec(user, title=f"Quarterly zebra review {uuid.uuid4().hex[:6]}")+ c = _client(user)+ c.post(f'/recording/{rec.id}/toggle_archive')+ assert rec.id in _ids(c, q=rec.title)+++def test_rows_with_null_archive_flag_stay_visible(ctx):+ user = _user()+ rec = _rec(user)+ db.session.execute(db.text("UPDATE recording SET is_archived = NULL WHERE id = :id"), {"id": rec.id})+ db.session.commit()+ assert rec.id in _ids(_client(user))+++def test_archiving_a_shared_recording_is_personal(ctx):+ owner, other = _user(), _user()+ rec = _rec(owner)+ _share(rec, owner, other)+ other_client = _client(other)+ assert other_client.post(f'/recording/{rec.id}/toggle_archive').get_json()['is_archived'] is True+ assert rec.id not in _ids(other_client)+ assert rec.id in _ids(other_client, archived='true')+ # The owner's list is unaffected.+ assert rec.id in _ids(_client(owner))+ db.session.expire_all()+ assert not db.session.get(Recording, rec.id).is_archived+++def test_archive_needs_access(ctx):+ owner, stranger = _user(), _user()+ rec = _rec(owner)+ assert _client(stranger).post(f'/recording/{rec.id}/toggle_archive').status_code == 403+ assert SharedRecordingState.query.filter_by(recording_id=rec.id, user_id=stranger.id).count() == 0+++def test_bulk_archive_and_save_field(ctx):+ user = _user()+ a, b = _rec(user), _rec(user)+ c = _client(user)+ r = c.post('/api/recordings/bulk-toggle', json={'recording_ids': [a.id, b.id], 'field': 'archive', 'value': True})+ assert r.status_code == 200 and set(r.get_json()['affected_ids']) == {a.id, b.id}+ assert not ({a.id, b.id} & _ids(c))+ c.post(f'/save', json={'id': a.id, 'is_archived': False})+ assert a.id in _ids(c)+++def test_recording_payloads_carry_the_flag(ctx):+ user = _user()+ rec = _rec(user)+ c = _client(user)+ c.post(f'/recording/{rec.id}/toggle_archive')+ body = c.get('/api/recordings', query_string={'archived': 'true', 'per_page': 100}).get_json()+ row = next(r for r in body['recordings'] if r['id'] == rec.id)+ assert row['is_archived'] is True+++# ----------------------------------------------------------------- audio removal++def _fake_storage():+ storage = MagicMock()+ storage.exists.return_value = True+ return storage+++def test_delete_audio_keeps_the_recording(ctx):+ user = _user()+ rec = _rec(user)+ storage = _fake_storage()+ with patch("src.services.retention.get_storage_service", return_value=storage):+ r = _client(user).post(f'/recording/{rec.id}/delete_audio')+ assert r.status_code == 200, r.get_data(as_text=True)+ storage.delete.assert_called_once_with("local://recordings/x.mp3", missing_ok=True)+ db.session.expire_all()+ saved = db.session.get(Recording, rec.id)+ assert saved.audio_deleted_at is not None+ assert saved.summary == "A summary" and "hello" in saved.transcription+ assert r.get_json()['recording']['audio_deleted_at']+++def test_delete_audio_refusals(ctx):+ owner, other = _user(), _user()+ done, busy = _rec(owner), _rec(owner, status="PROCESSING")+ storage = _fake_storage()+ with patch("src.services.retention.get_storage_service", return_value=storage):+ assert _client(other).post(f'/recording/{done.id}/delete_audio').status_code == 403+ assert _client(owner).post(f'/recording/{busy.id}/delete_audio').status_code == 409+ assert _client(owner).post(f'/recording/{done.id}/delete_audio').status_code == 200+ assert _client(owner).post(f'/recording/{done.id}/delete_audio').status_code == 409+ with patch("src.api.recordings.USERS_CAN_DELETE", False):+ assert _client(owner).post(f'/recording/{busy.id}/delete_audio').status_code == 403+ storage.delete.assert_called_once()+++def test_audio_removed_filter(ctx):+ user = _user()+ kept, removed = _rec(user), _rec(user)+ with patch("src.services.retention.get_storage_service", return_value=_fake_storage()):+ _client(user).post(f'/recording/{removed.id}/delete_audio')+ c = _client(user)+ assert _ids(c, audio_removed='true') & {kept.id, removed.id} == {removed.id}+ # Removing audio does not archive: the recording stays in the main list.+ assert removed.id in _ids(c)+++def test_retention_audio_only_path_uses_the_shared_helper(ctx):+ from src.services import retention+ user = _user()+ rec = _rec(user)+ storage = _fake_storage()+ with patch("src.services.retention.get_storage_service", return_value=storage):+ assert retention.remove_recording_audio(rec) is True+ assert rec.audio_deleted_at is not None+ storage.exists.return_value = False+ with patch("src.services.retention.get_storage_service", return_value=storage):+ assert retention.remove_recording_audio(rec) is False+++# -------------------------------------------------------------------- API v1++def _token_client(user):+ from src.models import APIToken+ from src.utils.token_auth import hash_token+ raw = f"tok_{uuid.uuid4().hex}"+ db.session.add(APIToken(user_id=user.id, token_hash=hash_token(raw), name="t"))+ db.session.commit()+ return app.test_client(), {"Authorization": f"Bearer {raw}"}+++def test_api_v1_archive_and_delete_audio(ctx):+ user = _user()+ rec = _rec(user)+ c, h = _token_client(user)+ r = c.patch(f'/api/v1/recordings/{rec.id}', json={'is_archived': True}, headers=h)+ assert r.status_code == 200, r.get_data(as_text=True)+ listed = c.get('/api/v1/recordings', query_string={'archived': 'true', 'per_page': 100}, headers=h).get_json()+ rows = listed.get('recordings', listed.get('data', []))+ assert any(row['id'] == rec.id and row['is_archived'] for row in rows)+ unarchived = c.get('/api/v1/recordings', query_string={'archived': 'false', 'per_page': 100}, headers=h).get_json()+ assert all(row['id'] != rec.id for row in unarchived.get('recordings', unarchived.get('data', [])))++ with patch("src.services.retention.get_storage_service", return_value=_fake_storage()):+ r = c.post(f'/api/v1/recordings/{rec.id}/delete-audio', headers=h)+ assert r.status_code == 200 and r.get_json()['audio_deleted_at']