Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
API v1: scope=own|shared|all on the list, the changes feed and search (mailr spec G4)
Murtaza Nasirf299652ad26c
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex 55d6b37d..b8b7b2ee 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -409,6 +409,8 @@ GET /api/v1/recordings| `date_field` | string | `created_at` | What `date_from` and `date_to` filter: `created_at` or `meeting_date` || `updated_since` | string | - | Only recordings changed after this time (ISO 8601). Deletions are not listed; use the [changes feed](#changes-feed) for those. || `external_system`, `external_ref`, `external_kind` | string | - | Only recordings that carry this [external reference](#external-references) of yours (`external_kind` optional) |+| `scope` | string | `own` | `own`, `shared` (recordings other users shared with you) or `all` |+| `owner_id` | integer | - | Only recordings of this owner || `tag_id` | integer | - | Filter by tag ID || `q` | string | - | Search query (title, participants) || `inbox` | boolean | - | Filter by inbox status |@@ -462,6 +464,19 @@ GET /api/v1/recordings}```+**Shared recordings.** With `scope=shared` or `scope=all` the list includes completed recordings other users shared with you (shared directly, through a group tag or through a group folder), as the web app's shared list does. Every item says whose it is:++```json+{+ "is_shared": true,+ "owner": {"id": 3, "username": "evan", "name": "Evan Ross"},+ "share": {"id": 51, "can_edit": false, "can_reshare": false, "source": "group_tag",+ "shared_at": "2026-09-20T10:00:00.000000Z"}+}+```++Your own recordings have `"is_shared": false, "owner": null, "share": null`. `owner.username` and `owner.name` are `null` unless the administrator sets `SHOW_USERNAMES_IN_UI=true`. For a shared recording, `is_inbox`, `is_highlighted` and `is_archived` are your own values and `tags` are the tags you can see. With internal sharing turned off, `shared` is empty and `all` is the same as `own`.+`updated_at` is the time of the last change a client can see: title, participants, notes, summary, transcript, status, dates, folder, flags, tags, events or sharing. It is present on every recording in API v1 and starts at `created_at`.### External References@@ -528,7 +543,7 @@ Every create, edit and delete of your recordings since a cursor, each once and i|-----------|------|---------|-------------|| `cursor` | string | - | `next_cursor` from the previous answer. Without it, the answer lists every recording (a full pass) and no older deletions. || `limit` | integer | 100 | 1 to 500 |-| `scope` | string | `own` | `own` |+| `scope` | string | `own` | `own`, `shared` or `all`. With `shared` or `all`, a share that is removed arrives as a delete with reason `access_revoked`. |**Response:**@@ -881,7 +896,7 @@ Finds words in the titles, participants, notes, summaries and transcripts of you| `q` | string | required | 2 to 500 characters. Words are matched separately; `"a quoted phrase"` stays together. Every word must appear in the recording. `%` and `_` are literal. || `mode` | string | `keyword` | `keyword`, `semantic`, or `auto` (semantic when available, else keyword) || `fields` | string | all | Comma list of `title`, `participants`, `notes`, `summary`, `transcript` (keyword mode) |-| `scope` | string | `own` | `own` |+| `scope` | string | `own` | `own`, `shared` or `all` (see [List Recordings](#list-recordings)) || `recording_ids` | string | - | Comma list of recording ids || `tag_id`, `folder_id` | - | - | As on [List Recordings](#list-recordings) || `speaker` | string | - | Transcript hits of this speaker only (exact name, any case) |diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 6eaf508e..6281dbf1 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -154,7 +154,11 @@ OPENAPI_SPEC = {"events": {"type": "array", "description": "Calendar events extracted from the recording (detail endpoint only)", "items": {"type": "object"}},"tags": {"type": "array", "items": {"$ref": "#/components/schemas/Tag"}},"keep_audio_only": {"type": "boolean", "description": "True if the upload was processed in audio-only mode (video stream discarded). Set at upload time; immutable via PATCH."},- "updated_at": {"type": "string", "format": "date-time", "description": "Last change a client can see; starts at created_at"}+ "updated_at": {"type": "string", "format": "date-time", "description": "Last change a client can see; starts at created_at"},+ "is_shared": {"type": "boolean"},+ "owner": {"type": "object", "nullable": True},+ "share": {"type": "object", "nullable": True},+ "external_refs": {"type": "array", "items": {"type": "object"}}}},"Tag": {@@ -285,7 +289,7 @@ OPENAPI_SPEC = {"parameters": [{"name": "cursor", "in": "query", "schema": {"type": "string"}},{"name": "limit", "in": "query", "schema": {"type": "integer", "default": 100, "minimum": 1, "maximum": 500}},- {"name": "scope", "in": "query", "schema": {"type": "string", "enum": ["own"], "default": "own"}}+ {"name": "scope", "in": "query", "schema": {"type": "string", "enum": ["own", "shared", "all"], "default": "own"}}],"responses": {"200": {"description": "A page of changes", "content": {"application/json": {"schema": {@@ -332,6 +336,8 @@ OPENAPI_SPEC = {{"name": "sort_by", "in": "query", "schema": {"type": "string", "enum": ["created_at", "meeting_date", "title", "file_size", "status", "updated_at"]}},{"name": "updated_since", "in": "query", "schema": {"type": "string", "format": "date-time"}, "description": "Only recordings changed after this time"},{"name": "date_field", "in": "query", "schema": {"type": "string", "enum": ["created_at", "meeting_date"], "default": "created_at"}, "description": "What date_from and date_to filter"},+ {"name": "scope", "in": "query", "schema": {"type": "string", "enum": ["own", "shared", "all"], "default": "own"}},+ {"name": "owner_id", "in": "query", "schema": {"type": "integer"}},{"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."},@@ -1009,7 +1015,7 @@ def _updated_at_z(recording):return iso_z(effective_updated_at(recording))-def _recording_list_item(r, refs=None):+def _recording_list_item(r, refs=None, shared=None):"""One recording as GET /recordings lists it; the changes feed uses the same shape.refs: this caller's external references of the recording, when the caller@@ -1047,7 +1053,10 @@ def _recording_list_item(r, refs=None):'keep_audio_only': r.keep_audio_only,'updated_at': iso_z(effective_updated_at(r)),'external_refs': refs,- }+ 'is_shared': False,+ 'owner': None,+ 'share': None,+ } if shared is None else dict(_recording_list_item(r, refs), **shared)@api_v1_bp.route('/recordings', methods=['GET'])@@ -1070,6 +1079,8 @@ def list_recordings():inbox: Filter by inbox status (true/false)starred: Filter by starred status (true/false)archived: Filter by archive status (true/false); omitted returns both+ scope: own (default), shared or all+ owner_id: Only recordings of this ownerupdated_since: Only recordings changed after this time (ISO 8601)date_field: What date_from and date_to filter: created_at (default)or meeting_date@@ -1089,6 +1100,11 @@ def list_recordings():starred_filter = request.args.get('starred')archived_filter = request.args.get('archived')updated_since = request.args.get('updated_since')+ from src.services.recording_scope import SCOPES, join_personal_state, personal_flag, scope_condition+ scope = request.args.get('scope', 'own')+ if scope not in SCOPES:+ return jsonify({'error': 'scope must be own, shared or all', 'code': 'invalid_parameter'}), 400+ owner_id = request.args.get('owner_id', type=int)date_field = request.args.get('date_field', 'created_at')if date_field not in ('created_at', 'meeting_date'):return jsonify({'error': "date_field must be created_at or meeting_date",@@ -1108,8 +1124,12 @@ def list_recordings():joinedload(Recording.folder),joinedload(Recording.tag_associations).joinedload(RecordingTag.tag),)- .filter(Recording.user_id == current_user.id)+ .filter(scope_condition(current_user.id, scope)))+ if scope != 'own':+ query = join_personal_state(query, current_user.id)+ if owner_id is not None:+ query = query.filter(Recording.user_id == owner_id)# Status filterif status_filter == 'pending':@@ -1195,21 +1215,24 @@ def list_recordings():))- # Inbox filter+ # Inbox and starred filters: the caller's own value (a recipient's is on+ # SharedRecordingState).if inbox_filter is not None:is_inbox = inbox_filter.lower() == 'true'- query = query.filter(Recording.is_inbox == is_inbox)+ query = query.filter((personal_flag(current_user.id, 'is_inbox', True) if scope != 'own'+ else Recording.is_inbox) == is_inbox)- # Starred filterif starred_filter is not None:is_starred = starred_filter.lower() == 'true'- query = query.filter(Recording.is_highlighted == is_starred)+ query = query.filter((personal_flag(current_user.id, 'is_highlighted', False) if scope != 'own'+ else 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)+ query = query.filter((personal_flag(current_user.id, 'is_archived', False) if scope != 'own'+ else db.func.coalesce(Recording.is_archived, False)) == is_archived)# Sortingsort_columns = {@@ -1232,8 +1255,11 @@ def list_recordings():# Build responsefrom src.services.external_refs import refs_map+ from src.services.recording_scope import share_detailspage_refs = refs_map([r.id for r in pagination.items], current_user.id)- recordings = [_recording_list_item(r, page_refs.get(r.id, [])) for r in pagination.items]+ page_shared = share_details(pagination.items, current_user)+ recordings = [_recording_list_item(r, page_refs.get(r.id, []), page_shared.get(r.id))+ for r in pagination.items]return jsonify({'recordings': recordings,@@ -1302,8 +1328,9 @@ def search_recordings_v1():mode = args.get('mode', 'keyword')if mode not in ('keyword', 'semantic', 'auto'):return jsonify({'error': 'mode must be keyword, semantic or auto', 'code': 'invalid_parameter'}), 400- if args.get('scope', 'own') != 'own':- return jsonify({'error': "scope must be 'own'", 'code': 'invalid_parameter'}), 400+ scope = args.get('scope', 'own')+ if scope not in ('own', 'shared', 'all'):+ return jsonify({'error': 'scope must be own, shared or all', 'code': 'invalid_parameter'}), 400fields = tuple(f.strip() for f in args.get('fields', ','.join(search_v1.FIELDS)).split(',') if f.strip())unknown = [f for f in fields if f not in search_v1.FIELDS]if unknown or not fields:@@ -1331,7 +1358,7 @@ def search_recordings_v1():return jsonify({'error': 'folder_id must be an id or none', 'code': 'invalid_parameter'}), 400filters = dict(recording_ids=recording_ids, tag_id=args.get('tag_id', type=int), folder_id=folder_id,date_from=args.get('date_from') or None, date_to=args.get('date_to') or None,- date_field=date_field)+ date_field=date_field, scope=scope)speaker = (args.get('speaker') or '').strip() or Noneuse_semantic = mode == 'semantic' or (mode == 'auto' and search_v1.semantic_available())@@ -1448,8 +1475,8 @@ def list_recording_changes():if limit is None or not 1 <= limit <= 500:return jsonify({'error': 'limit must be between 1 and 500', 'code': 'invalid_parameter'}), 400scope = request.args.get('scope', 'own')- if scope != 'own':- return jsonify({'error': "scope must be 'own'", 'code': 'invalid_parameter'}), 400+ if scope not in ('own', 'shared', 'all'):+ return jsonify({'error': 'scope must be own, shared or all', 'code': 'invalid_parameter'}), 400if cursor:try:changed_at, _, _, full_since = decode_cursor(cursor)@@ -1458,13 +1485,17 @@ def list_recording_changes():if cursor_expired(current_user.id, changed_at, full_since):return jsonify({'error': 'The cursor is too old; start again without a cursor','code': 'cursor_expired'}), 410- items, next_cursor, has_more = read_changes(current_user.id, cursor=cursor, limit=limit)+ items, next_cursor, has_more = read_changes(current_user.id, cursor=cursor, limit=limit, scope=scope)from src.services.external_refs import refs_map- page_refs = refs_map([obj.id for kind, obj in items if kind == 'upsert'], current_user.id)+ from src.services.recording_scope import share_details+ upserts = [obj for kind, obj in items if kind == 'upsert']+ page_refs = refs_map([obj.id for obj in upserts], current_user.id)+ page_shared = share_details(upserts, current_user)changes = []for kind, obj in items:if kind == 'upsert':- changes.append({'type': 'upsert', 'recording': _recording_list_item(obj, page_refs.get(obj.id, []))})+ changes.append({'type': 'upsert', 'recording': _recording_list_item(+ obj, page_refs.get(obj.id, []), page_shared.get(obj.id))})else:changes.append({'type': 'delete', 'id': obj.recording_id,'deleted_at': iso_z(obj.deleted_at), 'reason': obj.reason})diff --git a/src/services/recording_changes.py b/src/services/recording_changes.pyindex bd3018f8..f3464ab2 100644--- a/src/services/recording_changes.py+++ b/src/services/recording_changes.py@@ -302,7 +302,7 @@ def cursor_expired(user_id, changed_at, full_since):return False-def read_changes(user_id, cursor=None, limit=100, now=None):+def read_changes(user_id, cursor=None, limit=100, now=None, scope='own'):"""One page of the feed. Returns (items, next_cursor, has_more); each itemis ('upsert', Recording) or ('delete', RecordingTombstone).@@ -320,13 +320,17 @@ def read_changes(user_id, cursor=None, limit=100, now=None):key, full_since = None, now # a full pass: tombstones only from its startchanged = func.coalesce(Recording.updated_at, Recording.created_at)- rq = Recording.query.filter(Recording.user_id == user_id, changed <= settle)+ from src.services.recording_scope import scope_condition+ rq = Recording.query.filter(scope_condition(user_id, scope), changed <= settle)if key:rq = rq.filter(_after(changed, Recording.id, _UPSERT, key))recs = rq.order_by(changed.asc(), Recording.id.asc()).limit(limit + 1).all()tq = RecordingTombstone.query.filter(RecordingTombstone.user_id == user_id,RecordingTombstone.deleted_at <= settle)+ if scope == 'own':+ # access_revoked concerns recordings shared with the user+ tq = tq.filter(RecordingTombstone.reason != 'access_revoked')if full_since is not None:tq = tq.filter(RecordingTombstone.deleted_at >= full_since)if key:diff --git a/src/services/recording_scope.py b/src/services/recording_scope.pynew file mode 100644index 00000000..da7beb27--- /dev/null+++ b/src/services/recording_scope.py@@ -0,0 +1,94 @@+"""Which recordings an API v1 list covers: own, shared with the caller, or+both (mailr spec G4).++Shared means an InternalShare for the caller (manual, group tag and group+folder shares all create one) on a completed recording, as in the web app's+shared-with-me list. With internal sharing off, shared is empty and all+equals own.+"""++import os++from sqlalchemy import and_, case, func, or_++from src.database import db++SCOPES = ('own', 'shared', 'all')+++def sharing_enabled():+ from src import app as app_module+ return bool(getattr(app_module, 'ENABLE_INTERNAL_SHARING', False))+++def _show_usernames():+ return os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'+++def scope_condition(user_id, scope):+ """SQL condition on Recording for the scope."""+ from src.models import InternalShare, Recording+ own = Recording.user_id == user_id+ if scope == 'own' or not sharing_enabled():+ return own if scope != 'shared' else Recording.id.is_(None)+ shared = and_(+ Recording.id.in_(db.session.query(InternalShare.recording_id)+ .filter(InternalShare.shared_with_user_id == user_id)),+ Recording.user_id != user_id,+ Recording.status == 'COMPLETED',+ )+ return shared if scope == 'shared' else or_(own, shared)+++def personal_flag(user_id, column_name, default):+ """The caller's value of is_inbox / is_highlighted / is_archived: the+ recording's own for the owner, SharedRecordingState for a recipient.+ Use with an outer join on SharedRecordingState for this user."""+ from src.models import Recording, SharedRecordingState+ return case((Recording.user_id == user_id, func.coalesce(getattr(Recording, column_name), default)),+ else_=func.coalesce(getattr(SharedRecordingState, column_name), default))+++def join_personal_state(query, user_id):+ from src.models import Recording, SharedRecordingState+ return query.outerjoin(SharedRecordingState, and_(SharedRecordingState.recording_id == Recording.id,+ SharedRecordingState.user_id == user_id))+++def share_details(recordings, user):+ """{recording id: dict of is_shared, owner, share, flags, tags} for the+ recordings of one page that are shared with user."""+ from src.models import InternalShare, SharedRecordingState, User+ shared_ids = [r.id for r in recordings if r.user_id != user.id]+ if not shared_ids:+ return {}+ shares = {s.recording_id: s for s in InternalShare.query.filter(+ InternalShare.recording_id.in_(shared_ids), InternalShare.shared_with_user_id == user.id)}+ 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}))}+ show = _show_usernames()+ details = {}+ for r in recordings:+ share = shares.get(r.id)+ if share is None:+ continue+ owner = owners.get(r.user_id)+ state = states.get(r.id)+ details[r.id] = {+ 'is_shared': True,+ 'owner': {'id': r.user_id,+ 'username': owner.username if (owner and show) else None,+ 'name': owner.name if (owner and show) else None},+ 'share': {'id': share.id, 'can_edit': bool(share.can_edit), 'can_reshare': bool(share.can_reshare),+ 'source': share.source_type or 'manual',+ 'shared_at': share.created_at.strftime('%Y-%m-%dT%H:%M:%S.%fZ') if share.created_at else None},+ '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)],+ }+ return details+++OWN_ITEM = {'is_shared': False, 'owner': None, 'share': None}diff --git a/src/services/search_v1.py b/src/services/search_v1.pyindex b535e181..8b746115 100644--- a/src/services/search_v1.py+++ b/src/services/search_v1.py@@ -117,9 +117,10 @@ def _parse_date(value, end_of_day=False):def candidate_query(user, terms, fields, recording_ids=None, tag_id=None, folder_id=None,- date_from=None, date_to=None, date_field='meeting_date'):+ date_from=None, date_to=None, date_field='meeting_date', scope='own'):from src.models import Recording, RecordingTag- query = Recording.query.filter(Recording.user_id == user.id) # scope=own (G4 adds shared)+ from src.services.recording_scope import scope_condition+ query = Recording.query.filter(scope_condition(user.id, scope))if recording_ids:query = query.filter(Recording.id.in_(recording_ids))if tag_id:@@ -202,10 +203,11 @@ def semantic_available():def semantic_search(user, query_text, limit=20, recording_ids=None, tag_id=None, date_from=None,- date_to=None, speaker=None, **_ignored):+ date_to=None, speaker=None, scope='own', **_ignored):from src.models import Recordingfrom src.services.embeddings import semantic_search_chunks- own = [rid for (rid,) in db.session.query(Recording.id).filter(Recording.user_id == user.id)]+ from src.services.recording_scope import scope_condition+ own = [rid for (rid,) in db.session.query(Recording.id).filter(scope_condition(user.id, scope))]if recording_ids:own = [rid for rid in own if rid in set(recording_ids)]if not own:diff --git a/tests/test_api_v1_shared_scope.py b/tests/test_api_v1_shared_scope.pynew file mode 100644index 00000000..a6be519d--- /dev/null+++ b/tests/test_api_v1_shared_scope.py@@ -0,0 +1,144 @@+"""scope=own|shared|all on the list, the changes feed and search (mailr spec G4).++SHARED-DB: users, tokens, shares, states and recordings are removed afterwards.+"""++import json+import os+import secrets+import sys+from unittest.mock import patch++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import (APIToken, InternalShare, Recording, RecordingTombstone, SharedRecordingState, User)+from src.services import recording_changes as rc+from src.utils.token_auth import hash_token+++def world():+ with app.app_context():+ s = secrets.token_hex(4)+ me = User(username=f"sc_{s}", email=f"sc_{s}@local.test", password="x", name="Me Myself")+ evan = User(username=f"evan_{s}", email=f"evan_{s}@local.test", password="x", name="Evan Ross")+ db.session.add_all([me, evan])+ db.session.commit()+ mine = Recording(user_id=me.id, title="Mine budget", status="COMPLETED", original_filename="a.wav",+ transcription="We discussed the budget.")+ manual = Recording(user_id=evan.id, title="Manual budget", status="COMPLETED", original_filename="b.wav",+ transcription="The budget freeze.")+ by_tag = Recording(user_id=evan.id, title="Tag share", status="COMPLETED", original_filename="c.wav")+ by_folder = Recording(user_id=evan.id, title="Folder share", status="COMPLETED", original_filename="d.wav")+ busy = Recording(user_id=evan.id, title="Still processing", status="PROCESSING", original_filename="e.wav")+ private = Recording(user_id=evan.id, title="Evan only", status="COMPLETED", original_filename="f.wav")+ db.session.add_all([mine, manual, by_tag, by_folder, busy, private])+ db.session.commit()+ for rec, source in ((manual, "manual"), (by_tag, "group_tag"), (by_folder, "group_folder"), (busy, "manual")):+ db.session.add(InternalShare(recording_id=rec.id, owner_id=evan.id, shared_with_user_id=me.id,+ can_edit=(source == "manual"), source_type=source))+ db.session.add(SharedRecordingState(recording_id=manual.id, user_id=me.id, is_inbox=False,+ is_highlighted=True, is_archived=False))+ plain = f"tok-{secrets.token_urlsafe(16)}"+ db.session.add(APIToken(user_id=me.id, token_hash=hash_token(plain), name="sc"))+ db.session.commit()+ ids = dict(me=me.id, evan=evan.id, mine=mine.id, manual=manual.id, by_tag=by_tag.id,+ by_folder=by_folder.id, busy=busy.id, private=private.id, token=plain)+ with patch("src.app.ENABLE_INTERNAL_SHARING", True):+ yield ids+ with app.app_context():+ db.session.rollback()+ users = [ids["me"], ids["evan"]]+ recs = [r.id for r in Recording.query.filter(Recording.user_id.in_(users))]+ SharedRecordingState.query.filter(SharedRecordingState.recording_id.in_(recs)).delete(synchronize_session=False)+ InternalShare.query.filter(InternalShare.recording_id.in_(recs)).delete(synchronize_session=False)+ Recording.query.filter(Recording.id.in_(recs)).delete(synchronize_session=False)+ RecordingTombstone.query.filter(RecordingTombstone.user_id.in_(users)).delete(synchronize_session=False)+ APIToken.query.filter(APIToken.user_id.in_(users)).delete(synchronize_session=False)+ User.query.filter(User.id.in_(users)).delete(synchronize_session=False)+ db.session.commit()+++def _get(world, path):+ with app.test_client() as c:+ resp = c.get(path, headers={"Authorization": f"Bearer {world['token']}"})+ assert resp.status_code == 200, resp.get_json()+ return resp.get_json()+++def _ids(body):+ return {r["id"] for r in body["recordings"]}+++def test_shared_lists_every_kind_of_share_but_not_processing(world):+ body = _get(world, "/api/v1/recordings?scope=shared")+ assert _ids(body) == {world["manual"], world["by_tag"], world["by_folder"]}+ item = next(r for r in body["recordings"] if r["id"] == world["manual"])+ assert item["is_shared"] is True and item["owner"]["id"] == world["evan"]+ assert item["share"]["source"] == "manual" and item["share"]["can_edit"] is True+ assert item["share"]["shared_at"].endswith("Z")+ assert (item["is_inbox"], item["is_highlighted"]) == (False, True) # the recipient's own flags+ sources = {r["id"]: r["share"]["source"] for r in body["recordings"]}+ assert sources[world["by_tag"]] == "group_tag" and sources[world["by_folder"]] == "group_folder"+++def test_own_is_the_default_and_all_merges(world):+ own = _get(world, "/api/v1/recordings")+ assert _ids(own) == {world["mine"]} and own["recordings"][0]["is_shared"] is False+ assert own["recordings"][0]["owner"] is None and own["recordings"][0]["share"] is None+ every = _get(world, "/api/v1/recordings?scope=all")+ assert _ids(every) == {world["mine"], world["manual"], world["by_tag"], world["by_folder"]}+ pages, seen = 0, set()+ for page in (1, 2, 3, 4):+ body = _get(world, f"/api/v1/recordings?scope=all&per_page=1&page={page}")+ seen |= _ids(body)+ assert seen == _ids(every) and body["pagination"]["total"] == 4+++def test_filters_on_the_shared_list(world):+ assert _ids(_get(world, "/api/v1/recordings?scope=all&starred=true")) == {world["manual"]}+ assert world["manual"] not in _ids(_get(world, "/api/v1/recordings?scope=all&inbox=true"))+ assert _ids(_get(world, f"/api/v1/recordings?scope=all&owner_id={world['me']}")) == {world["mine"]}+++def test_sharing_off_gives_nothing_shared(world):+ with patch("src.app.ENABLE_INTERNAL_SHARING", False):+ assert _get(world, "/api/v1/recordings?scope=shared")["recordings"] == []+ assert _ids(_get(world, "/api/v1/recordings?scope=all")) == {world["mine"]}+++def test_owner_names_follow_the_ui_setting(world):+ with patch.dict(os.environ, {"SHOW_USERNAMES_IN_UI": "false"}):+ hidden = _get(world, "/api/v1/recordings?scope=shared")["recordings"][0]["owner"]+ assert hidden["username"] is None and hidden["name"] is None+ with patch.dict(os.environ, {"SHOW_USERNAMES_IN_UI": "true"}):+ shown = next(r for r in _get(world, "/api/v1/recordings?scope=shared")["recordings"]+ if r["id"] == world["manual"])["owner"]+ assert shown["name"] == "Evan Ross" and shown["username"].startswith("evan_")+++def test_the_feed_reports_a_revoked_share(world):+ with patch.object(rc, "SETTLE_SECONDS", 0):+ start = _get(world, "/api/v1/recordings/changes?scope=all")+ assert {c["recording"]["id"] for c in start["changes"]} == {world["mine"], world["manual"], world["by_tag"],+ world["by_folder"]}+ with app.app_context():+ db.session.delete(InternalShare.query.filter_by(recording_id=world["by_tag"]).one())+ db.session.commit()+ after = _get(world, f"/api/v1/recordings/changes?scope=all&cursor={start['next_cursor']}")+ own = _get(world, f"/api/v1/recordings/changes?scope=own&cursor={start['next_cursor']}")+ revoked = [c for c in after["changes"] if c["type"] == "delete"]+ assert [(c["id"], c["reason"]) for c in revoked] == [(world["by_tag"], "access_revoked")]+ assert not [c for c in own["changes"] if c["type"] == "delete"]+++def test_search_scope(world):+ own = _get(world, "/api/v1/search?q=budget")+ shared = _get(world, "/api/v1/search?q=budget&scope=shared")+ every = _get(world, "/api/v1/search?q=budget&scope=all")+ assert {h["recording_id"] for h in own["results"]} == {world["mine"]}+ assert {h["recording_id"] for h in shared["results"]} == {world["manual"]}+ assert {h["recording_id"] for h in every["results"]} == {world["mine"], world["manual"]}