Commit 79bdfe8f authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add Soundmarks: location-tied anthems with business/super admin roles

New feature, distinct from the existing GeoDrop (any user dropping a
song for others to find): a Soundmark is a curated anthem tied to a
place. One with no owner is a super-admin-curated landmark; one with
a business_owner_id is that business's location, and only its owner
(or a super admin) can change its anthem.

- User.role ("user" | "business_admin" | "super_admin") plus
  get_current_business_admin / get_current_super_admin dependencies.
  Super admin passes both checks - same privileges, elevated.
- New soundmarks router: nearby detection (haversine against each
  soundmark's own trigger radius, not a caller-supplied search
  radius), cross-user anthem streaming (deliberately not scoped to
  the caller owning the underlying song, unlike /library/stream),
  business-owner song assignment, super-admin CRUD, a "public
  library" search across every user's songs (no such cross-user
  endpoint existed before - everything else is locked to the
  caller), and user role management (promote/demote, with owning a
  soundmark auto-promoting a plain user to business_admin so
  ownership isn't otherwise inaccessible to them).
- GET /auth/me so the webapp can read the caller's role.

25 new tests covering role gating, ownership enforcement, cross-user
song picking/streaming, and radius-based nearby matching. Promoted
dev-test-user to super_admin for webapp testing.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent a97f9454
Pipeline #1051 passed with stage
in 4 minutes and 50 seconds
"""add user roles and soundmarks table
Revision ID: 28cc64af2c16
Revises: e9d581074a3f
Create Date: 2026-08-11 05:30:25.568806
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '28cc64af2c16'
down_revision: Union[str, Sequence[str], None] = 'e9d581074a3f'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('soundmarks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.Column('latitude', sa.Float(), nullable=True),
sa.Column('longitude', sa.Float(), nullable=True),
sa.Column('radius_meters', sa.Float(), nullable=False),
sa.Column('business_owner_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['business_owner_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_soundmarks_business_owner_id'), 'soundmarks', ['business_owner_id'], unique=False)
op.create_index(op.f('ix_soundmarks_id'), 'soundmarks', ['id'], unique=False)
op.create_index(op.f('ix_soundmarks_name'), 'soundmarks', ['name'], unique=False)
# server_default backfills existing rows - without it, adding a NOT NULL column to a
# table that already has rows fails.
op.add_column('users', sa.Column('role', sa.String(), nullable=False, server_default='user'))
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'role')
op.drop_index(op.f('ix_soundmarks_name'), table_name='soundmarks')
op.drop_index(op.f('ix_soundmarks_id'), table_name='soundmarks')
op.drop_index(op.f('ix_soundmarks_business_owner_id'), table_name='soundmarks')
op.drop_table('soundmarks')
# ### end Alembic commands ###
......@@ -10,7 +10,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from src.api.routers import auth, channels, discovery, library, music, remix, social
from src.api.routers import auth, channels, discovery, library, music, remix, social, soundmarks
from src.core.config import CORS_ORIGINS, DOCS_PASSWORD, DOCS_USERNAME
from src.core.database import SessionLocal
from src.services.storage import DOWNLOADS_DIR
......@@ -91,6 +91,7 @@ app.include_router(music.router)
app.include_router(social.router)
app.include_router(remix.router)
app.include_router(channels.router)
app.include_router(soundmarks.router)
@app.get("/", include_in_schema=False)
......
......@@ -141,6 +141,20 @@ async def auth_logout(req: RefreshReq, db: Session = Depends(get_db)):
return {"status": "success"}
@router.get("/me")
async def auth_me(current_user: User = Depends(get_current_user)):
"""Lets the client know who's logged in and what they're allowed to see - the webapp uses
`role` to decide whether to show the business/super admin panels."""
return {
"status": "success",
"user": {
"id": current_user.id,
"username": current_user.username,
"role": current_user.role,
},
}
@router.get("/chats")
async def get_chats(current_user: User = Depends(get_current_user)):
if not current_user.telegram_session_string:
......
import math
import os
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Soundmark, User
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, is_super_admin
router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
VALID_ROLES = {"user", "business_admin", "super_admin"}
def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
R = 6371000.0 # Earth radius in meters
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) ** 2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _serialize(sm: Soundmark, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == sm.song_id).first() if sm.song_id else None
owner = db.query(User).filter(User.id == sm.business_owner_id).first() if sm.business_owner_id else None
return {
"id": sm.id,
"name": sm.name,
"description": sm.description,
"latitude": sm.latitude,
"longitude": sm.longitude,
"radius_meters": sm.radius_meters,
"business_owner_id": sm.business_owner_id,
"business_owner_username": owner.username if owner else None,
"song": (
{
"id": song.id,
"title": song.title,
"artist": song.artist,
"album": song.album,
"coverart": song.coverart,
}
if song
else None
),
"created_at": sm.created_at,
"updated_at": sm.updated_at,
}
def _maybe_promote_to_business_admin(owner: User, db: Session) -> None:
"""Owning a soundmark is meaningless without business_admin access to actually manage it -
only upgrades ('user' -> 'business_admin'), never downgrades an existing super_admin."""
if owner.role == "user":
owner.role = "business_admin"
db.add(owner)
# ---- Schemas ----
class SoundmarkCreate(BaseModel):
name: str
description: Optional[str] = None
latitude: float
longitude: float
radius_meters: float = 200.0
business_owner_id: Optional[int] = None
song_id: Optional[int] = None
class SoundmarkUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None
radius_meters: Optional[float] = None
business_owner_id: Optional[int] = None
song_id: Optional[int] = None
class SongAssign(BaseModel):
song_id: Optional[int] = None # null clears the anthem
class RoleUpdate(BaseModel):
role: str
# ---- Consumer endpoints (any authenticated user) ----
@router.get("/nearby")
def get_nearby_soundmarks(
lat: float, lon: float, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""Soundmarks whose own trigger radius currently contains (lat, lon), closest first - this
is what the webapp polls as the user moves, to find 'the anthem playing here' rather than
a caller-supplied search radius."""
all_marks = db.query(Soundmark).filter(Soundmark.song_id.isnot(None)).all()
matches = []
for sm in all_marks:
if sm.latitude is None or sm.longitude is None:
continue
dist = _haversine_meters(lat, lon, sm.latitude, sm.longitude)
if dist <= sm.radius_meters:
entry = _serialize(sm, db)
entry["distance_meters"] = dist
matches.append(entry)
matches.sort(key=lambda m: m["distance_meters"])
return {"status": "success", "soundmarks": matches}
@router.get("/mine")
def get_my_soundmarks(db: Session = Depends(get_db), current_user: User = Depends(get_current_business_admin)):
marks = (
db.query(Soundmark).filter(Soundmark.business_owner_id == current_user.id).order_by(Soundmark.name).all()
)
return {"status": "success", "soundmarks": [_serialize(sm, db) for sm in marks]}
@router.get("/song-library")
def search_song_library(
q: str = "", db: Session = Depends(get_db), current_user: User = Depends(get_current_business_admin)
):
"""The 'public library' business admins pick anthems from - every user's tagged songs, not
just their own (unlike /library/search, which is scoped to the caller)."""
query = db.query(LibrarySong)
if q:
like = f"%{q}%"
query = query.filter((LibrarySong.title.ilike(like)) | (LibrarySong.artist.ilike(like)))
songs = query.order_by(LibrarySong.title).limit(50).all()
return {"status": "success", "results": songs}
@router.get("/admin/users")
def list_users(
role: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
"""Lets the super admin panel find/list users to promote to business_admin or assign as a
soundmark's owner."""
query = db.query(User)
if role:
query = query.filter(User.role == role)
users = query.order_by(User.id).all()
return {
"status": "success",
"users": [
{"id": u.id, "username": u.username, "phone_number": u.phone_number, "role": u.role} for u in users
],
}
@router.patch("/admin/users/{user_id}/role")
def update_user_role(
user_id: int,
body: RoleUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
if body.role not in VALID_ROLES:
raise HTTPException(status_code=422, detail=f"role must be one of {sorted(VALID_ROLES)}")
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.role = body.role
db.commit()
return {"status": "success", "user": {"id": user.id, "username": user.username, "role": user.role}}
@router.get("")
def list_all_soundmarks(db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)):
marks = db.query(Soundmark).order_by(Soundmark.name).all()
return {"status": "success", "soundmarks": [_serialize(sm, db) for sm in marks]}
@router.post("", status_code=201)
def create_soundmark(
body: SoundmarkCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
owner = None
if body.business_owner_id is not None:
owner = db.query(User).filter(User.id == body.business_owner_id).first()
if not owner:
raise HTTPException(status_code=404, detail="Owner user not found")
if body.song_id is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
sm = Soundmark(**body.dict())
db.add(sm)
if owner:
_maybe_promote_to_business_admin(owner, db)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.patch("/{soundmark_id}/song")
def set_soundmark_song(
soundmark_id: int,
body: SongAssign,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_business_admin),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
if sm.business_owner_id != current_user.id and not is_super_admin(current_user):
raise HTTPException(status_code=403, detail="You don't own this soundmark")
if body.song_id is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
sm.song_id = body.song_id
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.patch("/{soundmark_id}")
def update_soundmark(
soundmark_id: int,
body: SoundmarkUpdate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_super_admin),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
data = body.dict(exclude_unset=True)
owner = None
if "business_owner_id" in data and data["business_owner_id"] is not None:
owner = db.query(User).filter(User.id == data["business_owner_id"]).first()
if not owner:
raise HTTPException(status_code=404, detail="Owner user not found")
if "song_id" in data and data["song_id"] is not None:
song = db.query(LibrarySong).filter(LibrarySong.id == data["song_id"]).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
for key, value in data.items():
setattr(sm, key, value)
if owner:
_maybe_promote_to_business_admin(owner, db)
db.commit()
db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)}
@router.delete("/{soundmark_id}")
def delete_soundmark(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
db.delete(sm)
db.commit()
return {"status": "success"}
@router.get("/{soundmark_id}/stream")
def stream_soundmark_anthem(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
):
"""Streams a soundmark's current anthem regardless of which user originally uploaded the
underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to
the caller owning the song, since the whole point is other people hearing it too."""
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm or not sm.song_id:
raise HTTPException(status_code=404, detail="This soundmark has no anthem set")
song = db.query(LibrarySong).filter(LibrarySong.id == sm.song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path):
raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg")
......@@ -31,6 +31,10 @@ class User(Base):
# Pyrogram session string for this user's linked Telegram account. Set on /auth/login,
# used server-side only (by telegram_sync calls) - never serialized back to a client.
telegram_session_string = Column(String, nullable=True)
# "user" | "business_admin" | "super_admin" - kept as a plain string rather than a DB enum
# so adding a role later doesn't need a migration to alter the enum type (sqlite's enum
# support is weak anyway). Validated at the API boundary in soundmarks.py, not here.
role = Column(String, default="user", nullable=False)
class RefreshToken(Base):
__tablename__ = "refresh_tokens"
......@@ -122,6 +126,27 @@ class GeoDrop(Base):
longitude = Column(Float)
dropped_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Soundmark(Base):
"""A curated 'anthem' tied to a real-world place - distinct from GeoDrop (any user
dropping a song for others to stumble on). A Soundmark with business_owner_id NULL is a
super-admin-curated landmark (e.g. locally significant to the area); one with an owner is
that business's location, and its anthem can only be changed by that owner or a super
admin. song_id is nullable so a soundmark can exist (name/location set by a super admin)
before anyone has picked its anthem yet."""
__tablename__ = "soundmarks"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
latitude = Column(Float)
longitude = Column(Float)
# How close (in meters) someone needs to be for this soundmark to be considered "active" -
# this is what /soundmarks/nearby matches against, not a caller-supplied search radius.
radius_meters = Column(Float, default=200.0, nullable=False)
business_owner_id = Column(Integer, ForeignKey("users.id"), nullable=True, index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class LiveRoom(Base):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
......
......@@ -63,3 +63,21 @@ def get_current_user(
if not user:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
return user
def is_super_admin(user: User) -> bool:
return user.role == "super_admin"
def get_current_business_admin(current_user: User = Depends(get_current_user)) -> User:
"""Business admins manage their own soundmarks; super admins pass this check too since
they can do everything a business admin can, plus more (see get_current_super_admin)."""
if current_user.role not in ("business_admin", "super_admin"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Business admin access required")
return current_user
def get_current_super_admin(current_user: User = Depends(get_current_user)) -> User:
if not is_super_admin(current_user):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin access required")
return current_user
......@@ -47,12 +47,13 @@ _user_ids = itertools.count(10_000)
def make_user(db_session):
"""Creates a real User row (as if they'd completed Telegram login) without going through
the actual Telegram auth flow - test_auth.py covers that flow itself with mocks."""
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string"):
def _make(phone_number: str = None, telegram_session_string: str = "fake-session-string", role: str = "user"):
uid = next(_user_ids)
user = User(
id=uid,
phone_number=phone_number or f"+1555{uid}",
telegram_session_string=telegram_session_string,
role=role,
)
db_session.add(user)
db_session.commit()
......
import os
import tempfile
from src.core.database import LibrarySong, Soundmark
def _make_library_song(db_session, user_id, **overrides):
fd, path = tempfile.mkstemp(suffix=".mp3", dir="/tmp")
with os.fdopen(fd, "wb") as f:
f.write(b"fake mp3 bytes for soundmark stream test")
defaults = dict(user_id=user_id, title="Test Anthem", artist="Test Artist", album="Test Album", genre="Pop", file_path=path)
defaults.update(overrides)
song = LibrarySong(**defaults)
db_session.add(song)
db_session.commit()
db_session.refresh(song)
return song, path
def _make_soundmark(db_session, **overrides):
defaults = dict(name="Test Soundmark", latitude=37.7749, longitude=-122.4194, radius_meters=200.0)
defaults.update(overrides)
sm = Soundmark(**defaults)
db_session.add(sm)
db_session.commit()
db_session.refresh(sm)
return sm
# ---- Role gating ----
def test_soundmarks_nearby_requires_auth(client):
response = client.get("/soundmarks/nearby", params={"lat": 0, "lon": 0})
assert response.status_code == 401
def test_regular_user_cannot_access_business_endpoints(client, auth_as):
headers, _ = auth_as()
response = client.get("/soundmarks/mine", headers=headers)
assert response.status_code == 403
def test_regular_user_cannot_access_super_admin_endpoints(client, auth_as):
headers, _ = auth_as()
assert client.get("/soundmarks", headers=headers).status_code == 403
assert client.post("/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0}, headers=headers).status_code == 403
def test_business_admin_cannot_access_super_admin_only_endpoints(client, auth_as):
headers, _ = auth_as(role="business_admin")
assert client.get("/soundmarks", headers=headers).status_code == 403
assert client.post("/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0}, headers=headers).status_code == 403
assert client.delete("/soundmarks/1", headers=headers).status_code == 403
def test_super_admin_can_access_business_endpoints_too(client, db_session, auth_as):
"""Super admin has business admin privileges plus elevated ones - not a separate track."""
headers, _ = auth_as(role="super_admin")
response = client.get("/soundmarks/mine", headers=headers)
assert response.status_code == 200
# ---- Super admin CRUD ----
def test_super_admin_creates_soundmark(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks",
json={"name": "Landmark Plaza", "description": "Historic square", "latitude": 1.0, "longitude": 2.0, "radius_meters": 100},
headers=headers,
)
assert response.status_code == 201
body = response.json()["soundmark"]
assert body["name"] == "Landmark Plaza"
assert body["business_owner_id"] is None
assert body["song"] is None
def test_creating_soundmark_with_owner_promotes_them_to_business_admin(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
owner_headers, owner = auth_as() # plain "user" role
assert owner.role == "user"
response = client.post(
"/soundmarks",
json={"name": "Joe's Cafe", "latitude": 1.0, "longitude": 2.0, "business_owner_id": owner.id},
headers=headers,
)
assert response.status_code == 201
db_session.refresh(owner)
assert owner.role == "business_admin"
def test_creating_soundmark_with_unknown_owner_fails(client, auth_as):
headers, _ = auth_as(role="super_admin")
response = client.post(
"/soundmarks", json={"name": "x", "latitude": 0, "longitude": 0, "business_owner_id": 999999}, headers=headers
)
assert response.status_code == 404
def test_super_admin_updates_and_deletes_soundmark(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
sm = _make_soundmark(db_session)
response = client.patch(f"/soundmarks/{sm.id}", json={"name": "Renamed", "radius_meters": 50}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["name"] == "Renamed"
assert response.json()["soundmark"]["radius_meters"] == 50
response = client.delete(f"/soundmarks/{sm.id}", headers=headers)
assert response.status_code == 200
assert db_session.query(Soundmark).filter(Soundmark.id == sm.id).first() is None
def test_super_admin_lists_all_soundmarks_regardless_of_owner(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_make_soundmark(db_session, name="Mark A")
_make_soundmark(db_session, name="Mark B")
response = client.get("/soundmarks", headers=headers)
assert response.status_code == 200
names = {sm["name"] for sm in response.json()["soundmarks"]}
assert {"Mark A", "Mark B"}.issubset(names)
# ---- Business admin song assignment ----
def test_business_admin_can_set_song_on_own_soundmark(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"]["id"] == song.id
def test_business_admin_cannot_set_song_on_someone_elses_soundmark(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
other_headers, other_owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=other_owner.id)
song, _ = _make_library_song(db_session, other_owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 403
def test_business_admin_can_pick_a_song_from_another_users_library(client, db_session, auth_as):
"""The whole point of the 'public library' picker - not restricted to songs they uploaded."""
headers, owner = auth_as(role="business_admin")
_, stranger = auth_as()
sm = _make_soundmark(db_session, business_owner_id=owner.id)
song, _ = _make_library_song(db_session, stranger.id, title="Someone Else's Song")
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"]["title"] == "Someone Else's Song"
def test_business_admin_can_clear_the_anthem(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
song, _ = _make_library_song(db_session, owner.id)
sm = _make_soundmark(db_session, business_owner_id=owner.id, song_id=song.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": None}, headers=headers)
assert response.status_code == 200
assert response.json()["soundmark"]["song"] is None
def test_super_admin_can_set_song_on_any_soundmark(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, owner = auth_as(role="business_admin")
sm = _make_soundmark(db_session, business_owner_id=owner.id)
song, _ = _make_library_song(db_session, owner.id)
response = client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": song.id}, headers=headers)
assert response.status_code == 200
def test_get_my_soundmarks_only_returns_own(client, db_session, auth_as):
headers, owner = auth_as(role="business_admin")
_, other = auth_as(role="business_admin")
mine = _make_soundmark(db_session, name="Mine", business_owner_id=owner.id)
_make_soundmark(db_session, name="Theirs", business_owner_id=other.id)
response = client.get("/soundmarks/mine", headers=headers)
assert response.status_code == 200
names = [sm["name"] for sm in response.json()["soundmarks"]]
assert names == ["Mine"]
assert mine.id in [sm["id"] for sm in response.json()["soundmarks"]]
# ---- Song library search ----
def test_song_library_search_spans_all_users(client, db_session, auth_as):
headers, _ = auth_as(role="business_admin")
_, user_a = auth_as()
_, user_b = auth_as()
_make_library_song(db_session, user_a.id, title="Alpha Song")
_make_library_song(db_session, user_b.id, title="Beta Song")
response = client.get("/soundmarks/song-library", params={"q": "Song"}, headers=headers)
assert response.status_code == 200
titles = {s["title"] for s in response.json()["results"]}
assert {"Alpha Song", "Beta Song"}.issubset(titles)
# ---- Nearby detection ----
def test_nearby_matches_within_radius(client, db_session, auth_as):
headers, _ = auth_as()
song, _ = _make_library_song(db_session, 1)
# ~10 meters north of the soundmark's center - well within a 200m radius.
_make_soundmark(db_session, name="Close Mark", latitude=37.7749, longitude=-122.4194, radius_meters=200, song_id=song.id)
response = client.get("/soundmarks/nearby", params={"lat": 37.77499, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
marks = response.json()["soundmarks"]
assert any(m["name"] == "Close Mark" for m in marks)
assert marks[0]["distance_meters"] < 200
def test_nearby_excludes_marks_outside_their_radius(client, db_session, auth_as):
headers, _ = auth_as()
song, _ = _make_library_song(db_session, 1)
# Roughly 1000km away - well outside any reasonable radius.
_make_soundmark(db_session, name="Far Mark", latitude=48.8566, longitude=2.3522, radius_meters=200, song_id=song.id)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
names = {m["name"] for m in response.json()["soundmarks"]}
assert "Far Mark" not in names
def test_nearby_excludes_soundmarks_with_no_anthem(client, db_session, auth_as):
headers, _ = auth_as()
_make_soundmark(db_session, name="Empty Mark", latitude=37.7749, longitude=-122.4194, radius_meters=200, song_id=None)
response = client.get("/soundmarks/nearby", params={"lat": 37.7749, "lon": -122.4194}, headers=headers)
assert response.status_code == 200
names = {m["name"] for m in response.json()["soundmarks"]}
assert "Empty Mark" not in names
# ---- Streaming (cross-user, unlike /library/stream) ----
def test_stream_soundmark_anthem_works_regardless_of_song_owner(client, db_session, auth_as):
listener_headers, _ = auth_as()
_, uploader = auth_as()
song, path = _make_library_song(db_session, uploader.id)
sm = _make_soundmark(db_session, song_id=song.id)
try:
response = client.get(f"/soundmarks/{sm.id}/stream", headers=listener_headers)
assert response.status_code == 200
assert response.content == b"fake mp3 bytes for soundmark stream test"
finally:
os.remove(path)
def test_stream_soundmark_with_no_anthem_404s(client, db_session, auth_as):
headers, _ = auth_as()
sm = _make_soundmark(db_session, song_id=None)
response = client.get(f"/soundmarks/{sm.id}/stream", headers=headers)
assert response.status_code == 404
# ---- User role management ----
def test_super_admin_lists_and_filters_users_by_role(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, biz = auth_as(role="business_admin")
response = client.get("/soundmarks/admin/users", params={"role": "business_admin"}, headers=headers)
assert response.status_code == 200
ids = {u["id"] for u in response.json()["users"]}
assert biz.id in ids
def test_super_admin_promotes_a_user_to_business_admin(client, db_session, auth_as):
headers, _ = auth_as(role="super_admin")
_, plain_user = auth_as()
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}/role", json={"role": "business_admin"}, headers=headers)
assert response.status_code == 200
db_session.refresh(plain_user)
assert plain_user.role == "business_admin"
def test_role_update_rejects_invalid_role(client, auth_as):
headers, _ = auth_as(role="super_admin")
_, plain_user = auth_as()
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}/role", json={"role": "wizard"}, headers=headers)
assert response.status_code == 422
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment