Commit 8b2ac79a authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add song proposals + voting to Soundmarks, and a Nominatim geocode proxy

Users can now propose a song for any soundmark; the most-voted
proposal is what actually plays there, not just an admin's original
pick. One vote per (soundmark, user), movable between proposals.
Directly setting a soundmark's song (business/super admin) now also
seeds a proposal with the setter's own vote, so it competes fairly
in the same ranking instead of being a separate, un-votable channel
that a single stray vote could trivially override - and instead of
silently losing to the crowd the moment anyone else proposes
something. Soundmark.song_id remains as the fallback used only while
a soundmark has zero proposals.

/soundmarks/nearby and /soundmarks/{id}/stream now resolve through
the same popularity logic, so a soundmark that only has user
proposals (no admin-set song_id at all) is discoverable and
streamable too, not just admin-seeded ones.

Also added GET /soundmarks/geocode, a server-side proxy to
OpenStreetMap's free Nominatim geocoder for the webapp's upcoming
location-picker autocomplete - proxied because Nominatim's usage
policy requires a real, identifying User-Agent header, which browser
JS can't set on a raw fetch().

11 new tests (proposal creation/merging, vote-switching, popularity
overriding the admin fallback, and the geocode proxy incl. failure
handling) - 144 backend tests passing overall.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 79bdfe8f
Pipeline #1053 passed with stage
in 3 minutes and 1 second
"""add soundmark proposals and votes
Revision ID: 63839d131d50
Revises: 28cc64af2c16
Create Date: 2026-08-11 07:15:40.317957
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '63839d131d50'
down_revision: Union[str, Sequence[str], None] = '28cc64af2c16'
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('soundmark_proposals',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('soundmark_id', sa.Integer(), nullable=True),
sa.Column('song_id', sa.Integer(), nullable=True),
sa.Column('proposed_by_user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposed_by_user_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['song_id'], ['library_songs.id'], ),
sa.ForeignKeyConstraint(['soundmark_id'], ['soundmarks.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('soundmark_id', 'song_id', name='uq_soundmark_proposal_song')
)
op.create_index(op.f('ix_soundmark_proposals_id'), 'soundmark_proposals', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposals_soundmark_id'), 'soundmark_proposals', ['soundmark_id'], unique=False)
op.create_table('soundmark_proposal_votes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('proposal_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['proposal_id'], ['soundmark_proposals.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('proposal_id', 'user_id', name='uq_soundmark_proposal_vote')
)
op.create_index(op.f('ix_soundmark_proposal_votes_id'), 'soundmark_proposal_votes', ['id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_proposal_id'), 'soundmark_proposal_votes', ['proposal_id'], unique=False)
op.create_index(op.f('ix_soundmark_proposal_votes_user_id'), 'soundmark_proposal_votes', ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_soundmark_proposal_votes_user_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_proposal_id'), table_name='soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposal_votes_id'), table_name='soundmark_proposal_votes')
op.drop_table('soundmark_proposal_votes')
op.drop_index(op.f('ix_soundmark_proposals_soundmark_id'), table_name='soundmark_proposals')
op.drop_index(op.f('ix_soundmark_proposals_id'), table_name='soundmark_proposals')
op.drop_table('soundmark_proposals')
# ### end Alembic commands ###
...@@ -2,17 +2,23 @@ import math ...@@ -2,17 +2,23 @@ import math
import os import os
from typing import Optional from typing import Optional
import httpx
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, LibrarySong, Soundmark, User from src.core.config import logger
from src.core.database import get_db, LibrarySong, Soundmark, SoundmarkProposal, SoundmarkProposalVote, User
from src.core.security import get_current_business_admin, get_current_super_admin, get_current_user, is_super_admin 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"]) router = APIRouter(prefix="/soundmarks", tags=["Soundmarks"])
VALID_ROLES = {"user", "business_admin", "super_admin"} VALID_ROLES = {"user", "business_admin", "super_admin"}
# Nominatim's usage policy requires a real, identifying User-Agent - browsers won't let JS set
# a custom one on a raw fetch(), which is the main reason this is proxied server-side rather
# than called directly from the webapp.
NOMINATIM_USER_AGENT = "StaxSoundmarks/1.0 (location picker for the Stax soundmarks feature)"
def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float: def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
...@@ -23,9 +29,28 @@ def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> flo ...@@ -23,9 +29,28 @@ def _haversine_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> flo
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
def _resolve_active_song_id(sm: Soundmark, db: Session) -> Optional[int]:
"""The song that actually plays: whichever proposal has the most votes, ties broken by
whichever was proposed first. Soundmark.song_id (set directly via PATCH .../song) is only
the fallback for a soundmark with no proposals yet - see set_soundmark_song, which turns
every direct song assignment into a proposal (with the setter's own vote) so it competes
fairly instead of being silently overridden by a single stray vote."""
proposals = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == sm.id).all()
if not proposals:
return sm.song_id
scored = [
(db.query(SoundmarkProposalVote).filter(SoundmarkProposalVote.proposal_id == p.id).count(), p)
for p in proposals
]
scored.sort(key=lambda pair: (-pair[0], pair[1].created_at))
return scored[0][1].song_id
def _serialize(sm: Soundmark, db: Session) -> dict: def _serialize(sm: Soundmark, db: Session) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == sm.song_id).first() if sm.song_id else None active_song_id = _resolve_active_song_id(sm, db)
song = db.query(LibrarySong).filter(LibrarySong.id == active_song_id).first() if active_song_id else None
owner = db.query(User).filter(User.id == sm.business_owner_id).first() if sm.business_owner_id else None owner = db.query(User).filter(User.id == sm.business_owner_id).first() if sm.business_owner_id else None
proposal_count = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == sm.id).count()
return { return {
"id": sm.id, "id": sm.id,
"name": sm.name, "name": sm.name,
...@@ -46,11 +71,67 @@ def _serialize(sm: Soundmark, db: Session) -> dict: ...@@ -46,11 +71,67 @@ def _serialize(sm: Soundmark, db: Session) -> dict:
if song if song
else None else None
), ),
"proposal_count": proposal_count,
"created_at": sm.created_at, "created_at": sm.created_at,
"updated_at": sm.updated_at, "updated_at": sm.updated_at,
} }
def _serialize_proposal(p: SoundmarkProposal, db: Session, current_user_id: int) -> dict:
song = db.query(LibrarySong).filter(LibrarySong.id == p.song_id).first()
vote_count = db.query(SoundmarkProposalVote).filter(SoundmarkProposalVote.proposal_id == p.id).count()
has_voted = (
db.query(SoundmarkProposalVote)
.filter(SoundmarkProposalVote.proposal_id == p.id, SoundmarkProposalVote.user_id == current_user_id)
.first()
is not None
)
proposer = db.query(User).filter(User.id == p.proposed_by_user_id).first()
return {
"id": p.id,
"song": (
{"id": song.id, "title": song.title, "artist": song.artist, "album": song.album, "coverart": song.coverart}
if song
else None
),
"vote_count": vote_count,
"has_voted": has_voted,
"proposed_by_username": proposer.username if proposer else None,
"created_at": p.created_at,
}
def _cast_vote(soundmark_id: int, proposal_id: int, user_id: int, db: Session) -> None:
"""One vote per (soundmark, user) - moves the vote if the user already backed a different
proposal here, no-ops if they're just re-affirming the one they already picked."""
existing = (
db.query(SoundmarkProposalVote)
.join(SoundmarkProposal, SoundmarkProposal.id == SoundmarkProposalVote.proposal_id)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposalVote.user_id == user_id)
.first()
)
if existing:
if existing.proposal_id == proposal_id:
return
db.delete(existing)
db.flush()
db.add(SoundmarkProposalVote(proposal_id=proposal_id, user_id=user_id))
def _propose_and_vote(soundmark_id: int, song_id: int, user_id: int, db: Session) -> SoundmarkProposal:
proposal = (
db.query(SoundmarkProposal)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposal.song_id == song_id)
.first()
)
if not proposal:
proposal = SoundmarkProposal(soundmark_id=soundmark_id, song_id=song_id, proposed_by_user_id=user_id)
db.add(proposal)
db.flush() # need proposal.id before voting for it
_cast_vote(soundmark_id, proposal.id, user_id, db)
return proposal
def _maybe_promote_to_business_admin(owner: User, db: Session) -> None: def _maybe_promote_to_business_admin(owner: User, db: Session) -> None:
"""Owning a soundmark is meaningless without business_admin access to actually manage it - """Owning a soundmark is meaningless without business_admin access to actually manage it -
only upgrades ('user' -> 'business_admin'), never downgrades an existing super_admin.""" only upgrades ('user' -> 'business_admin'), never downgrades an existing super_admin."""
...@@ -99,15 +180,18 @@ def get_nearby_soundmarks( ...@@ -99,15 +180,18 @@ def get_nearby_soundmarks(
): ):
"""Soundmarks whose own trigger radius currently contains (lat, lon), closest first - this """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 is what the webapp polls as the user moves, to find 'the anthem playing here' rather than
a caller-supplied search radius.""" a caller-supplied search radius. Includes soundmarks that only have user proposals and no
all_marks = db.query(Soundmark).filter(Soundmark.song_id.isnot(None)).all() admin-set song_id, since a winning proposal is just as real an anthem as an admin pick."""
all_marks = db.query(Soundmark).all()
matches = [] matches = []
for sm in all_marks: for sm in all_marks:
if sm.latitude is None or sm.longitude is None: if sm.latitude is None or sm.longitude is None:
continue continue
entry = _serialize(sm, db)
if not entry["song"]:
continue
dist = _haversine_meters(lat, lon, sm.latitude, sm.longitude) dist = _haversine_meters(lat, lon, sm.latitude, sm.longitude)
if dist <= sm.radius_meters: if dist <= sm.radius_meters:
entry = _serialize(sm, db)
entry["distance_meters"] = dist entry["distance_meters"] = dist
matches.append(entry) matches.append(entry)
matches.sort(key=lambda m: m["distance_meters"]) matches.sort(key=lambda m: m["distance_meters"])
...@@ -136,6 +220,32 @@ def search_song_library( ...@@ -136,6 +220,32 @@ def search_song_library(
return {"status": "success", "results": songs} return {"status": "success", "results": songs}
@router.get("/geocode")
async def geocode_address(q: str, current_user: User = Depends(get_current_business_admin)):
"""Address-search autocomplete for the location picker, backed by OpenStreetMap's free
Nominatim geocoder - see NOMINATIM_USER_AGENT for why this has to be a server-side proxy
rather than the webapp calling Nominatim directly."""
if not q.strip():
return {"status": "success", "results": []}
try:
async with httpx.AsyncClient(timeout=10.0) as client:
res = await client.get(
"https://nominatim.openstreetmap.org/search",
params={"q": q, "format": "jsonv2", "limit": 5},
headers={"User-Agent": NOMINATIM_USER_AGENT},
)
res.raise_for_status()
data = res.json()
except httpx.HTTPError as e:
logger.error(f"Nominatim geocode request failed: {e}")
raise HTTPException(status_code=502, detail="Location search is temporarily unavailable")
results = [
{"display_name": item["display_name"], "latitude": float(item["lat"]), "longitude": float(item["lon"])}
for item in data
]
return {"status": "success", "results": results}
@router.get("/admin/users") @router.get("/admin/users")
def list_users( def list_users(
role: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin) role: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
...@@ -217,6 +327,11 @@ def set_soundmark_song( ...@@ -217,6 +327,11 @@ def set_soundmark_song(
if not song: if not song:
raise HTTPException(status_code=404, detail="Song not found") raise HTTPException(status_code=404, detail="Song not found")
sm.song_id = body.song_id sm.song_id = body.song_id
if body.song_id is not None:
# Turn this into a proposal (with the setter's own vote) rather than a silent
# override, so it competes fairly with user proposals instead of being trivially
# out-voted by whoever proposes something else first.
_propose_and_vote(sm.id, body.song_id, current_user.id, db)
db.commit() db.commit()
db.refresh(sm) db.refresh(sm)
return {"status": "success", "soundmark": _serialize(sm, db)} return {"status": "success", "soundmark": _serialize(sm, db)}
...@@ -269,13 +384,87 @@ def delete_soundmark( ...@@ -269,13 +384,87 @@ def delete_soundmark(
def stream_soundmark_anthem( def stream_soundmark_anthem(
soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user) 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 """Streams a soundmark's current anthem (the most-voted proposal, or the admin-set
fallback if there are no proposals) regardless of which user originally uploaded the
underlying LibrarySong - unlike /library/stream/{id}, this is deliberately not scoped to 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.""" 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() sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm or not sm.song_id: if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
active_song_id = _resolve_active_song_id(sm, db)
if not active_song_id:
raise HTTPException(status_code=404, detail="This soundmark has no anthem set") raise HTTPException(status_code=404, detail="This soundmark has no anthem set")
song = db.query(LibrarySong).filter(LibrarySong.id == sm.song_id).first() song = db.query(LibrarySong).filter(LibrarySong.id == active_song_id).first()
if not song or not song.file_path or not os.path.exists(song.file_path): 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") raise HTTPException(status_code=404, detail="Audio file not found")
return FileResponse(song.file_path, media_type="audio/mpeg") return FileResponse(song.file_path, media_type="audio/mpeg")
# ---- Song proposals & voting (any authenticated user) ----
class ProposeSong(BaseModel):
song_id: int
@router.get("/{soundmark_id}/proposals")
def get_proposals(soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
proposals = db.query(SoundmarkProposal).filter(SoundmarkProposal.soundmark_id == soundmark_id).all()
serialized = [_serialize_proposal(p, db, current_user.id) for p in proposals]
serialized.sort(key=lambda p: -p["vote_count"])
return {"status": "success", "proposals": serialized}
@router.post("/{soundmark_id}/proposals", status_code=201)
def propose_song(
soundmark_id: int,
body: ProposeSong,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
sm = db.query(Soundmark).filter(Soundmark.id == soundmark_id).first()
if not sm:
raise HTTPException(status_code=404, detail="Soundmark not found")
song = db.query(LibrarySong).filter(LibrarySong.id == body.song_id).first()
if not song:
raise HTTPException(status_code=404, detail="Song not found")
proposal = _propose_and_vote(soundmark_id, body.song_id, current_user.id, db)
db.commit()
db.refresh(proposal)
return {"status": "success", "proposal": _serialize_proposal(proposal, db, current_user.id)}
@router.post("/{soundmark_id}/proposals/{proposal_id}/vote")
def vote_for_proposal(
soundmark_id: int,
proposal_id: int,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
):
proposal = (
db.query(SoundmarkProposal)
.filter(SoundmarkProposal.id == proposal_id, SoundmarkProposal.soundmark_id == soundmark_id)
.first()
)
if not proposal:
raise HTTPException(status_code=404, detail="Proposal not found")
_cast_vote(soundmark_id, proposal_id, current_user.id, db)
db.commit()
return {"status": "success", "proposal": _serialize_proposal(proposal, db, current_user.id)}
@router.delete("/{soundmark_id}/proposals/vote")
def remove_vote(soundmark_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
existing = (
db.query(SoundmarkProposalVote)
.join(SoundmarkProposal, SoundmarkProposal.id == SoundmarkProposalVote.proposal_id)
.filter(SoundmarkProposal.soundmark_id == soundmark_id, SoundmarkProposalVote.user_id == current_user.id)
.first()
)
if existing:
db.delete(existing)
db.commit()
return {"status": "success"}
import os import os
from sqlalchemy import create_engine, event, Column, Integer, String, DateTime, ForeignKey, Boolean, Float from sqlalchemy import create_engine, event, Column, Integer, String, DateTime, ForeignKey, Boolean, Float, UniqueConstraint
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime, timezone from datetime import datetime, timezone
...@@ -147,6 +147,30 @@ class Soundmark(Base): ...@@ -147,6 +147,30 @@ class Soundmark(Base):
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) 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)) updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
class SoundmarkProposal(Base):
"""A candidate anthem someone's suggested for a soundmark. The proposal with the most
votes is what actually plays there (see soundmarks.py's _resolve_active_song) - the
business/super-admin-set Soundmark.song_id is only the fallback used while a soundmark has
no proposals yet, not a permanent override."""
__tablename__ = "soundmark_proposals"
__table_args__ = (UniqueConstraint("soundmark_id", "song_id", name="uq_soundmark_proposal_song"),)
id = Column(Integer, primary_key=True, index=True)
soundmark_id = Column(Integer, ForeignKey("soundmarks.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
proposed_by_user_id = Column(Integer, ForeignKey("users.id"))
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class SoundmarkProposalVote(Base):
"""One row per (proposal, voter). A voter switching their pick for a soundmark deletes
their old vote row (on whichever proposal it was) and inserts a new one - enforced in
soundmarks.py, not by a DB constraint, since "one vote per soundmark" spans proposals."""
__tablename__ = "soundmark_proposal_votes"
__table_args__ = (UniqueConstraint("proposal_id", "user_id", name="uq_soundmark_proposal_vote"),)
id = Column(Integer, primary_key=True, index=True)
proposal_id = Column(Integer, ForeignKey("soundmark_proposals.id"), index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class LiveRoom(Base): class LiveRoom(Base):
__tablename__ = "live_rooms" __tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
......
import os import os
import tempfile import tempfile
import httpx
from src.core.database import LibrarySong, Soundmark from src.core.database import LibrarySong, Soundmark
...@@ -303,3 +305,199 @@ def test_role_update_rejects_invalid_role(client, auth_as): ...@@ -303,3 +305,199 @@ def test_role_update_rejects_invalid_role(client, auth_as):
_, plain_user = auth_as() _, plain_user = auth_as()
response = client.patch(f"/soundmarks/admin/users/{plain_user.id}/role", json={"role": "wizard"}, headers=headers) response = client.patch(f"/soundmarks/admin/users/{plain_user.id}/role", json={"role": "wizard"}, headers=headers)
assert response.status_code == 422 assert response.status_code == 422
# ---- Song proposals & voting ----
def test_proposing_a_song_creates_it_with_the_proposers_own_vote(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
song, _ = _make_library_song(db_session, user.id)
response = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers)
assert response.status_code == 201
body = response.json()["proposal"]
assert body["vote_count"] == 1
assert body["has_voted"] is True
assert body["song"]["id"] == song.id
def test_proposing_the_same_song_twice_by_different_users_merges_into_one_proposal(client, db_session, auth_as):
headers_a, user_a = auth_as()
headers_b, _ = auth_as()
sm = _make_soundmark(db_session)
song, _ = _make_library_song(db_session, user_a.id)
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers_a)
response = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers_b)
assert response.status_code == 201
assert response.json()["proposal"]["vote_count"] == 2
proposals = client.get(f"/soundmarks/{sm.id}/proposals", headers=headers_a).json()["proposals"]
assert len(proposals) == 1
def test_voting_moves_a_users_vote_between_proposals_for_the_same_soundmark(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
song_a, _ = _make_library_song(db_session, user.id, title="A")
song_b, _ = _make_library_song(db_session, user.id, title="B")
prop_a = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song_a.id}, headers=headers).json()["proposal"]
prop_b_res = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song_b.id}, headers=headers)
# Proposing B moved this user's one vote from A to B - A should now have 0 votes.
proposals = {p["id"]: p for p in client.get(f"/soundmarks/{sm.id}/proposals", headers=headers).json()["proposals"]}
assert proposals[prop_a["id"]]["vote_count"] == 0
assert proposals[prop_b_res.json()["proposal"]["id"]]["vote_count"] == 1
def test_removing_a_vote(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
song, _ = _make_library_song(db_session, user.id)
proposal = client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": song.id}, headers=headers).json()["proposal"]
response = client.delete(f"/soundmarks/{sm.id}/proposals/vote", headers=headers)
assert response.status_code == 200
proposals = client.get(f"/soundmarks/{sm.id}/proposals", headers=headers).json()["proposals"]
assert proposals[0]["vote_count"] == 0
assert proposals[0]["has_voted"] is False
def test_most_voted_proposal_overrides_the_admin_set_fallback_song(client, db_session, auth_as):
"""The core "most popular is displayed" rule - once a proposal earns more votes than the
admin's original pick, the popular one is what's actually shown/streamed."""
admin_headers, admin = auth_as(role="business_admin")
voter1, voter1_user = auth_as()
voter2, voter2_user = auth_as()
sm = _make_soundmark(db_session, business_owner_id=admin.id)
official_song, _ = _make_library_song(db_session, admin.id, title="Official Pick")
popular_song, path = _make_library_song(db_session, admin.id, title="Popular Upstart")
# Admin sets the official anthem directly - this seeds one proposal with the admin's vote.
client.patch(f"/soundmarks/{sm.id}/song", json={"song_id": official_song.id}, headers=admin_headers)
# Two different users propose/vote for a different song - now it has more votes (2 vs 1).
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": popular_song.id}, headers=voter1)
client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": popular_song.id}, headers=voter2)
try:
response = client.get("/soundmarks/mine", headers=admin_headers)
assert response.status_code == 200
sm_body = next(s for s in response.json()["soundmarks"] if s["id"] == sm.id)
assert sm_body["song"]["id"] == popular_song.id
stream_response = client.get(f"/soundmarks/{sm.id}/stream", headers=voter1)
assert stream_response.status_code == 200
finally:
os.remove(path)
def test_proposal_requires_soundmark_and_song_to_exist(client, db_session, auth_as):
headers, user = auth_as()
sm = _make_soundmark(db_session)
song, _ = _make_library_song(db_session, user.id)
assert client.post("/soundmarks/999999/proposals", json={"song_id": song.id}, headers=headers).status_code == 404
assert client.post(f"/soundmarks/{sm.id}/proposals", json={"song_id": 999999}, headers=headers).status_code == 404
def test_voting_for_unknown_proposal_404s(client, db_session, auth_as):
headers, _ = auth_as()
sm = _make_soundmark(db_session)
response = client.post(f"/soundmarks/{sm.id}/proposals/999999/vote", headers=headers)
assert response.status_code == 404
# ---- Geocode proxy ----
class _FakeGeocodeResponse:
def __init__(self, payload):
self._payload = payload
def raise_for_status(self):
pass
def json(self):
return self._payload
class _FakeAsyncClient:
"""Stand-in for httpx.AsyncClient - real network calls have no place in a test suite, and
Nominatim's usage policy wouldn't welcome CI hammering it anyway."""
last_request = None
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def get(self, url, params=None, headers=None):
_FakeAsyncClient.last_request = {"url": url, "params": params, "headers": headers}
return _FakeGeocodeResponse(
[{"display_name": "Eiffel Tower, Paris, France", "lat": "48.8584", "lon": "2.2945"}]
)
def test_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeAsyncClient)
response = client.get("/soundmarks/geocode", params={"q": "Eiffel Tower"}, headers=headers)
assert response.status_code == 200
results = response.json()["results"]
assert results == [{"display_name": "Eiffel Tower, Paris, France", "latitude": 48.8584, "longitude": 2.2945}]
assert "User-Agent" in _FakeAsyncClient.last_request["headers"]
assert _FakeAsyncClient.last_request["headers"]["User-Agent"] # non-empty
def test_geocode_requires_business_admin(client, auth_as):
headers, _ = auth_as()
response = client.get("/soundmarks/geocode", params={"q": "Paris"}, headers=headers)
assert response.status_code == 403
def test_geocode_empty_query_skips_the_network_call(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
class _ExplodingAsyncClient:
"""If the endpoint tried to use this for a blank query, entering the context manager
would raise and the request would 500 - proves the network call was actually skipped,
without relying on Mock-specific assertion methods on a plain stand-in class."""
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
raise AssertionError("should not have made a network call for an empty query")
async def __aexit__(self, *args):
return False
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _ExplodingAsyncClient)
response = client.get("/soundmarks/geocode", params={"q": " "}, headers=headers)
assert response.status_code == 200
assert response.json()["results"] == []
def test_geocode_upstream_failure_returns_502(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
class _FailingClient(_FakeAsyncClient):
async def get(self, *args, **kwargs):
raise httpx.ConnectError("boom")
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FailingClient)
response = client.get("/soundmarks/geocode", params={"q": "Paris"}, headers=headers)
assert response.status_code == 502
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