Skip to content

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

Python

API v1 tag writes: edit access on POST, PUT to set the tags, group-tag shares as in the web app, ?name= on GET /tags (mailr spec section 8)

Murtaza Nasir68fcdecfcc6b
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index 10e64ebc..e590743c 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -933,7 +933,7 @@ GET /api/v1/tags
**Scope:** `read`
-Returns both personal tags and group tags you have access to.
+Returns both personal tags and group tags you have access to. `?name=` returns only the tag with that name (any case), so a client can find a tag by name.
**Response:**
@@ -1021,6 +1021,36 @@ POST /api/v1/recordings/{id}/tags
}
```
+Adds the tags after the ones already on the recording. Needs edit access to the recording. A group tag can be applied by the recording's owner or a group admin.
+
+**Tags that share.** A group tag with *auto-share on apply* (or *share with group lead*) shares a completed recording with the group, as in the web app: admins get edit access, members read access. A scoped token needs the `share` scope for such a tag; without it the request gets `403 insufficient_scope` and nothing changes.
+
+### Set Recording Tags
+
+```http
+PUT /api/v1/recordings/{id}/tags
+```
+
+**Scope:** `write`
+
+Sets the recording's tags to exactly this list, in this order. The access and sharing rules of Add Tags apply. Tags of other users that you cannot see stay on the recording.
+
+```json
+{"tag_ids": [3, 9]}
+```
+
+**Response:**
+
+```json
+{
+ "tags": [{"id": 3, "name": "Followed up", "color": "#10B981"}, {"id": 9, "name": "Client", "color": "#3B82F6"}],
+ "added": [9],
+ "removed": [4]
+}
+```
+
+An unknown tag, or one you cannot use, gives `400` with `"code": "invalid_parameter"` and the refused ids in `tag_ids`; nothing changes.
+
### Remove Tag from Recording
```http
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index b8ddf6dc..40730deb 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -2030,6 +2030,9 @@ def list_tags():
'can_edit': (user_role == 'admin')
})
+ name = (request.args.get('name') or '').strip().lower()
+ if name:
+ result = [t for t in result if (t['name'] or '').strip().lower() == name]
return jsonify({'tags': result})
@@ -2187,21 +2190,49 @@ def delete_tag(tag_id):
return jsonify({'success': True, 'message': 'Tag deleted'})
+
+def _tag_problem(recording, tag):
+ """Why the caller may not apply tag to recording, or None."""
+ from src.models.organization import GroupMembership
+ if tag is None:
+ return 'not found'
+ if tag.group_id:
+ membership = GroupMembership.query.filter_by(group_id=tag.group_id, user_id=current_user.id).first()
+ if not membership:
+ return 'no access'
+ if recording.user_id != current_user.id and membership.role != 'admin':
+ return 'only the recording owner or a group admin can apply group tags'
+ return None
+ return None if tag.user_id == current_user.id else 'no access'
+
+
+def _share_scope_refusal(recording, tags):
+ """403 when applying these tags would share the recording and the token
+ lacks the share scope (mailr spec section 8); nothing has changed yet."""
+ from src.services.tag_sharing import share_targets
+ from src.utils.token_auth import current_api_token, scope_error_response
+ token = current_api_token()
+ if token is None or token.scope_set is None or 'share' in token.scope_set:
+ return None
+ if any(share_targets(recording, tag) for tag in tags):
+ return scope_error_response({'share'}, token)
+ return None
+
+
@api_v1_bp.route('/recordings/<int:recording_id>/tags', methods=['POST'])
@require_scope('write')
@login_required
def add_tags_to_recording(recording_id):
- """Add tag(s) to a recording."""
- from src.models.organization import GroupMembership
-
+ """Add tag(s) to a recording. Needs edit access; a group tag that shares
+ the recording also needs the share scope on a scoped token."""
recording = db.session.get(Recording, recording_id)
if not recording:
return jsonify({'error': 'Recording not found'}), 404
- if not has_recording_access(recording, current_user):
+ if not has_recording_access(recording, current_user, require_edit=True):
return jsonify({'error': 'Permission denied'}), 403
- data = request.get_json()
+ data = request.get_json() or {}
tag_ids = data.get('tag_ids', [])
if not tag_ids:
# Support single tag_id for backward compatibility
@@ -2211,48 +2242,29 @@ def add_tags_to_recording(recording_id):
else:
return jsonify({'error': 'tag_ids or tag_id required'}), 400
- added_tags = []
errors = []
-
+ to_add = []
+ present = {rt.tag_id for rt in RecordingTag.query.filter_by(recording_id=recording_id)}
for tag_id in tag_ids:
tag = db.session.get(Tag, tag_id)
- if not tag:
+ problem = _tag_problem(recording, tag)
+ if problem == 'not found':
errors.append(f'Tag {tag_id} not found')
- continue
-
- # Check permission for this tag
- if tag.group_id:
- membership = GroupMembership.query.filter_by(
- group_id=tag.group_id,
- user_id=current_user.id
- ).first()
- if not membership:
- errors.append(f'No access to tag {tag_id}')
- continue
- else:
- if tag.user_id != current_user.id:
- errors.append(f'No access to tag {tag_id}')
- continue
-
- # Check if already exists
- existing = RecordingTag.query.filter_by(
- recording_id=recording_id,
- tag_id=tag_id
- ).first()
- if existing:
- continue # Skip, already added
+ elif problem:
+ errors.append(f'No access to tag {tag_id}')
+ elif tag.id not in present and tag not in to_add:
+ to_add.append(tag)
- # Get next order position
- max_order = db.session.query(func.max(RecordingTag.order)).filter_by(
- recording_id=recording_id
- ).scalar() or 0
+ refusal = _share_scope_refusal(recording, to_add)
+ if refusal is not None:
+ return refusal
- recording_tag = RecordingTag(
- recording_id=recording_id,
- tag_id=tag_id,
- order=max_order + 1
- )
- db.session.add(recording_tag)
+ from src.services.tag_sharing import apply_tag_shares
+ max_order = db.session.query(func.max(RecordingTag.order)).filter_by(recording_id=recording_id).scalar() or 0
+ added_tags = []
+ for offset, tag in enumerate(to_add, 1):
+ db.session.add(RecordingTag(recording_id=recording_id, tag_id=tag.id, order=max_order + offset))
+ apply_tag_shares(recording, tag)
added_tags.append({'id': tag.id, 'name': tag.name})
db.session.commit()
@@ -2264,6 +2276,72 @@ def add_tags_to_recording(recording_id):
})
+@api_v1_bp.route('/recordings/<int:recording_id>/tags', methods=['PUT'])
+@require_scope('write')
+@login_required
+def replace_recording_tags(recording_id):
+ """Set the recording's tags to exactly tag_ids, in that order.
+
+ Tags the caller cannot see (another user's personal tags) stay on the
+ recording. An unknown or forbidden id refuses the whole request.
+ """
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found', 'code': 'not_found'}), 404
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'Permission denied'}), 403
+ data = request.get_json(silent=True) or {}
+ tag_ids = data.get('tag_ids')
+ if not isinstance(tag_ids, list) or not all(isinstance(t, int) and not isinstance(t, bool) for t in tag_ids):
+ return jsonify({'error': 'tag_ids must be a list of tag ids', 'code': 'invalid_parameter'}), 400
+ wanted, bad = [], []
+ for tag_id in dict.fromkeys(tag_ids):
+ tag = db.session.get(Tag, tag_id)
+ if _tag_problem(recording, tag):
+ bad.append(tag_id)
+ else:
+ wanted.append(tag)
+ if bad:
+ return jsonify({'error': 'Unknown or forbidden tag ids', 'code': 'invalid_parameter',
+ 'tag_ids': bad}), 400
+
+ visible = {t.id for t in recording.get_visible_tags(current_user)}
+ current = RecordingTag.query.filter_by(recording_id=recording_id).order_by(RecordingTag.order).all()
+ current_ids = [rt.tag_id for rt in current]
+ added = [t for t in wanted if t.id not in current_ids]
+ removed = [rt.tag_id for rt in current if rt.tag_id in visible and rt.tag_id not in {t.id for t in wanted}]
+
+ refusal = _share_scope_refusal(recording, added)
+ if refusal is not None:
+ return refusal
+
+ from src.services.tag_sharing import apply_tag_shares
+ for rt in current:
+ if rt.tag_id in removed:
+ db.session.delete(rt)
+ db.session.flush()
+ kept_hidden = [rt for rt in current if rt.tag_id not in visible]
+ by_id = {rt.tag_id: rt for rt in current if rt.tag_id not in removed}
+ order = 0
+ for tag in wanted:
+ order += 1
+ if tag.id in by_id:
+ if by_id[tag.id].order != order:
+ by_id[tag.id].order = order
+ else:
+ db.session.add(RecordingTag(recording_id=recording_id, tag_id=tag.id, order=order))
+ apply_tag_shares(recording, tag)
+ for rt in kept_hidden:
+ order += 1
+ rt.order = order
+ db.session.commit()
+ return jsonify({
+ 'tags': [{'id': t.id, 'name': t.name, 'color': t.color} for t in wanted],
+ 'added': [t.id for t in added],
+ 'removed': removed,
+ })
+
+
@api_v1_bp.route('/recordings/<int:recording_id>/tags/<int:tag_id>', methods=['DELETE'])
@require_scope('write')
@login_required
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 22735e39..51cd7df3 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -3975,64 +3975,12 @@ def add_tag_to_recording(recording_id):
)
db.session.add(recording_tag)
- # If this is a group tag with sharing enabled, automatically share the recording
- # Only auto-share if recording is completed (not during processing)
- if tag.group_id and ENABLE_INTERNAL_SHARING and recording.status == 'COMPLETED' and (tag.auto_share_on_apply or tag.share_with_group_lead):
- # Determine who to share with
- if tag.auto_share_on_apply:
- group_members = GroupMembership.query.filter_by(group_id=tag.group_id).all()
- elif tag.share_with_group_lead:
- group_members = GroupMembership.query.filter_by(group_id=tag.group_id, role='admin').all()
- else:
- group_members = []
-
- shares_created = 0
- for membership_to_share in group_members:
- # Skip the recording owner
- if membership_to_share.user_id == recording.user_id:
- continue
-
- # Check if already shared
- existing_share = InternalShare.query.filter_by(
- recording_id=recording_id,
- shared_with_user_id=membership_to_share.user_id
- ).first()
-
- if not existing_share:
- # Create internal share with correct permissions
- # Group admins get edit permission, regular members get read-only
- share = InternalShare(
- recording_id=recording_id,
- owner_id=recording.user_id,
- shared_with_user_id=membership_to_share.user_id,
- can_edit=(membership_to_share.role == 'admin'),
- can_reshare=False,
- source_type='group_tag',
- source_tag_id=tag.id
- )
- db.session.add(share)
-
- # Check if SharedRecordingState already exists (might exist from previous share)
- existing_state = SharedRecordingState.query.filter_by(
- recording_id=recording_id,
- user_id=membership_to_share.user_id
- ).first()
-
- if not existing_state:
- # Create SharedRecordingState with default values for the recipient
- state = SharedRecordingState(
- recording_id=recording_id,
- user_id=membership_to_share.user_id,
- is_inbox=True, # New shares appear in inbox by default
- is_highlighted=False # Not favorited by default
- )
- db.session.add(state)
-
- shares_created += 1
- current_app.logger.info(f"Auto-shared recording {recording_id} with user {membership_to_share.user_id} (role={membership_to_share.role}) via group tag '{tag.name}'")
-
- if shares_created > 0:
- current_app.logger.info(f"Created {shares_created} auto-shares for recording {recording_id} via group tag '{tag.name}'")
+ # A group tag with sharing shares the completed recording (same rule
+ # as API v1 and the end of processing: src/services/tag_sharing.py).
+ from src.services.tag_sharing import apply_tag_shares
+ shares_created = apply_tag_shares(recording, tag, sharing_enabled=ENABLE_INTERNAL_SHARING)
+ if shares_created > 0:
+ current_app.logger.info(f"Created {shares_created} auto-shares for recording {recording_id} via group tag '{tag.name}'")
db.session.commit()
diff --git a/src/services/tag_sharing.py b/src/services/tag_sharing.py
new file mode 100644
index 00000000..7fd37ba5
--- /dev/null
+++ b/src/services/tag_sharing.py
@@ -0,0 +1,68 @@
+"""Shares created by applying a group tag (one rule for every path).
+
+A group tag with auto_share_on_apply shares the recording with every member
+of the group; with share_with_group_lead, with the group's admins. Members
+who are admins get edit access, others read access. Only completed
+recordings are shared this way; recordings still processing get their
+shares when processing completes (apply_team_tag_auto_shares).
+
+The web route, API v1 (POST and PUT tags) and the end of processing call
+these functions, so a tag shares the same way wherever it is applied.
+"""
+
+from flask import current_app
+
+from src.database import db
+
+
+def _sharing_enabled(enabled):
+ if enabled is not None:
+ return bool(enabled)
+ from src import app as app_module
+ return bool(getattr(app_module, 'ENABLE_INTERNAL_SHARING', False))
+
+
+def share_targets(recording, tag, require_completed=True, sharing_enabled=None):
+ """Group memberships that applying tag would share the recording with.
+
+ sharing_enabled: the caller's ENABLE_INTERNAL_SHARING (None reads src.app's).
+ """
+ from src.models import GroupMembership, InternalShare
+ if not tag.group_id or not _sharing_enabled(sharing_enabled):
+ return []
+ if require_completed and recording.status != 'COMPLETED':
+ return []
+ if tag.auto_share_on_apply:
+ members = GroupMembership.query.filter_by(group_id=tag.group_id).all()
+ elif tag.share_with_group_lead:
+ members = GroupMembership.query.filter_by(group_id=tag.group_id, role='admin').all()
+ else:
+ return []
+ already = {uid for (uid,) in db.session.query(InternalShare.shared_with_user_id)
+ .filter(InternalShare.recording_id == recording.id)}
+ return [m for m in members if m.user_id != recording.user_id and m.user_id not in already]
+
+
+def apply_tag_shares(recording, tag, require_completed=True, sharing_enabled=None):
+ """Create the shares for one applied tag (no commit). Returns the count."""
+ from src.models import InternalShare, SharedRecordingState
+ created = 0
+ for membership in share_targets(recording, tag, require_completed=require_completed,
+ sharing_enabled=sharing_enabled):
+ db.session.add(InternalShare(
+ recording_id=recording.id,
+ owner_id=recording.user_id,
+ shared_with_user_id=membership.user_id,
+ can_edit=(membership.role == 'admin'),
+ can_reshare=False,
+ source_type='group_tag',
+ source_tag_id=tag.id,
+ ))
+ if not SharedRecordingState.query.filter_by(recording_id=recording.id, user_id=membership.user_id).first():
+ db.session.add(SharedRecordingState(recording_id=recording.id, user_id=membership.user_id,
+ is_inbox=True, is_highlighted=False))
+ created += 1
+ current_app.logger.info(f"Auto-shared recording {recording.id} with user {membership.user_id} "
+ f"(role={membership.role}) via group tag '{tag.name}'")
+ db.session.flush()
+ return created
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 703888f6..4f88b9ed 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -152,53 +152,11 @@ def apply_team_tag_auto_shares(recording_id):
if not group_tags:
return
+ from src.services.tag_sharing import apply_tag_shares
shares_created = 0
-
for tag in group_tags:
- # Determine who to share with
- if tag.auto_share_on_apply:
- group_members = GroupMembership.query.filter_by(group_id=tag.group_id).all()
- elif tag.share_with_group_lead:
- group_members = GroupMembership.query.filter_by(group_id=tag.group_id, role='admin').all()
- else:
- continue
-
- for membership in group_members:
- # Skip the recording owner
- if membership.user_id == recording.user_id:
- continue
-
- # Check if already shared
- existing_share = InternalShare.query.filter_by(
- recording_id=recording_id,
- shared_with_user_id=membership.user_id
- ).first()
-
- if not existing_share:
- # Create internal share with correct permissions
- # Group admins get edit permission, regular members get read-only
- share = InternalShare(
- recording_id=recording_id,
- owner_id=recording.user_id,
- shared_with_user_id=membership.user_id,
- can_edit=(membership.role == 'admin'),
- can_reshare=False,
- source_type='group_tag',
- source_tag_id=tag.id
- )
- db.session.add(share)
-
- # Create SharedRecordingState with default values for the recipient
- state = SharedRecordingState(
- recording_id=recording_id,
- user_id=membership.user_id,
- is_inbox=True, # New shares appear in inbox by default
- is_highlighted=False # Not favorited by default
- )
- db.session.add(state)
-
- shares_created += 1
- current_app.logger.info(f"Auto-shared recording {recording_id} with user {membership.user_id} (role={membership.role}) via group tag '{tag.name}'")
+ shares_created += apply_tag_shares(recording, tag, require_completed=False,
+ sharing_enabled=ENABLE_INTERNAL_SHARING)
if shares_created > 0:
db.session.commit()
diff --git a/tests/test_api_v1_scope_coverage.py b/tests/test_api_v1_scope_coverage.py
index 5e39cb47..a4ac8933 100644
--- a/tests/test_api_v1_scope_coverage.py
+++ b/tests/test_api_v1_scope_coverage.py
@@ -17,7 +17,7 @@ EXPECTED = {
"get_transcript", "get_summary", "get_notes", "get_recording_status", "list_tags", "list_folders",
"get_folder", "get_transcription_info", "list_speakers", "get_recording_speakers",
"get_recording_events", "download_events_ics", "download_audio"},
- "write": {"add_external_ref", "replace_external_refs", "delete_external_ref", "update_recording", "replace_notes", "replace_summary", "create_tag", "update_tag",
+ "write": {"replace_recording_tags", "add_external_ref", "replace_external_refs", "delete_external_ref", "update_recording", "replace_notes", "replace_summary", "create_tag", "update_tag",
"add_tags_to_recording", "remove_tag_from_recording", "create_folder", "update_folder",
"create_speaker", "update_speaker", "assign_speakers", "batch_update_recordings"},
"account": {"update_auto_summarization"},
diff --git a/tests/test_api_v1_tag_writes.py b/tests/test_api_v1_tag_writes.py
new file mode 100644
index 00000000..0cc99f6f
--- /dev/null
+++ b/tests/test_api_v1_tag_writes.py
@@ -0,0 +1,198 @@
+"""Tag writes in API v1 (mailr spec section 8).
+
+POST needs edit access; PUT sets the tags exactly; a group tag that shares
+the recording shares it the same way as the web app, and a scoped token
+needs the share scope for that. GET /tags?name= finds a tag by name.
+
+SHARED-DB: users, group, tags, shares, tokens, webhooks and the recording
+are removed afterwards.
+"""
+
+import json
+import os
+import secrets
+import sys
+from datetime import datetime
+from unittest.mock import patch
+
+import pytest
+from flask import g, has_app_context
+from flask.testing import FlaskClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import (APIToken, Group, GroupMembership, InternalShare, Recording, RecordingTag,
+ SharedRecordingState, Tag, User, Webhook, WebhookDelivery)
+from src.utils.token_auth import hash_token
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def world():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ owner = User(username=f"tw_{s}", email=f"tw_{s}@local.test", password="x")
+ viewer = User(username=f"twv_{s}", email=f"twv_{s}@local.test", password="x")
+ member = User(username=f"twm_{s}", email=f"twm_{s}@local.test", password="x")
+ db.session.add_all([owner, viewer, member])
+ db.session.commit()
+ group = Group(name=f"team-{s}")
+ db.session.add(group)
+ db.session.commit()
+ db.session.add_all([GroupMembership(group_id=group.id, user_id=owner.id, role="admin"),
+ GroupMembership(group_id=group.id, user_id=member.id, role="member")])
+ rec = Recording(user_id=owner.id, title="Sync", status="COMPLETED", original_filename="s.wav")
+ a = Tag(name=f"Followed up {s}", user_id=owner.id)
+ b = Tag(name=f"b-{s}", user_id=owner.id)
+ c = Tag(name=f"c-{s}", user_id=owner.id)
+ foreign = Tag(name=f"f-{s}", user_id=viewer.id)
+ team = Tag(name=f"team-tag-{s}", user_id=owner.id, group_id=group.id, auto_share_on_apply=True)
+ db.session.add_all([rec, a, b, c, foreign, team])
+ db.session.commit()
+ db.session.add(InternalShare(recording_id=rec.id, owner_id=owner.id, shared_with_user_id=viewer.id,
+ can_edit=False))
+ db.session.add(RecordingTag(recording_id=rec.id, tag_id=a.id, order=1))
+ tokens = {}
+ for key, user, scopes in (("full", owner, None), ("write", owner, ["read", "write"]),
+ ("share", owner, ["read", "write", "share"]), ("viewer", viewer, None)):
+ p = f"tok-{secrets.token_urlsafe(16)}"
+ db.session.add(APIToken(user_id=user.id, token_hash=hash_token(p), name=key,
+ scopes=None if scopes is None else json.dumps(scopes)))
+ tokens[key] = p
+ db.session.commit()
+ ids = dict(owner=owner.id, viewer=viewer.id, member=member.id, group=group.id, rec=rec.id, a=a.id,
+ b=b.id, c=c.id, foreign=foreign.id, team=team.id, tokens=tokens, suffix=s)
+ with patch("src.app.ENABLE_INTERNAL_SHARING", True), patch("src.api.recordings.ENABLE_INTERNAL_SHARING", True):
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ users = [ids["owner"], ids["viewer"], ids["member"]]
+ hooks = [w.id for w in Webhook.query.filter(Webhook.user_id.in_(users))]
+ WebhookDelivery.query.filter(WebhookDelivery.webhook_id.in_(hooks)).delete(synchronize_session=False)
+ Webhook.query.filter(Webhook.id.in_(hooks)).delete(synchronize_session=False)
+ RecordingTag.query.filter_by(recording_id=ids["rec"]).delete()
+ SharedRecordingState.query.filter_by(recording_id=ids["rec"]).delete()
+ InternalShare.query.filter_by(recording_id=ids["rec"]).delete()
+ Recording.query.filter_by(id=ids["rec"]).delete()
+ Tag.query.filter(Tag.user_id.in_(users)).delete(synchronize_session=False)
+ GroupMembership.query.filter_by(group_id=ids["group"]).delete()
+ Group.query.filter_by(id=ids["group"]).delete()
+ 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 _h(world, key="full"):
+ return {"Authorization": f"Bearer {world['tokens'][key]}"}
+
+
+def _tags(world):
+ with app.app_context():
+ return [rt.tag_id for rt in RecordingTag.query.filter_by(recording_id=world["rec"]).order_by(RecordingTag.order)]
+
+
+def _shared_with(world):
+ with app.app_context():
+ return {(s.shared_with_user_id, s.source_type) for s in InternalShare.query.filter_by(recording_id=world["rec"])}
+
+
+def test_a_view_only_recipient_cannot_add_tags(world):
+ with app.test_client() as c:
+ resp = c.post(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["foreign"]]},
+ headers=_h(world, "viewer"))
+ assert resp.status_code == 403 and world["foreign"] not in _tags(world)
+
+
+def test_put_replaces_in_order_and_reports(world):
+ with app.test_client() as c:
+ resp = c.put(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["c"], world["b"]]},
+ headers=_h(world, "write"))
+ body = resp.get_json()
+ assert resp.status_code == 200, body
+ assert [t["id"] for t in body["tags"]] == [world["c"], world["b"]]
+ assert sorted(body["added"]) == sorted([world["b"], world["c"]]) and body["removed"] == [world["a"]]
+ assert _tags(world) == [world["c"], world["b"]]
+
+
+def test_put_with_a_foreign_tag_changes_nothing(world):
+ with app.test_client() as c:
+ resp = c.put(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["b"], world["foreign"], 999999]},
+ headers=_h(world))
+ assert resp.status_code == 400 and resp.get_json()["code"] == "invalid_parameter"
+ assert sorted(resp.get_json()["tag_ids"]) == sorted([world["foreign"], 999999])
+ assert _tags(world) == [world["a"]]
+
+
[email protected]("route", ["web", "v1_post", "v1_put"])
+def test_a_group_tag_shares_the_same_way_everywhere(world, route):
+ if route == "web":
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(world["owner"])
+ resp = c.post(f"/api/recordings/{world['rec']}/tags", json={"tag_id": world["team"]})
+ else:
+ with app.test_client() as c:
+ if route == "v1_post":
+ resp = c.post(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["team"]]}, headers=_h(world, "share"))
+ else:
+ resp = c.put(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["a"], world["team"]]},
+ headers=_h(world, "share"))
+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]
+ assert (world["member"], "group_tag") in _shared_with(world)
+ with app.app_context():
+ share = InternalShare.query.filter_by(recording_id=world["rec"], shared_with_user_id=world["member"]).one()
+ assert share.can_edit is False and share.source_tag_id == world["team"]
+ assert SharedRecordingState.query.filter_by(recording_id=world["rec"], user_id=world["member"]).count() == 1
+
+
[email protected]("method", ["post", "put"])
+def test_a_write_token_without_share_cannot_share_by_tagging(world, method):
+ with app.test_client() as c:
+ if method == "post":
+ resp = c.post(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["team"]]}, headers=_h(world, "write"))
+ else:
+ resp = c.put(f"/api/v1/recordings/{world['rec']}/tags", json={"tag_ids": [world["team"]]}, headers=_h(world, "write"))
+ assert resp.status_code == 403 and resp.get_json()["code"] == "insufficient_scope"
+ assert resp.get_json()["required_scopes"] == ["share"]
+ assert _tags(world) == [world["a"]] and (world["member"], "group_tag") not in _shared_with(world)
+
+
[email protected]("call", ["post", "put", "delete"])
+def test_each_route_moves_updated_at_and_fires_a_webhook(world, call):
+ with app.app_context():
+ r = db.session.get(Recording, world["rec"])
+ r.updated_at = datetime(2020, 1, 1)
+ hook = Webhook(user_id=world["owner"], name="m", url="https://example.com/h", secret="s" * 40,
+ events=json.dumps(["recording.updated"]))
+ db.session.add(hook)
+ db.session.commit()
+ hook_id = hook.id
+ with app.test_client() as c:
+ url = f"/api/v1/recordings/{world['rec']}/tags"
+ if call == "post":
+ resp = c.post(url, json={"tag_ids": [world["b"]]}, headers=_h(world))
+ elif call == "put":
+ resp = c.put(url, json={"tag_ids": [world["b"]]}, headers=_h(world))
+ else:
+ resp = c.delete(f"{url}/{world['a']}", headers=_h(world))
+ assert resp.status_code == 200
+ with app.app_context():
+ assert db.session.get(Recording, world["rec"]).updated_at > datetime(2025, 1, 1)
+ fields = [json.loads(d.payload)["data"]["fields_changed"] for d in WebhookDelivery.query.filter_by(webhook_id=hook_id)]
+ assert fields == [["tags"]]
+
+
+def test_find_a_tag_by_name(world):
+ with app.test_client() as c:
+ found = c.get(f"/api/v1/tags?name=followed UP {world['suffix']}", headers=_h(world, "write")).get_json()["tags"]
+ none = c.get("/api/v1/tags?name=nothing-like-this", headers=_h(world, "write")).get_json()["tags"]
+ assert [t["id"] for t in found] == [world["a"]] and none == []