Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
GET /recordings, the tag and folder lists and the Shared Transcripts overview in a fixed number of statements, and statement counts limited to the request thread (D#483)
Murtaza Nasire5a6b2110479
diff --git a/src/api/folders.py b/src/api/folders.pyindex 78e75189..74ea8e2a 100644--- a/src/api/folders.py+++ b/src/api/folders.py@@ -50,7 +50,9 @@ def get_folders():return jsonify([])# Get user's personal folders- user_folders = Folder.query.filter_by(user_id=current_user.id, group_id=None).order_by(Folder.name).all()+ from src.services.recording_list import folder_dicts, folder_load_options+ user_folders = (Folder.query.filter_by(user_id=current_user.id, group_id=None)+ .options(*folder_load_options()).order_by(Folder.name).all())# Get user's team memberships with rolesmemberships = GroupMembership.query.filter_by(user_id=current_user.id).all()@@ -60,21 +62,23 @@ def get_folders():# Get group folders for all teams the user is a member ofteam_folders = []if team_ids:- team_folders = Folder.query.filter(Folder.group_id.in_(team_ids)).order_by(Folder.name).all()+ team_folders = (Folder.query.filter(Folder.group_id.in_(team_ids))+ .options(*folder_load_options()).order_by(Folder.name).all())# Build response with edit permissionsresult = []+ dicts = dict(zip([f.id for f in user_folders + team_folders], folder_dicts(user_folders + team_folders)))# Personal folders - user can always edit their ownfor folder in user_folders:- folder_dict = folder.to_dict()+ folder_dict = dicts[folder.id]folder_dict['can_edit'] = Truefolder_dict['user_role'] = Noneresult.append(folder_dict)# Group folders - only admins can editfor folder in team_folders:- folder_dict = folder.to_dict()+ folder_dict = dicts[folder.id]user_role = team_roles.get(folder.group_id, 'member')folder_dict['can_edit'] = (user_role == 'admin')folder_dict['user_role'] = user_role@@ -445,9 +449,10 @@ def get_group_folders(group_id):return jsonify({'error': 'You must be a team member to view group folders'}), 403# Get all group folders- folders = Folder.query.filter_by(group_id=group_id).all()+ from src.services.recording_list import folder_dicts, folder_load_options+ folders = Folder.query.filter_by(group_id=group_id).options(*folder_load_options()).order_by(Folder.id).all()- return jsonify({'folders': [folder.to_dict() for folder in folders]})+ return jsonify({'folders': folder_dicts(folders)})@folders_bp.route('/api/recordings/<int:recording_id>/folder', methods=['PUT'])diff --git a/src/api/recordings.py b/src/api/recordings.pyindex a266c953..a9327d48 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -1451,13 +1451,15 @@ def get_recordings():return jsonify([]) # Return empty array if not logged in# Filter recordings by the current user+ from src.services.recording_list import RecordingListBatch, full_load_optionsstmt = select(Recording).where(Recording.user_id == current_user.id).order_by(Recording.created_at.desc())- recordings = db.session.execute(stmt).scalars().all()+ recordings = db.session.execute(stmt.options(*full_load_options())).scalars().all()# Pre-batch the duplicate-info groupings so we don't run a# per-row query inside each recording's to_dict() call.dup_map = Recording.get_duplicate_info_map(current_user.id)+ batch = RecordingListBatch(recordings, current_user, duplicates=False)return jsonify([- recording.to_dict(viewer_user=current_user, duplicate_info_map=dup_map)+ recording.to_dict(viewer_user=current_user, duplicate_info_map=dup_map, batch=batch)for recording in recordings])except Exception as e:diff --git a/src/api/shares.py b/src/api/shares.pyindex ebaa704b..739117d3 100644--- a/src/api/shares.py+++ b/src/api/shares.py@@ -276,22 +276,43 @@ def get_shares_overview():The list predates internal sharing and showed public links only. It nowhas what the user shared (public links, and recordings shared with peopleand groups) and what was shared with them.++ The recordings, users, source tags and source folders of the shares are+ read once per list (D#483), with only the recording columns shown here."""+ from sqlalchemy.orm import joinedload, load_only, selectinload+ folders = {}+def _source(share):if share.source_type == 'group_tag' and share.source_tag is not None:return {'type': 'group_tag', 'name': share.source_tag.name}if share.source_type == 'group_folder' and share.source_folder_id:- folder = db.session.get(Folder, share.source_folder_id)+ folder = folders.get(share.source_folder_id)return {'type': 'group_folder', 'name': folder.name if folder else None}return {'type': 'manual', 'name': None}+ def _internal(*criteria):+ shares = (InternalShare.query.filter(*criteria)+ .options(selectinload(InternalShare.recording).load_only(+ Recording.id, Recording.title, Recording.original_filename, Recording.status),+ joinedload(InternalShare.shared_with), joinedload(InternalShare.owner),+ joinedload(InternalShare.source_tag))+ .order_by(InternalShare.created_at.desc(), InternalShare.id.desc()).all())+ wanted = {s.source_folder_id for s in shares+ if s.source_type == 'group_folder' and s.source_folder_id and s.source_folder_id not in folders}+ if wanted:+ folders.update({f.id: f for f in Folder.query.filter(Folder.id.in_(sorted(wanted)))})+ return shares+public_links = [s.to_dict() for s in- Share.query.filter_by(user_id=current_user.id).order_by(Share.created_at.desc()).all()]+ Share.query.filter_by(user_id=current_user.id)+ .options(selectinload(Share.recording).load_only(+ Recording.id, Recording.title, Recording.audio_deleted_at))+ .order_by(Share.created_at.desc(), Share.id.desc()).all()]shared_by_me, shared_with_me = [], []if ENABLE_INTERNAL_SHARING:by_recording = {}- for share in (InternalShare.query.filter_by(owner_id=current_user.id)- .order_by(InternalShare.created_at.desc()).all()):+ for share in _internal(InternalShare.owner_id == current_user.id):recording = share.recordingif recording is None:continue@@ -315,8 +336,7 @@ def get_shares_overview():})shared_by_me = list(by_recording.values())- for share in (InternalShare.query.filter_by(shared_with_user_id=current_user.id)- .order_by(InternalShare.created_at.desc()).all()):+ for share in _internal(InternalShare.shared_with_user_id == current_user.id):recording = share.recordingif recording is None:continuediff --git a/src/api/tags.py b/src/api/tags.pyindex 56d56264..90cb2e74 100644--- a/src/api/tags.py+++ b/src/api/tags.py@@ -138,7 +138,9 @@ def init_tags_helpers(**kwargs):def get_tags():"""Get all tags for the current user, including group tags they have access to."""# Get user's personal tags- user_tags = Tag.query.filter_by(user_id=current_user.id, group_id=None).order_by(Tag.name).all()+ from src.services.recording_list import tag_dicts, tag_load_options+ user_tags = (Tag.query.filter_by(user_id=current_user.id, group_id=None)+ .options(*tag_load_options()).order_by(Tag.name).all())# Get user's team memberships with rolesmemberships = GroupMembership.query.filter_by(user_id=current_user.id).all()@@ -148,21 +150,22 @@ def get_tags():# Get group tags for all teams the user is a member ofteam_tags = []if team_ids:- team_tags = Tag.query.filter(Tag.group_id.in_(team_ids)).order_by(Tag.name).all()+ team_tags = Tag.query.filter(Tag.group_id.in_(team_ids)).options(*tag_load_options()).order_by(Tag.name).all()# Build response with edit permissionsresult = []+ dicts = dict(zip([t.id for t in user_tags + team_tags], tag_dicts(user_tags + team_tags)))# Personal tags - user can always edit their ownfor tag in user_tags:- tag_dict = tag.to_dict()+ tag_dict = dicts[tag.id]tag_dict['can_edit'] = Truetag_dict['user_role'] = Noneresult.append(tag_dict)# Group tags - only admins can editfor tag in team_tags:- tag_dict = tag.to_dict()+ tag_dict = dicts[tag.id]user_role = team_roles.get(tag.group_id, 'member')tag_dict['can_edit'] = (user_role == 'admin')tag_dict['user_role'] = user_role@@ -588,9 +591,10 @@ def get_group_tags(group_id):return jsonify({'error': 'You must be a team member to view group tags'}), 403# Get all group tags- tags = Tag.query.filter_by(group_id=group_id).all()+ from src.services.recording_list import tag_dicts, tag_load_options+ tags = Tag.query.filter_by(group_id=group_id).options(*tag_load_options()).order_by(Tag.id).all()- return jsonify({'tags': [tag.to_dict() for tag in tags]})+ return jsonify({'tags': tag_dicts(tags)})diff --git a/src/models/recording.py b/src/models/recording.pyindex 76de9c1f..24725bd4 100644--- a/src/models/recording.py+++ b/src/models/recording.py@@ -460,7 +460,7 @@ class Recording(db.Model):return {'total_copies': entry['total_copies'], 'copies': copies}return self.get_duplicate_info()- def to_dict(self, include_html=True, viewer_user=None, duplicate_info_map=None, share_map=None):+ def to_dict(self, include_html=True, viewer_user=None, duplicate_info_map=None, share_map=None, batch=None):"""Full dict with optional HTML conversion for notes/summary.@@ -469,24 +469,38 @@ class Recording(db.Model):viewer_user: User viewing the recording (for tag visibility filtering)share_map: optional {recording_id: InternalShare} for #314 share-reasonresolution without an N+1 query.+ batch: optional RecordingListBatch built for viewer_user over the+ list: share counts, duplicates, visible tags, tag/folder counts+ and the viewer's notes come from it instead of per-row queries.+ A duplicate_info_map, when given, still decides duplicate_info."""# Import here to avoid circular dependenciesfrom 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)+ if share_map is None:+ share_map = batch.share_map+ user_notes = batch.user_notes(self) if viewer_user is not None else self.notes+ duplicate_info = (self._dup_from_map_or_query(duplicate_info_map) if duplicate_info_map is not None+ else batch.duplicate_info(self))+ 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- tags_ser, folder_ser, folder_id_ser = self._serialize_tags_and_folder(viewer_user, share_map)+ # Get user-specific notes+ user_notes = self.get_user_notes(viewer_user)+ duplicate_info = self._dup_from_map_or_query(duplicate_info_map)- # Get user-specific notes- user_notes = self.get_user_notes(viewer_user)+ tags_ser, folder_ser, folder_id_ser = self._serialize_tags_and_folder(viewer_user, share_map, batch)data = {'id': self.id,@@ -522,7 +536,7 @@ class Recording(db.Model):'prompt_variables': self.prompt_variables or {},'resolved_hotwords': self.resolved_hotwords,'resolved_initial_prompt': self.resolved_initial_prompt,- '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,'keep_audio_only': self.keep_audio_only,diff --git a/src/services/recording_list.py b/src/services/recording_list.pyindex e7b65fcd..3d8ec3d5 100644--- a/src/services/recording_list.py+++ b/src/services/recording_list.py@@ -3,9 +3,11 @@Serializing a page one row at a time cost several queries per row: the twoshare 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.+reads each of them once for the page. Recording.to_list_dict and+Recording.to_dict take it as ``batch``; without one they keep their per-row+queries, which single-row callers still use, so both paths must give the+same payload. tag_dicts and folder_dicts do the same for the tag and folder+lists."""from sqlalchemy import func@@ -25,18 +27,45 @@ _LIST_DEFERRED = ()-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))+def tag_load_options():+ """Loader options for a Tag query whose rows go through Tag.to_dict."""+ return [joinedload(Tag.group), joinedload(Tag.naming_template), joinedload(Tag.export_template)]+++def folder_load_options():+ """Loader options for a Folder query whose rows go through Folder.to_dict."""+ return [joinedload(Folder.group), joinedload(Folder.naming_template), joinedload(Folder.export_template)]+++def _tags_and_folder_options():return [- selectinload(Recording.tag_associations).joinedload(RecordingTag.tag).options(*names),- selectinload(Recording.folder).options(*folder_names),- *(defer(column) for column in _LIST_DEFERRED),+ selectinload(Recording.tag_associations).joinedload(RecordingTag.tag).options(*tag_load_options()),+ selectinload(Recording.folder).options(*folder_load_options()),]+def list_load_options():+ """Loader options for a page query whose rows go through to_list_dict."""+ return [*_tags_and_folder_options(), *(defer(column) for column in _LIST_DEFERRED)]+++def full_load_options():+ """Loader options for a list query whose rows go through to_dict."""+ return [*_tags_and_folder_options(), selectinload(Recording.events)]+++def tag_dicts(tags):+ """Tag.to_dict for each tag, with the recording counts read in one query."""+ counts = _counts(RecordingTag.tag_id, sorted({t.id for t in tags}))+ return [tag.to_dict(recording_count=counts.get(tag.id, 0)) for tag in tags]+++def folder_dicts(folders):+ """Folder.to_dict for each folder, with the recording counts read in one query."""+ counts = _counts(Recording.folder_id, sorted({f.id for f in folders}))+ return [folder.to_dict(recording_count=counts.get(folder.id, 0)) for folder in folders]++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})@@ -57,10 +86,11 @@ 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.+ page, when the caller has already read it. duplicates=False skips the+ duplicate lookup for a caller that passes its own duplicate_info_map."""- def __init__(self, recordings, viewer, share_map=None):+ def __init__(self, recordings, viewer, share_map=None, duplicates=True):self.viewer = viewerids = [r.id for r in recordings]foreign = [r for r in recordings if r.user_id != viewer.id]@@ -85,7 +115,7 @@ class RecordingListBatch: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)+ self._duplicates = self._load_duplicates(recordings) if duplicates else {}member_group_ids = group_ids_of(viewer, recordings)self._visible = {r.id: r.get_visible_tags(viewer, member_group_ids) for r in recordings}@@ -148,6 +178,13 @@ class RecordingListBatch:state = self.states.get(recording.id)return (state.is_inbox, state.is_highlighted) if state else (True, False)+ def user_notes(self, recording):+ """Recording.get_user_notes for the viewer."""+ if recording.user_id == self.viewer.id:+ return recording.notes+ state = self.states.get(recording.id)+ return state.personal_notes if state else None+def user_archived(self, recording):"""get_user_archived for the viewer."""if recording.user_id == self.viewer.id:diff --git a/tests/test_recording_list_batch.py b/tests/test_recording_list_batch.pyindex c49a7e94..c38effdd 100644--- a/tests/test_recording_list_batch.py+++ b/tests/test_recording_list_batch.py@@ -15,6 +15,10 @@ The statement tests count every SQL statement of one request and requirethe same count for 25 and for 100 rows, under STATEMENT_BOUND; the v1 listand shared-with-me are held to the same rule.+GET /recordings (the full to_dict of every owned recording), the tag and+folder lists and the Shared Transcripts overview are compared with frozen+copies of their per-row code in the same way, and held to the same rule.+SHARED-DB: everything is created under fresh users and removed afterwards;assertions are scoped to this module's viewers."""@@ -22,22 +26,24 @@ assertions are scoped to this module's viewers.import jsonimport osimport sys+import threadingimport uuidfrom contextlib import contextmanagerfrom datetime import datetime, timedeltafrom unittest.mock import patchimport pytest-from sqlalchemy import event+from sqlalchemy import event, selectsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import src.api.folders as folders_moduleimport src.api.recordings as rec_moduleimport src.api.shares as shares_modulefrom src.app import app, dbfrom src.models import (- APIToken, ExportTemplate, Folder, Group, GroupMembership, InternalShare, NamingTemplate, Recording,- RecordingTag, Share, SharedRecordingState, Tag, User,+ APIToken, Event, ExportTemplate, Folder, Group, GroupMembership, InternalShare, NamingTemplate, Recording,+ RecordingTag, Share, SharedRecordingState, SystemSetting, Tag, User,)from src.utils.token_auth import hash_token@@ -61,11 +67,18 @@ STATEMENT_BOUND = 20@contextmanagerdef count_statements():- """Collect every SQL statement sent to the database inside the block."""+ """Collect every SQL statement this thread sends to the database inside the block.++ The test client serves the request in the calling thread. Statements of+ background threads (the webhook dispatcher polls the same engine) are+ left out, so a poll during the request does not change the count.+ """statements = []+ thread = threading.get_ident()def _before(conn, cursor, statement, parameters, context, executemany):- statements.append(statement)+ if threading.get_ident() == thread:+ statements.append(statement)with app.app_context():engine = db.engine@@ -84,6 +97,17 @@ def sharing_on():yield+@contextmanager+def folders_on():+ real = SystemSetting.get_setting++ def get_setting(key, default_value=None):+ return True if key == 'enable_folders' else real(key, default_value)++ with patch.object(SystemSetting, "get_setting", staticmethod(get_setting)):+ yield++def _user(tag):s = uuid.uuid4().hex[:8]u = User(username=f"{_PREFIX}{tag}_{s}"[:20], email=f"{_PREFIX}{tag}_{s}@local.test", password="x")@@ -117,7 +141,7 @@ def _cleanup(user_ids, group_ids):db.session.rollback()rec_ids = [r for (r,) in db.session.query(Recording.id).filter(Recording.user_id.in_(user_ids))]if rec_ids:- for model in (RecordingTag, Share, InternalShare, SharedRecordingState):+ for model in (RecordingTag, Share, InternalShare, SharedRecordingState, Event):model.query.filter(model.recording_id.in_(rec_ids)).delete(synchronize_session=False)Recording.query.filter(Recording.id.in_(rec_ids)).delete(synchronize_session=False)Tag.query.filter(Tag.user_id.in_(user_ids)).delete(synchronize_session=False)@@ -326,6 +350,7 @@ def world():_tag(c, t_personal, 0)_tag(e, t_member, 0)_tag(e, t_personal, 1)+ db.session.add(Event(recording_id=a.id, title="Kickoff", start_datetime=base, location="Room 1"))_share(a, o1, can_edit=True)_share(a, o2)db.session.add(Share(recording_id=a.id, user_id=viewer.id))@@ -484,7 +509,9 @@ def _build_scenario(kind, n):db.session.flush()rec.folder_id = folder.idrec.file_hash = f"hash{i // 2}-{viewer.id}" # pairs of duplicates+ rec.notes = f"notes {i}"_tag(rec, tag, 0)+ db.session.add(Event(recording_id=rec.id, title=f"e{i}", start_datetime=base))else:group = Group(name=f"{_PREFIX}_sc_{uuid.uuid4().hex[:8]}")db.session.add(group)@@ -559,3 +586,220 @@ def test_v1_and_shared_with_me_statements_do_not_grow_with_rows(kind):assert count <= STATEMENT_BOUNDfinally:_cleanup(small_users + large_users, small_groups + large_groups)+++# --------------------------------------------------------------------------- #+# GET /recordings, tag and folder lists, Shared Transcripts overview+# --------------------------------------------------------------------------- #++def _legacy_get_recordings(viewer_id):+ """GET /recordings before the batching, verbatim."""+ with app.app_context():+ current_user = db.session.get(User, viewer_id)+ stmt = select(Recording).where(Recording.user_id == current_user.id).order_by(Recording.created_at.desc())+ recordings = db.session.execute(stmt).scalars().all()+ dup_map = Recording.get_duplicate_info_map(current_user.id)+ return json.loads(json.dumps([+ recording.to_dict(viewer_user=current_user, duplicate_info_map=dup_map)+ for recording in recordings+ ]))+++def _legacy_tags(viewer_id):+ """GET /api/tags before the batching, verbatim."""+ with app.app_context():+ current_user = db.session.get(User, viewer_id)+ user_tags = Tag.query.filter_by(user_id=current_user.id, group_id=None).order_by(Tag.name).all()+ memberships = GroupMembership.query.filter_by(user_id=current_user.id).all()+ team_roles = {m.group_id: m.role for m in memberships}+ team_ids = list(team_roles.keys())+ team_tags = []+ if team_ids:+ team_tags = Tag.query.filter(Tag.group_id.in_(team_ids)).order_by(Tag.name).all()+ result = []+ for tag in user_tags:+ tag_dict = tag.to_dict()+ tag_dict['can_edit'] = True+ tag_dict['user_role'] = None+ result.append(tag_dict)+ for tag in team_tags:+ tag_dict = tag.to_dict()+ user_role = team_roles.get(tag.group_id, 'member')+ tag_dict['can_edit'] = (user_role == 'admin')+ tag_dict['user_role'] = user_role+ result.append(tag_dict)+ return json.loads(json.dumps(result))+++def _legacy_folders(viewer_id):+ """GET /api/folders before the batching, verbatim (folders enabled)."""+ with app.app_context():+ current_user = db.session.get(User, viewer_id)+ user_folders = Folder.query.filter_by(user_id=current_user.id, group_id=None).order_by(Folder.name).all()+ memberships = GroupMembership.query.filter_by(user_id=current_user.id).all()+ team_roles = {m.group_id: m.role for m in memberships}+ team_ids = list(team_roles.keys())+ team_folders = []+ if team_ids:+ team_folders = Folder.query.filter(Folder.group_id.in_(team_ids)).order_by(Folder.name).all()+ result = []+ for folder in user_folders:+ folder_dict = folder.to_dict()+ folder_dict['can_edit'] = True+ folder_dict['user_role'] = None+ result.append(folder_dict)+ for folder in team_folders:+ folder_dict = folder.to_dict()+ user_role = team_roles.get(folder.group_id, 'member')+ folder_dict['can_edit'] = (user_role == 'admin')+ folder_dict['user_role'] = user_role+ result.append(folder_dict)+ return json.loads(json.dumps(result))+++def _legacy_overview(viewer_id):+ """GET /api/shares/overview before the batching, verbatim apart from the+ id tie-breakers both versions now use for shares created in the same instant."""+ from src.api.shares import ENABLE_PUBLIC_SHARING, SHOW_USERNAMES_IN_UI+ ENABLE_INTERNAL_SHARING = shares_module.ENABLE_INTERNAL_SHARING+ with app.app_context():+ current_user = db.session.get(User, viewer_id)++ def _source(share):+ if share.source_type == 'group_tag' and share.source_tag is not None:+ return {'type': 'group_tag', 'name': share.source_tag.name}+ if share.source_type == 'group_folder' and share.source_folder_id:+ folder = db.session.get(Folder, share.source_folder_id)+ return {'type': 'group_folder', 'name': folder.name if folder else None}+ return {'type': 'manual', 'name': None}++ public_links = [s.to_dict() for s in+ Share.query.filter_by(user_id=current_user.id)+ .order_by(Share.created_at.desc(), Share.id.desc()).all()]+ shared_by_me, shared_with_me = [], []+ if ENABLE_INTERNAL_SHARING:+ by_recording = {}+ for share in (InternalShare.query.filter_by(owner_id=current_user.id)+ .order_by(InternalShare.created_at.desc(), InternalShare.id.desc()).all()):+ recording = share.recording+ if recording is None:+ continue+ entry = by_recording.setdefault(recording.id, {+ 'recording_id': recording.id,+ 'recording_title': recording.title or recording.original_filename or f'#{recording.id}',+ 'recipients': [],+ })+ source = _source(share)+ entry['recipients'].append({+ 'share_id': share.id,+ 'user_id': share.shared_with_user_id,+ 'username': share.shared_with.username if share.shared_with else None,+ 'can_edit': bool(share.can_edit),+ 'can_reshare': bool(share.can_reshare),+ 'source': source,+ 'revocable': source['type'] == 'manual',+ 'created_at': share.created_at.isoformat() if share.created_at else None,+ })+ shared_by_me = list(by_recording.values())++ for share in (InternalShare.query.filter_by(shared_with_user_id=current_user.id)+ .order_by(InternalShare.created_at.desc(), InternalShare.id.desc()).all()):+ recording = share.recording+ if recording is None:+ continue+ shared_with_me.append({+ 'share_id': share.id,+ 'recording_id': recording.id,+ 'recording_title': recording.title or recording.original_filename or f'#{recording.id}',+ 'owner_username': share.owner.username if SHOW_USERNAMES_IN_UI and share.owner else None,+ 'can_edit': bool(share.can_edit),+ 'can_reshare': bool(share.can_reshare),+ 'source': _source(share),+ 'status': recording.status,+ 'created_at': share.created_at.isoformat() if share.created_at else None,+ })++ return json.loads(json.dumps({+ 'public_sharing_enabled': ENABLE_PUBLIC_SHARING,+ 'internal_sharing_enabled': ENABLE_INTERNAL_SHARING,+ 'public_links': public_links,+ 'shared_by_me': shared_by_me,+ 'shared_with_me': shared_with_me,+ }))+++def test_get_recordings_matches_the_per_row_path(world):+ w = world+ rows = _get(w["viewer"], "/recordings")+ assert [r["id"] for r in rows] == [w[k] for k in ("v2", "v1", "e", "d", "c", "b", "a")]+ assert rows == _legacy_get_recordings(w["viewer"])+ a = rows[-1]+ assert a["events"][0]["title"] == "Kickoff" and a["notes"] == "owner notes" and a["transcription"] == "hello"+ assert [t["name"] for t in a["tags"]] == ["Personal", "TeamTag"] and a["tags"][0]["recording_count"] == 4+ assert (a["shared_with_count"], a["public_share_count"]) == (2, 1)+ assert a["duplicate_info"]["total_copies"] == 2 and a["folder"]["recording_count"] == 4+++def test_tag_and_folder_lists_match_the_per_row_path(world):+ w = world+ tags = _get(w["viewer"], "/api/tags")+ assert tags == _legacy_tags(w["viewer"])+ by_name = {t["name"]: t for t in tags}+ assert by_name["Personal"]["recording_count"] == 4 and by_name["Personal"]["naming_template_name"] == "Naming T"+ assert by_name["TeamTag"]["recording_count"] == 3 and by_name["AdminTag"]["can_edit"] is True+ assert "Outsiders" not in by_name+ with folders_on():+ folders = _get(w["viewer"], "/api/folders")+ assert folders == _legacy_folders(w["viewer"])+ by_name = {f["name"]: f for f in folders}+ assert by_name["MyFolder"]["recording_count"] == 4 and by_name["MyFolder"]["export_template_name"] == "Export T"+ assert by_name["TeamFolder"]["recording_count"] == 2 and by_name["TeamFolder"]["can_edit"] is False+ with app.app_context():+ group_id = db.session.get(Folder, w["f_group"]).group_id+ legacy_folders = json.loads(json.dumps(+ [f.to_dict() for f in sorted(Folder.query.filter_by(group_id=group_id).all(), key=lambda f: f.id)]))+ legacy_tags = json.loads(json.dumps(+ [t.to_dict() for t in sorted(Tag.query.filter_by(group_id=group_id).all(), key=lambda t: t.id)]))+ assert _get(w["viewer"], f"/api/groups/{group_id}/folders")["folders"] == legacy_folders+ assert _get(w["viewer"], f"/api/groups/{group_id}/tags")["tags"] == legacy_tags+ assert [t["name"] for t in legacy_tags] == ["TeamTag"]+++def test_shares_overview_matches_the_per_row_path(world):+ w = world+ for show in (False, True):+ with patch.object(shares_module, "SHOW_USERNAMES_IN_UI", show):+ body = _get(w["viewer"], "/api/shares/overview")+ assert body == _legacy_overview(w["viewer"])+ assert [e["recording_id"] for e in body["shared_by_me"]] == [w["a"]]+ assert len(body["shared_by_me"][0]["recipients"]) == 2 and len(body["public_links"]) == 1+ sources = {s["recording_id"]: s["source"] for s in body["shared_with_me"]}+ assert sources[w["s2"]] == {"type": "group_tag", "name": "AdminTag"}+ assert sources[w["s5"]] == {"type": "group_folder", "name": "TeamFolder"}+ assert sources[w["s1"]] == {"type": "manual", "name": None}++[email protected]("kind", ["owned_rich", "shared_rich"])+def test_full_list_tag_folder_and_overview_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)+ paths = ["/api/tags", "/api/folders", "/api/shares/overview"]+ if kind.startswith("owned"):+ paths.append("/recordings")+ try:+ counts = {}+ with sharing_on(), folders_on():+ for viewer, n in ((small_viewer, 25), (large_viewer, 100)):+ for path in paths:+ resp = lambda: _get(viewer, path)+ resp()+ with count_statements() as statements:+ body = resp()+ assert body, path+ counts[path, n] = len(statements)+ print(kind, counts)+ for (path, n), count in counts.items():+ assert count == counts[path, 25], (path, counts)+ assert count <= STATEMENT_BOUND+ finally:+ _cleanup(small_users + large_users, small_groups + large_groups)