Skip to content

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

Python

Paginated recording list in a fixed number of statements per page: share counts, duplicates, per-user state, edit rights, owners, tag visibility and tag/folder counts read once for the page; same for the inbox, audio-removed and shared-with-me lists and the v1 list tags (D#483)

Murtaza Nasireb7360fc2519
diff --git a/src/api/recordings.py b/src/api/recordings.py
index f54c38e9..d4bd7cdd 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -178,6 +178,7 @@ def reindex_recording_chunks_async(recording_id):
# Global helpers (will be injected from app)
has_recording_access = None
+editable_recording_ids = None
get_user_recording_status = None
set_user_recording_status = None
enrich_recording_dict_with_user_status = None
@@ -188,8 +189,9 @@ chunking_service = None
def init_recordings_helpers(**kwargs):
"""Initialize helper functions and extensions from app."""
- global has_recording_access, get_user_recording_status, set_user_recording_status, enrich_recording_dict_with_user_status, bcrypt, csrf, limiter, chunking_service
+ global has_recording_access, editable_recording_ids, get_user_recording_status, set_user_recording_status, enrich_recording_dict_with_user_status, bcrypt, csrf, limiter, chunking_service
has_recording_access = kwargs.get('has_recording_access')
+ editable_recording_ids = kwargs.get('editable_recording_ids')
get_user_recording_status = kwargs.get('get_user_recording_status')
set_user_recording_status = kwargs.get('set_user_recording_status')
enrich_recording_dict_with_user_status = kwargs.get('enrich_recording_dict_with_user_status')
@@ -1760,8 +1762,10 @@ def get_recordings_paginated():
offset = (page - 1) * per_page
stmt = stmt.offset(offset).limit(per_page)
- # Execute query
- recordings = db.session.execute(stmt).scalars().all()
+ # Execute query. Tags, folders and their names load for the whole
+ # page, and the long text columns the list never shows stay behind (D#483).
+ from src.services.recording_list import RecordingListBatch, list_load_options
+ recordings = db.session.execute(stmt.options(*list_load_options())).scalars().all()
# Batch-load this viewer's shares for the page so serialization can resolve
# the #314 share-reason tag/folder without an N+1 query.
@@ -1774,31 +1778,35 @@ def get_recordings_paginated():
).all():
share_map[s.recording_id] = s
+ # What the rows need beyond their own columns, read once for the page
+ # rather than per row (D#483)
+ batch = RecordingListBatch(recordings, current_user, share_map)
+ editable_ids = editable_recording_ids(recordings, current_user, share_map)
+
# Enrich recordings with sharing metadata
enriched_recordings = []
for recording in recordings:
- rec_dict = recording.to_list_dict(viewer_user=current_user, share_map=share_map)
+ rec_dict = recording.to_list_dict(viewer_user=current_user, share_map=share_map, batch=batch)
# Add sharing metadata
is_owner = recording.user_id == current_user.id
rec_dict['is_owner'] = is_owner
# Get per-user status (owner uses Recording fields, recipients use SharedRecordingState)
- user_inbox, user_highlighted = get_user_recording_status(recording, current_user)
+ user_inbox, user_highlighted = batch.user_status(recording)
rec_dict['is_inbox'] = user_inbox
rec_dict['is_highlighted'] = user_highlighted
- from src.services.recording_state import get_user_archived
- rec_dict['is_archived'] = get_user_archived(recording, current_user)
+ rec_dict['is_archived'] = batch.user_archived(recording)
- # 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)
+ # Add edit permission info (has_recording_access rules, group admins included)
+ rec_dict['can_edit'] = recording.id in editable_ids
# Add delete permission info (only owner can delete)
rec_dict['can_delete'] = is_owner and (USERS_CAN_DELETE or current_user.is_admin)
if not is_owner:
# This is a shared recording - get owner info and share permissions
- owner = db.session.get(User, recording.user_id)
+ owner = batch.owners.get(recording.user_id)
rec_dict['owner_username'] = owner.username if owner else "Unknown"
rec_dict['is_shared'] = True
# Don't show outgoing share count for recordings you don't own
@@ -1826,8 +1834,7 @@ def get_recordings_paginated():
rec_dict['is_shared'] = False
# Check if recording has group tags (among visible tags)
- visible_tags = recording.get_visible_tags(current_user)
- has_group_tags = any(tag.is_group_tag for tag in visible_tags)
+ has_group_tags = any(tag.is_group_tag for tag in batch.visible_tags(recording))
rec_dict['has_group_tags'] = has_group_tags
enriched_recordings.append(rec_dict)
@@ -3393,8 +3400,11 @@ def get_inbox_recordings():
Recording.status.in_(['PENDING', 'PROCESSING', 'SUMMARIZING'])
).order_by(Recording.created_at.desc())
- recordings = db.session.execute(stmt).scalars().all()
- return jsonify([recording.to_list_dict(viewer_user=current_user) for recording in recordings])
+ # Page lookups read once, not per row (D#483)
+ from src.services.recording_list import RecordingListBatch, list_load_options
+ recordings = db.session.execute(stmt.options(*list_load_options())).scalars().all()
+ batch = RecordingListBatch(recordings, current_user)
+ return jsonify([recording.to_list_dict(viewer_user=current_user, batch=batch) for recording in recordings])
except Exception as e:
current_app.logger.error(f"Error fetching inbox recordings: {e}")
return jsonify({'error': str(e)}), 500
@@ -3420,8 +3430,11 @@ def get_archived_recordings():
Recording.audio_deleted_at.is_not(None)
).order_by(Recording.audio_deleted_at.desc())
- recordings = db.session.execute(stmt).scalars().all()
- return jsonify([recording.to_list_dict(viewer_user=current_user) for recording in recordings])
+ # Page lookups read once, not per row (D#483)
+ from src.services.recording_list import RecordingListBatch, list_load_options
+ recordings = db.session.execute(stmt.options(*list_load_options())).scalars().all()
+ batch = RecordingListBatch(recordings, current_user)
+ return jsonify([recording.to_list_dict(viewer_user=current_user, batch=batch) for recording in recordings])
except Exception as e:
current_app.logger.error(f"Error fetching archived recordings: {e}")
return jsonify({'error': str(e)}), 500
diff --git a/src/api/shares.py b/src/api/shares.py
index 76481689..ebaa704b 100644
--- a/src/api/shares.py
+++ b/src/api/shares.py
@@ -652,31 +652,39 @@ def get_shared_with_me():
return jsonify({'error': 'Internal sharing is not enabled'}), 403
try:
- # Get shares where current user is the recipient
- shares = InternalShare.query.filter_by(shared_with_user_id=current_user.id).all()
+ # Get shares where current user is the recipient, with their
+ # recordings and owners, and the rows' lookups read once (D#483)
+ from sqlalchemy.orm import selectinload
+ from src.services.recording_list import RecordingListBatch, list_load_options
+ shares = InternalShare.query.filter_by(shared_with_user_id=current_user.id).options(
+ selectinload(InternalShare.recording).options(*list_load_options()),
+ selectinload(InternalShare.owner),
+ ).all()
+ listed = [s for s in shares if s.recording and s.recording.status == 'COMPLETED']
+ batch = RecordingListBatch([s.recording for s in listed], current_user,
+ {s.recording_id: s for s in listed})
result = []
- for share in shares:
+ for share in listed:
recording = share.recording
- if recording and recording.status == 'COMPLETED':
- rec_data = recording.to_list_dict(viewer_user=current_user)
- # Mark as shared recording with owner info
- rec_data['is_shared'] = True
- rec_data['owner_username'] = share.owner.username if SHOW_USERNAMES_IN_UI else None
- # Don't show outgoing share counts for recordings you don't own
- rec_data['shared_with_count'] = 0
- rec_data['public_share_count'] = 0
- # Check if recording has group tags (among visible tags)
- visible_tags = recording.get_visible_tags(current_user)
- rec_data['has_group_tags'] = any(tag.is_group_tag for tag in visible_tags) if visible_tags else False
- rec_data['share_info'] = {
- 'share_id': share.id,
- 'owner_username': share.owner.username if SHOW_USERNAMES_IN_UI else None,
- 'can_edit': share.can_edit,
- 'can_reshare': share.can_reshare,
- 'shared_at': share.created_at.isoformat()
- }
- result.append(rec_data)
+ rec_data = recording.to_list_dict(viewer_user=current_user, batch=batch)
+ # Mark as shared recording with owner info
+ rec_data['is_shared'] = True
+ rec_data['owner_username'] = share.owner.username if SHOW_USERNAMES_IN_UI else None
+ # Don't show outgoing share counts for recordings you don't own
+ rec_data['shared_with_count'] = 0
+ rec_data['public_share_count'] = 0
+ # Check if recording has group tags (among visible tags)
+ visible_tags = batch.visible_tags(recording)
+ rec_data['has_group_tags'] = any(tag.is_group_tag for tag in visible_tags) if visible_tags else False
+ rec_data['share_info'] = {
+ 'share_id': share.id,
+ 'owner_username': share.owner.username if SHOW_USERNAMES_IN_UI else None,
+ 'can_edit': share.can_edit,
+ 'can_reshare': share.can_reshare,
+ 'shared_at': share.created_at.isoformat()
+ }
+ result.append(rec_data)
return jsonify(result)
diff --git a/src/app.py b/src/app.py
index 084ef732..8e76008b 100644
--- a/src/app.py
+++ b/src/app.py
@@ -245,6 +245,40 @@ def has_recording_access(recording, user, require_edit=False, require_reshare=Fa
return True
+def editable_recording_ids(recordings, user, share_map):
+ """has_recording_access(..., require_edit=True) for a page of recordings.
+
+ share_map is {recording_id: InternalShare} of the user's shares for these
+ recordings. Returns the ids the user may edit, with one query in all for
+ the group-admin rule instead of one per row (D#483).
+ """
+ editable = {r.id for r in recordings if r.user_id == user.id}
+ if not ENABLE_INTERNAL_SHARING:
+ return editable
+ needs_admin = []
+ for recording in recordings:
+ share = share_map.get(recording.id)
+ if recording.id in editable or not share:
+ continue
+ if share.can_edit:
+ editable.add(recording.id)
+ else:
+ needs_admin.append(recording.id)
+ if needs_admin:
+ editable.update(rid for (rid,) in db.session.query(RecordingTag.recording_id).join(
+ Tag, RecordingTag.tag_id == Tag.id
+ ).join(
+ GroupMembership, Tag.group_id == GroupMembership.group_id
+ ).filter(
+ RecordingTag.recording_id.in_(needs_admin),
+ GroupMembership.user_id == user.id,
+ GroupMembership.role == 'admin',
+ Tag.group_id.isnot(None),
+ db.or_(Tag.auto_share_on_apply == True, Tag.share_with_group_lead == True)
+ ).distinct())
+ return editable
+
+
def get_user_recording_status(recording, user):
"""
Get the inbox and highlighted status for a recording from a user's perspective.
@@ -990,7 +1024,7 @@ client, chunking_service, version = initialize_config(app)
init_auth_extensions(bcrypt, csrf, limiter)
init_tokens_helpers(bcrypt, csrf, limiter)
init_shares_helpers(has_recording_access)
-init_recordings_helpers(has_recording_access=has_recording_access, get_user_recording_status=get_user_recording_status, set_user_recording_status=set_user_recording_status, enrich_recording_dict_with_user_status=enrich_recording_dict_with_user_status, bcrypt=bcrypt, csrf=csrf, limiter=limiter, chunking_service=chunking_service)
+init_recordings_helpers(has_recording_access=has_recording_access, editable_recording_ids=editable_recording_ids, get_user_recording_status=get_user_recording_status, set_user_recording_status=set_user_recording_status, enrich_recording_dict_with_user_status=enrich_recording_dict_with_user_status, bcrypt=bcrypt, csrf=csrf, limiter=limiter, chunking_service=chunking_service)
init_tags_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
init_folders_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
init_groups_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
diff --git a/src/models/organization.py b/src/models/organization.py
index 0fd00bca..99c3cc3f 100644
--- a/src/models/organization.py
+++ b/src/models/organization.py
@@ -134,8 +134,14 @@ class Folder(db.Model):
"""Check if this is a group-scoped folder."""
return self.group_id is not None
- def to_dict(self):
- """Convert model to dictionary representation."""
+ def to_dict(self, recording_count=None):
+ """Convert model to dictionary representation.
+
+ recording_count: the folder's recording count when the caller has
+ counted it already (list pages count all their folders at once).
+ """
+ if recording_count is None:
+ recording_count = len(self.recordings) if self.recordings else 0
return {
'id': self.id,
'name': self.name,
@@ -160,7 +166,7 @@ class Folder(db.Model):
'export_template_id': self.export_template_id,
'export_template_name': self.export_template.name if self.export_template else None,
'created_at': self.created_at.isoformat() if self.created_at else None,
- 'recording_count': len(self.recordings) if self.recordings else 0
+ 'recording_count': recording_count
}
@@ -222,8 +228,14 @@ class Tag(db.Model):
"""Check if this is a group-scoped tag."""
return self.group_id is not None
- def to_dict(self):
- """Convert model to dictionary representation."""
+ def to_dict(self, recording_count=None):
+ """Convert model to dictionary representation.
+
+ recording_count: the tag's recording count when the caller has
+ counted it already (list pages count all their tags at once).
+ """
+ if recording_count is None:
+ recording_count = len(self.recording_associations)
return {
'id': self.id,
'name': self.name,
@@ -250,5 +262,5 @@ class Tag(db.Model):
'is_auto_process': self.is_auto_process or False,
'auto_process_folder_name': self.auto_process_folder_name,
'created_at': self.created_at.isoformat() if self.created_at else None,
- 'recording_count': len(self.recording_associations)
+ 'recording_count': recording_count
}
diff --git a/src/models/recording.py b/src/models/recording.py
index 37d76bb7..76de9c1f 100644
--- a/src/models/recording.py
+++ b/src/models/recording.py
@@ -116,7 +116,7 @@ class Recording(db.Model):
"""Get tags ordered by the order they were added to this recording."""
return [assoc.tag for assoc in sorted(self.tag_associations, key=lambda x: x.order)]
- def get_visible_tags(self, viewer_user):
+ def get_visible_tags(self, viewer_user, member_group_ids=None):
"""
Get tags that are visible to a specific user viewing this recording.
@@ -129,6 +129,9 @@ class Recording(db.Model):
Args:
viewer_user: User object viewing the recording (or None for backward compatibility)
+ member_group_ids: optional set of the viewer's group ids, when a list
+ has read them once for its page (see group_ids_of); otherwise
+ each group tag costs one membership query
Returns:
List of Tag objects visible to the viewer
@@ -147,10 +150,13 @@ class Recording(db.Model):
for tag in self.tags:
# Group tags: visible if viewer is a member of the group
if tag.group_id:
- membership = GroupMembership.query.filter_by(
- group_id=tag.group_id,
- user_id=viewer_user.id
- ).first()
+ if member_group_ids is not None:
+ membership = tag.group_id in member_group_ids
+ else:
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=viewer_user.id
+ ).first()
if membership:
visible_tags.append(tag)
# Personal tags: visible only to tag creator
@@ -307,7 +313,7 @@ class Recording(db.Model):
}
return None
- def _serialize_tags_and_folder(self, viewer_user, share_map=None):
+ def _serialize_tags_and_folder(self, viewer_user, share_map=None, batch=None):
"""Build (tags, folder, folder_id) for a viewer, applying #314 rules.
For a recording the viewer does NOT own, only the tag/folder that GRANTED
@@ -318,13 +324,20 @@ class Recording(db.Model):
share_map: optional {recording_id: InternalShare} to avoid an N+1 query
in list views; falls back to a per-recording lookup when not provided.
+ batch: optional RecordingListBatch with the page's visible tags and
+ tag/folder counts (D#483).
"""
- visible_tags = self.get_visible_tags(viewer_user)
+ if batch is not None:
+ visible_tags = batch.visible_tags(self)
+ tag_dict, folder_dict = batch.tag_dict, batch.folder_dict
+ else:
+ visible_tags = self.get_visible_tags(viewer_user)
+ tag_dict, folder_dict = (lambda tag: tag.to_dict()), (lambda folder: folder.to_dict())
is_foreign = viewer_user is not None and self.user_id != viewer_user.id
if not is_foreign:
- tags = [tag.to_dict() for tag in visible_tags] if visible_tags else []
- folder = self.folder.to_dict() if self.folder else None
+ tags = [tag_dict(tag) for tag in visible_tags] if visible_tags else []
+ folder = folder_dict(self.folder) if self.folder else None
return tags, folder, self.folder_id
from src.models.sharing import InternalShare
@@ -341,11 +354,11 @@ class Recording(db.Model):
if reason_tag_id:
for tag in visible_tags:
if tag.id == reason_tag_id:
- td = tag.to_dict()
+ td = tag_dict(tag)
td['is_foreign'] = True
tags.append(td)
if reason_folder_id and self.folder_id == reason_folder_id and self.folder:
- folder = self.folder.to_dict()
+ folder = folder_dict(self.folder)
folder['is_foreign'] = True
return tags, folder, self.folder_id
return tags, None, None
@@ -355,7 +368,7 @@ class Recording(db.Model):
value = self.updated_at or self.created_at
return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') if value else None
- def to_list_dict(self, viewer_user=None, duplicate_info_map=None, share_map=None):
+ def to_list_dict(self, viewer_user=None, duplicate_info_map=None, share_map=None, batch=None):
"""
Lightweight dict for list views - excludes expensive HTML conversions.
@@ -363,21 +376,33 @@ class Recording(db.Model):
viewer_user: User viewing the recording (for tag visibility filtering)
share_map: optional {recording_id: InternalShare} for #314 share-reason
resolution without an N+1 query.
+ batch: optional RecordingListBatch (src/services/recording_list.py)
+ built for viewer_user over the page: share counts, duplicates,
+ visible tags and tag/folder counts come from it instead of
+ per-row queries (D#483).
"""
# Import here to avoid circular dependencies
from src.models.sharing import InternalShare, Share
- # Count internal shares for this recording
- shared_with_count = db.session.query(func.count(InternalShare.id)).filter(
- InternalShare.recording_id == self.id
- ).scalar() or 0
+ if batch is not None:
+ shared_with_count = batch.shared_with_counts.get(self.id, 0)
+ public_share_count = batch.public_share_counts.get(self.id, 0)
+ duplicate_info = batch.duplicate_info(self)
+ if share_map is None:
+ share_map = batch.share_map
+ else:
+ # Count internal shares for this recording
+ shared_with_count = db.session.query(func.count(InternalShare.id)).filter(
+ InternalShare.recording_id == self.id
+ ).scalar() or 0
- # Count public shares (link shares) for this recording
- public_share_count = db.session.query(func.count(Share.id)).filter(
- Share.recording_id == self.id
- ).scalar() or 0
+ # Count public shares (link shares) for this recording
+ public_share_count = db.session.query(func.count(Share.id)).filter(
+ Share.recording_id == self.id
+ ).scalar() or 0
+ duplicate_info = self._dup_from_map_or_query(duplicate_info_map)
- tags_ser, folder_ser, folder_id_ser = self._serialize_tags_and_folder(viewer_user, share_map)
+ tags_ser, folder_ser, folder_id_ser = self._serialize_tags_and_folder(viewer_user, share_map, batch)
return {
'id': self.id,
@@ -408,7 +433,7 @@ class Recording(db.Model):
'folder_id': folder_id_ser,
'folder': folder_ser,
'tags': tags_ser,
- 'duplicate_info': self._dup_from_map_or_query(duplicate_info_map),
+ 'duplicate_info': duplicate_info,
'shared_with_count': shared_with_count,
'public_share_count': public_share_count,
'audio_duration': self.get_audio_duration(),
diff --git a/src/services/recording_list.py b/src/services/recording_list.py
new file mode 100644
index 00000000..e7b65fcd
--- /dev/null
+++ b/src/services/recording_list.py
@@ -0,0 +1,156 @@
+"""Page-scoped lookups for the recording lists (D#483).
+
+Serializing a page one row at a time cost several queries per row: the two
+share counts, the duplicate copies, the viewer's inbox/star/archive state,
+tag visibility, and the tag and folder recording counts. RecordingListBatch
+reads each of them once for the page. Recording.to_list_dict takes it as
+``batch``; without one it keeps its per-row queries, which single-row
+callers still use, so both paths must give the same payload.
+"""
+
+from sqlalchemy import func
+from sqlalchemy.orm import defer, joinedload, selectinload
+
+from src.database import db
+from src.models import (
+ Folder, GroupMembership, InternalShare, Recording, RecordingTag, Share, SharedRecordingState, Tag, User,
+)
+
+# Long columns the list payload never reads. Nothing on the list path may
+# touch them: a deferred column read later costs one query per row.
+_LIST_DEFERRED = (
+ Recording.transcription, Recording.summary, Recording.error_message, Recording.speaker_embeddings,
+ Recording.speaker_label_map, Recording.prompt_variables, Recording.resolved_hotwords,
+ Recording.resolved_initial_prompt,
+)
+
+
+def list_load_options():
+ """Loader options for a page query whose rows go through to_list_dict."""
+ names = (joinedload(Tag.group), joinedload(Tag.naming_template), joinedload(Tag.export_template))
+ folder_names = (joinedload(Folder.group), joinedload(Folder.naming_template),
+ joinedload(Folder.export_template))
+ return [
+ selectinload(Recording.tag_associations).joinedload(RecordingTag.tag).options(*names),
+ selectinload(Recording.folder).options(*folder_names),
+ *(defer(column) for column in _LIST_DEFERRED),
+ ]
+
+
+def group_ids_of(viewer, recordings):
+ """The viewer's groups among those of the recordings' group tags, in one query."""
+ group_ids = sorted({t.group_id for r in recordings for t in r.tags if t.group_id})
+ if not group_ids:
+ return set()
+ return {gid for (gid,) in db.session.query(GroupMembership.group_id).filter(
+ GroupMembership.user_id == viewer.id, GroupMembership.group_id.in_(group_ids))}
+
+
+def _counts(column, ids):
+ if not ids:
+ return {}
+ rows = db.session.query(column, func.count()).filter(column.in_(ids)).group_by(column)
+ return {key: count for key, count in rows}
+
+
+class RecordingListBatch:
+ """The lookups for one page of recordings seen by one viewer.
+
+ share_map is {recording_id: InternalShare} of the viewer's shares for the
+ page, when the caller has already read it.
+ """
+
+ def __init__(self, recordings, viewer, share_map=None):
+ self.viewer = viewer
+ ids = [r.id for r in recordings]
+ foreign = [r for r in recordings if r.user_id != viewer.id]
+ foreign_ids = [r.id for r in foreign]
+
+ if share_map is None:
+ share_map = {}
+ if foreign_ids:
+ share_map = {s.recording_id: s for s in InternalShare.query.filter(
+ InternalShare.recording_id.in_(foreign_ids),
+ InternalShare.shared_with_user_id == viewer.id)}
+ self.share_map = share_map
+
+ self.shared_with_counts = _counts(InternalShare.recording_id, ids)
+ self.public_share_counts = _counts(Share.recording_id, ids)
+
+ self.states = {}
+ if foreign_ids:
+ self.states = {s.recording_id: s for s in SharedRecordingState.query.filter(
+ SharedRecordingState.recording_id.in_(foreign_ids),
+ SharedRecordingState.user_id == viewer.id)}
+ owner_ids = sorted({r.user_id for r in foreign if r.user_id is not None})
+ self.owners = {u.id: u for u in User.query.filter(User.id.in_(owner_ids))} if owner_ids else {}
+
+ self._duplicates = self._load_duplicates(recordings)
+
+ member_group_ids = group_ids_of(viewer, recordings)
+ self._visible = {r.id: r.get_visible_tags(viewer, member_group_ids) for r in recordings}
+
+ self.tag_counts = _counts(RecordingTag.tag_id,
+ sorted({t.id for tags in self._visible.values() for t in tags}))
+ self.folder_counts = _counts(Recording.folder_id,
+ sorted({r.folder_id for r in recordings if r.folder_id is not None}))
+
+ def _load_duplicates(self, recordings):
+ # Scoped to each row's owner, as Recording.get_duplicate_info is, so a
+ # shared row lists its owner's copies and never the viewer's.
+ pairs = {(r.user_id, r.file_hash) for r in recordings if r.file_hash and r.user_id is not None}
+ if not pairs:
+ return {}
+ rows = db.session.query(Recording.id, Recording.title, Recording.created_at, Recording.user_id,
+ Recording.file_hash).filter(
+ Recording.user_id.in_(sorted({u for u, _ in pairs})),
+ Recording.file_hash.in_(sorted({h for _, h in pairs})),
+ ).order_by(Recording.created_at, Recording.id)
+ copies = {}
+ for rid, title, created_at, user_id, file_hash in rows:
+ if (user_id, file_hash) in pairs:
+ copies.setdefault((user_id, file_hash), []).append((rid, title, created_at))
+ return copies
+
+ def duplicate_info(self, recording):
+ """Recording.get_duplicate_info for a row of the page."""
+ if not recording.file_hash:
+ return None
+ dupes = self._duplicates.get((recording.user_id, recording.file_hash), [])
+ if len(dupes) <= 1:
+ return None
+ return {
+ 'total_copies': len(dupes),
+ 'copies': [
+ {
+ 'id': rid,
+ 'title': title or f'#{rid}',
+ 'created_at': created_at.isoformat() if created_at else None,
+ 'is_self': rid == recording.id,
+ }
+ for rid, title, created_at in dupes
+ ],
+ }
+
+ def visible_tags(self, recording):
+ return self._visible[recording.id]
+
+ def tag_dict(self, tag):
+ return tag.to_dict(recording_count=self.tag_counts.get(tag.id, 0))
+
+ def folder_dict(self, folder):
+ return folder.to_dict(recording_count=self.folder_counts.get(folder.id, 0))
+
+ def user_status(self, recording):
+ """get_user_recording_status for the viewer: (is_inbox, is_highlighted)."""
+ if recording.user_id == self.viewer.id:
+ return (recording.is_inbox, recording.is_highlighted)
+ state = self.states.get(recording.id)
+ return (state.is_inbox, state.is_highlighted) if state else (True, False)
+
+ def user_archived(self, recording):
+ """get_user_archived for the viewer."""
+ if recording.user_id == self.viewer.id:
+ return bool(recording.is_archived)
+ state = self.states.get(recording.id)
+ return bool(state and state.is_archived)
diff --git a/src/services/recording_scope.py b/src/services/recording_scope.py
index da7beb27..524cb66c 100644
--- a/src/services/recording_scope.py
+++ b/src/services/recording_scope.py
@@ -67,6 +67,9 @@ def share_details(recordings, user):
states = {s.recording_id: s for s in SharedRecordingState.query.filter(
SharedRecordingState.recording_id.in_(shared_ids), SharedRecordingState.user_id == user.id)}
owners = {u.id: u for u in User.query.filter(User.id.in_({r.user_id for r in recordings if r.id in shares}))}
+ # Group memberships once for the page, not one query per group tag (D#483)
+ from src.services.recording_list import group_ids_of
+ member_group_ids = group_ids_of(user, [r for r in recordings if r.id in shares])
show = _show_usernames()
details = {}
for r in recordings:
@@ -86,7 +89,8 @@ def share_details(recordings, user):
'is_inbox': bool(state.is_inbox) if state and state.is_inbox is not None else True,
'is_highlighted': bool(state.is_highlighted) if state else False,
'is_archived': bool(state.is_archived) if state and state.is_archived is not None else False,
- 'tags': [{'id': t.id, 'name': t.name, 'color': t.color} for t in r.get_visible_tags(user)],
+ 'tags': [{'id': t.id, 'name': t.name, 'color': t.color}
+ for t in r.get_visible_tags(user, member_group_ids)],
}
return details
diff --git a/tests/test_recording_list_batch.py b/tests/test_recording_list_batch.py
index 80aeb1a9..c49a7e94 100644
--- a/tests/test_recording_list_batch.py
+++ b/tests/test_recording_list_batch.py
@@ -7,7 +7,13 @@ also exercises the per-row fallback of ``Recording.to_list_dict``), over a
fixture with every kind of row the list serves: owned, shared with and
without edit, editable through a group-admin role, tagged (personal, group,
hidden group), foldered, duplicated (owner-scoped on shared rows) and
-inbox / highlighted / archived for the owner and for a recipient.
+inbox / highlighted / archived for the owner and for a recipient. The
+inbox, audio-removed and shared-with-me lists, which serialize through the
+same to_list_dict, are compared the same way.
+
+The statement tests count every SQL statement of one request and require
+the same count for 25 and for 100 rows, under STATEMENT_BOUND; the v1 list
+and shared-with-me are held to the same rule.
SHARED-DB: everything is created under fresh users and removed afterwards;
assertions are scoped to this module's viewers.
@@ -27,16 +33,27 @@ from sqlalchemy import event
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import src.api.recordings as rec_module
+import src.api.shares as shares_module
from src.app import app, db
from src.models import (
- ExportTemplate, Folder, Group, GroupMembership, InternalShare, NamingTemplate, Recording,
+ APIToken, ExportTemplate, Folder, Group, GroupMembership, InternalShare, NamingTemplate, Recording,
RecordingTag, Share, SharedRecordingState, Tag, User,
)
+from src.utils.token_auth import hash_token
app.config["WTF_CSRF_ENABLED"] = False
_PREFIX = "lstb"
+# Statements for one page, whatever its size: the login user, the two
+# access-id queries, the count, the page, tags and folders (one each), the
+# viewer's shares, the two share counts, per-user states, owners,
+# duplicates, group memberships, tag counts, folder counts and the
+# group-admin check. The richest page measured 17 (25 or 100 shared rows
+# with group tags, group folders and duplicates); 20 leaves room for a
+# lookup or two, while one per-row query would add at least 25.
+STATEMENT_BOUND = 20
+
# --------------------------------------------------------------------------- #
# Helpers
@@ -62,7 +79,8 @@ def count_statements():
@contextmanager
def sharing_on():
with patch("src.app.ENABLE_INTERNAL_SHARING", True), \
- patch.object(rec_module, "ENABLE_INTERNAL_SHARING", True):
+ patch.object(rec_module, "ENABLE_INTERNAL_SHARING", True), \
+ patch.object(shares_module, "ENABLE_INTERNAL_SHARING", True):
yield
@@ -107,6 +125,7 @@ def _cleanup(user_ids, group_ids):
GroupMembership.query.filter(GroupMembership.user_id.in_(user_ids)).delete(synchronize_session=False)
if group_ids:
Group.query.filter(Group.id.in_(group_ids)).delete(synchronize_session=False)
+ APIToken.query.filter(APIToken.user_id.in_(user_ids)).delete(synchronize_session=False)
NamingTemplate.query.filter(NamingTemplate.user_id.in_(user_ids)).delete(synchronize_session=False)
ExportTemplate.query.filter(ExportTemplate.user_id.in_(user_ids)).delete(synchronize_session=False)
User.query.filter(User.id.in_(user_ids)).delete(synchronize_session=False)
@@ -123,7 +142,26 @@ def _client(user_id):
def _page(user_id, **params):
params.setdefault("per_page", 100)
- resp = _client(user_id).get("/api/recordings", query_string=params)
+ return _get(user_id, "/api/recordings", **params)
+
+
+def _get(user_id, path, **params):
+ resp = _client(user_id).get(path, query_string=params)
+ assert resp.status_code == 200, resp.get_json()
+ return resp.get_json()
+
+
+def _token(user_id):
+ plain = f"tok-{uuid.uuid4().hex}"
+ with app.app_context():
+ db.session.add(APIToken(user_id=user_id, token_hash=hash_token(plain), name="lstb"))
+ db.session.commit()
+ return plain
+
+
+def _v1(token, **params):
+ resp = app.test_client().get("/api/v1/recordings", query_string=params,
+ headers={"Authorization": f"Bearer {token}"})
assert resp.status_code == 200, resp.get_json()
return resp.get_json()
@@ -186,6 +224,41 @@ def _legacy_rows(viewer_id, ids):
return json.loads(json.dumps(enriched_recordings))
+def _legacy_plain_rows(viewer_id, ids):
+ """/api/inbox_recordings and /api/recordings/audio-removed before D#483."""
+ with app.app_context():
+ current_user = db.session.get(User, viewer_id)
+ return json.loads(json.dumps([db.session.get(Recording, rid).to_list_dict(viewer_user=current_user)
+ for rid in ids]))
+
+
+def _legacy_shared_with_me(viewer_id, ids):
+ """/api/recordings/shared-with-me before D#483, row by row."""
+ SHOW_USERNAMES_IN_UI = shares_module.SHOW_USERNAMES_IN_UI
+ with app.app_context():
+ current_user = db.session.get(User, viewer_id)
+ result = []
+ for rid in ids:
+ share = InternalShare.query.filter_by(recording_id=rid, shared_with_user_id=viewer_id).one()
+ recording = share.recording
+ rec_data = recording.to_list_dict(viewer_user=current_user)
+ rec_data['is_shared'] = True
+ rec_data['owner_username'] = share.owner.username if SHOW_USERNAMES_IN_UI else None
+ rec_data['shared_with_count'] = 0
+ rec_data['public_share_count'] = 0
+ visible_tags = recording.get_visible_tags(current_user)
+ rec_data['has_group_tags'] = any(tag.is_group_tag for tag in visible_tags) if visible_tags else False
+ rec_data['share_info'] = {
+ 'share_id': share.id,
+ 'owner_username': share.owner.username if SHOW_USERNAMES_IN_UI else None,
+ 'can_edit': share.can_edit,
+ 'can_reshare': share.can_reshare,
+ 'shared_at': share.created_at.isoformat()
+ }
+ result.append(rec_data)
+ return json.loads(json.dumps(result))
+
+
# --------------------------------------------------------------------------- #
# Rich fixture
# --------------------------------------------------------------------------- #
@@ -238,15 +311,21 @@ def world():
audio_duration_seconds=61.5, mime_type="audio/mpeg", file_size=1234)
b = _rec(viewer, None, marker, folder_id=f_personal.id, file_hash="h1" + sfx, created_at=next(when),
is_archived=True)
- c = _rec(viewer, "C", marker, created_at=next(when), audio_deleted_at=base, mime_type="video/mp4",
- deletion_exempt=True, keep_audio_only=True)
+ c = _rec(viewer, "C", marker, folder_id=f_personal.id, created_at=next(when), audio_deleted_at=base,
+ mime_type="video/mp4", deletion_exempt=True, keep_audio_only=True)
d = _rec(viewer, "D", marker, file_hash="h2" + sfx, created_at=next(when), completed_at=base)
+ e = _rec(viewer, "E", marker, folder_id=f_personal.id, file_hash="h2" + sfx, created_at=next(when),
+ status="PROCESSING")
v1 = _rec(viewer, "V1", marker, file_hash="h3" + sfx, created_at=next(when))
v2 = _rec(viewer, "V2", marker, file_hash="h3" + sfx, created_at=next(when))
_tag(a, t_personal, 0)
_tag(a, t_member, 1)
_tag(a, t_out, 2)
+ _tag(a, t_o1_private, 3) # an editor's personal tag: hidden from the owner
_tag(b, t_personal, 0)
+ _tag(c, t_personal, 0)
+ _tag(e, t_member, 0)
+ _tag(e, t_personal, 1)
_share(a, o1, can_edit=True)
_share(a, o2)
db.session.add(Share(recording_id=a.id, user_id=viewer.id))
@@ -281,17 +360,19 @@ def world():
personal_notes="mine"))
s6 = _rec(o2, "S6", marker, created_at=next(when), file_hash="h4" + sfx)
+ _tag(s6, t_out, 0)
_share(s6, viewer, can_reshare=True)
db.session.add(SharedRecordingState(recording_id=s6.id, user_id=viewer.id,
is_inbox=True, is_highlighted=False))
db.session.commit()
- ids = dict(viewer=viewer.id, o1=o1.id, o2=o2.id, x=x.id, a=a.id, b=b.id, c=c.id, d=d.id,
+ ids = dict(viewer=viewer.id, o1=o1.id, o2=o2.id, x=x.id, a=a.id, b=b.id, c=c.id, d=d.id, e=e.id,
v1=v1.id, v2=v2.id, s1=s1.id, s1_copy=s1_copy.id, s2=s2.id, s3=s3.id, s4=s4.id,
s5=s5.id, s6=s6.id, marker=marker,
t_personal=t_personal.id, t_member=t_member.id, t_admin=t_admin.id,
f_personal=f_personal.id, f_group=f_group.id)
groups = [g_admin.id, g_member.id, g_lead_off.id, g_out.id]
+ ids["token"] = _token(ids["viewer"])
with sharing_on():
yield ids
_cleanup([ids["viewer"], ids["o1"], ids["o2"], ids["x"]], groups)
@@ -322,16 +403,17 @@ def test_fixture_covers_every_kind_of_row(world):
"""Guards the parity test against a fixture that stopped exercising a case."""
w = world
rows = {r["id"]: r for r in _page(w["viewer"], q=w["marker"])["recordings"]}
- assert set(rows) == {w[k] for k in ("a", "b", "c", "d", "v1", "v2", "s1", "s2", "s3", "s4", "s5", "s6")}
+ assert set(rows) == {w[k] for k in ("a", "b", "c", "d", "e", "v1", "v2", "s1", "s2", "s3", "s4", "s5", "s6")}
default_ids = {r["id"] for r in _page(w["viewer"])["recordings"]}
assert default_ids == set(rows) - {w["b"], w["s5"]} # archived by owner / by recipient
a, b, s1, s2, s3, s4, s5, s6 = (rows[w[k]] for k in ("a", "b", "s1", "s2", "s3", "s4", "s5", "s6"))
# owned: tags in order, hidden group tag dropped, counts over all recordings
assert [t["name"] for t in a["tags"]] == ["Personal", "TeamTag"]
- assert a["tags"][0]["recording_count"] == 2 and a["tags"][0]["naming_template_name"] == "Naming T"
- assert a["tags"][1]["group_name"].startswith(f"{_PREFIX}_member_") and a["tags"][1]["recording_count"] == 2
- assert a["folder"]["recording_count"] == 2 and a["folder"]["export_template_name"] == "Export T"
+ assert a["tags"][0]["recording_count"] == 4 and a["tags"][0]["naming_template_name"] == "Naming T"
+ assert a["tags"][1]["group_name"].startswith(f"{_PREFIX}_member_") and a["tags"][1]["recording_count"] == 3
+ assert a["folder"]["recording_count"] == 4 and a["folder"]["export_template_name"] == "Export T"
+ assert [t["name"] for t in rows[w["e"]]["tags"]] == ["TeamTag", "Personal"]
assert (a["shared_with_count"], a["public_share_count"]) == (2, 1)
assert (a["is_inbox"], a["is_highlighted"], a["has_group_tags"]) == (False, True, True)
assert [c["id"] for c in a["duplicate_info"]["copies"]] == [w["a"], w["b"]]
@@ -350,6 +432,130 @@ def test_fixture_covers_every_kind_of_row(world):
assert s5["folder"]["is_foreign"] is True and s5["folder"]["recording_count"] == 2
assert (s5["is_archived"], s5["is_inbox"]) == (True, True)
assert (s6["is_inbox"], s6["is_highlighted"], s6["duplicate_info"]) == (True, False, None)
+ assert (s6["tags"], s6["has_group_tags"]) == ([], False)
assert s6["owner_username"].startswith(f"{_PREFIX}o2")
assert all(r["can_delete"] == r["is_owner"] for r in rows.values())
+
+def test_other_lists_match_the_per_row_path(world):
+ w = world
+ inbox = _get(w["viewer"], "/api/inbox_recordings")
+ assert [r["id"] for r in inbox] == [w["e"]] and inbox[0]["duplicate_info"]["total_copies"] == 2
+ assert inbox == _legacy_plain_rows(w["viewer"], [w["e"]])
+ removed = _get(w["viewer"], "/api/recordings/audio-removed")
+ assert [r["id"] for r in removed] == [w["c"]] and removed[0]["tags"][0]["recording_count"] == 4
+ assert removed == _legacy_plain_rows(w["viewer"], [w["c"]])
+ for show in (False, True):
+ with patch.object(shares_module, "SHOW_USERNAMES_IN_UI", show):
+ shared = _get(w["viewer"], "/api/recordings/shared-with-me")
+ assert {r["id"] for r in shared} == {w[k] for k in ("s1", "s2", "s3", "s4", "s5", "s6")}
+ assert shared == _legacy_shared_with_me(w["viewer"], [r["id"] for r in shared])
+ by_id = {r["id"]: r for r in shared}
+ assert by_id[w["s2"]]["has_group_tags"] is True and by_id[w["s1"]]["owner_username"].startswith(f"{_PREFIX}o1")
+
+
+def test_v1_list_tags_of_shared_rows(world):
+ # The v1 list reads the viewer's group memberships once for the page
+ w = world
+ rows = {r["id"]: r for r in _v1(w["token"], scope="all", per_page=100)["recordings"]}
+ assert [t["name"] for t in rows[w["s2"]]["tags"]] == ["AdminTag"] # O1's personal tag hidden
+ assert [t["name"] for t in rows[w["s3"]]["tags"]] == ["TeamTag"]
+ assert [t["name"] for t in rows[w["s4"]]["tags"]] == ["LeadOff"]
+ assert rows[w["s6"]]["tags"] == [] # viewer not in that group
+
+
+# --------------------------------------------------------------------------- #
+# Statements per page
+# --------------------------------------------------------------------------- #
+
+def _build_scenario(kind, n):
+ """A fresh viewer whose list holds n rows of one kind; returns the ids to clean up."""
+ with app.app_context():
+ viewer = _user("sv")
+ users, groups = [viewer.id], []
+ base = datetime(2026, 4, 1, 9, 0, 0)
+ if kind.startswith("owned"):
+ for i in range(n):
+ rec = _rec(viewer, f"own {i}", "m", created_at=base + timedelta(seconds=i))
+ if kind == "owned_rich":
+ folder = Folder(name=f"f{i}", user_id=viewer.id)
+ tag = Tag(name=f"t{i}", user_id=viewer.id)
+ db.session.add_all([folder, tag])
+ db.session.flush()
+ rec.folder_id = folder.id
+ rec.file_hash = f"hash{i // 2}-{viewer.id}" # pairs of duplicates
+ _tag(rec, tag, 0)
+ else:
+ group = Group(name=f"{_PREFIX}_sc_{uuid.uuid4().hex[:8]}")
+ db.session.add(group)
+ db.session.flush()
+ groups.append(group.id)
+ db.session.add(GroupMembership(group_id=group.id, user_id=viewer.id, role="admin"))
+ for i in range(n):
+ owner = _user("so")
+ users.append(owner.id)
+ rec = _rec(owner, f"shared {i}", "m", created_at=base + timedelta(seconds=i))
+ if kind == "shared_rich":
+ folder = Folder(name=f"gf{i}", user_id=owner.id, group_id=group.id)
+ tag = Tag(name=f"gt{i}", user_id=owner.id, group_id=group.id)
+ db.session.add_all([folder, tag])
+ db.session.flush()
+ rec.folder_id = folder.id
+ rec.file_hash = f"shash-{owner.id}"
+ _rec(owner, f"copy {i}", "m", file_hash=rec.file_hash, created_at=base)
+ _tag(rec, tag, 0)
+ _share(rec, viewer, can_edit=False, source_type="group_tag", source_tag_id=tag.id)
+ db.session.add(SharedRecordingState(recording_id=rec.id, user_id=viewer.id,
+ is_inbox=False, is_highlighted=bool(i % 2)))
+ else:
+ _share(rec, viewer, can_edit=(kind == "shared_edit"))
+ db.session.commit()
+ return viewer.id, users, groups
+
+
+def _statements(fetch, rows):
+ fetch() # warm-up
+ with count_statements() as statements:
+ body = fetch()
+ assert len(body["recordings"] if isinstance(body, dict) else body) == rows
+ return len(statements)
+
+
+def _statements_for_page(viewer_id, per_page):
+ return _statements(lambda: _page(viewer_id, per_page=per_page), per_page)
+
+
[email protected]("kind", ["owned_plain", "owned_rich", "shared_edit", "shared_view", "shared_rich"])
+def test_statements_per_page_do_not_grow_with_rows(kind):
+ small_viewer, small_users, small_groups = _build_scenario(kind, 25)
+ large_viewer, large_users, large_groups = _build_scenario(kind, 100)
+ try:
+ with sharing_on():
+ small = _statements_for_page(small_viewer, 25)
+ large = _statements_for_page(large_viewer, 100)
+ print(f"{kind}: 25 rows -> {small} statements, 100 rows -> {large} statements")
+ assert large == small
+ assert small <= STATEMENT_BOUND
+ finally:
+ _cleanup(small_users + large_users, small_groups + large_groups)
+
+
[email protected]("kind", ["owned_rich", "shared_rich"])
+def test_v1_and_shared_with_me_statements_do_not_grow_with_rows(kind):
+ small_viewer, small_users, small_groups = _build_scenario(kind, 25)
+ large_viewer, large_users, large_groups = _build_scenario(kind, 100)
+ try:
+ counts = {}
+ with sharing_on():
+ for viewer, n in ((small_viewer, 25), (large_viewer, 100)):
+ token = _token(viewer)
+ counts["v1", n] = _statements(lambda: _v1(token, scope="all", per_page=n), n)
+ if kind.startswith("shared"):
+ counts["shared-with-me", n] = _statements(
+ lambda: _get(viewer, "/api/recordings/shared-with-me"), n)
+ print(kind, counts)
+ for (name, n), count in counts.items():
+ assert count == counts[name, 25], (name, counts)
+ assert count <= STATEMENT_BOUND
+ finally:
+ _cleanup(small_users + large_users, small_groups + large_groups)