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 ###
This diff is collapsed.
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 datetime import datetime, timezone
......@@ -147,6 +147,30 @@ class Soundmark(Base):
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 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):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
......
import os
import tempfile
import httpx
from src.core.database import LibrarySong, Soundmark
......@@ -303,3 +305,199 @@ def test_role_update_rejects_invalid_role(client, auth_as):
_, 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
# ---- 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