From cb8f9c997e00fbd1927a4fe914fe2f7c5e7a7186 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:57:34 +0100 Subject: [PATCH] Settings column and now-playing state table (phase 4, step 1) federation_settings gains now_playing_mode (off/profile/posts, default off), validated in sharing.update() the same way visibility is. New federation_now_playing table: one row per user, tracking what we've last told the fediverse (profile_key/profile_updated_at, post_key/post_posted_at) - separate from core's now_playing table, which is what's actually playing right now. Verified the migration both ways against the local dev database: full downgrade to base and back up to heads on both branches, not just a single-step round trip. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/models.py | 20 +++++++++ src/scrobbler/federation/sharing.py | 6 ++- .../versions/2533b727da79_now_playing.py | 42 +++++++++++++++++++ tests/test_federation_keys_sharing.py | 18 +++++--- 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 src/scrobbler/migrations/versions/2533b727da79_now_playing.py diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index f3690d8..031b295 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -21,6 +21,7 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from scrobbler.extensions import db VISIBILITIES = ("followers", "unlisted", "public") +NOW_PLAYING_MODES = ("off", "profile", "posts") def utcnow() -> datetime: @@ -44,6 +45,8 @@ class FederationSettings(db.Model): timezone: Mapped[str] = mapped_column(String(64), default="UTC") post_weekly_summary: Mapped[bool] = mapped_column(Boolean, default=True) post_milestones: Mapped[bool] = mapped_column(Boolean, default=True) + # off, profile or posts (posts implies profile too) + now_playing_mode: Mapped[str] = mapped_column(String(16), default="off") created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=utcnow, onupdate=utcnow @@ -247,3 +250,20 @@ class FederationPendingCheck(db.Model): ) since: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) reason: Mapped[str] = mapped_column(String(32), default="scrobble") + + +class FederationNowPlaying(db.Model): + """What we've last told the fediverse is playing, as opposed to `now_playing` in the + core schema, which is what's actually playing. A "key" is `artist\\x1ftrack\\x1f + started_at`: playing the same track again later is a new now-playing moment, not a + stale repeat, and it doubles as federation_posts.key for the posts side.""" + + __tablename__ = "federation_now_playing" + + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + profile_key: Mapped[str | None] = mapped_column(String(512)) + profile_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + post_key: Mapped[str | None] = mapped_column(String(512)) + post_posted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index 1f76d9a..fe811c7 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -2,7 +2,7 @@ from scrobbler.extensions import db from scrobbler.federation import keys -from scrobbler.federation.models import VISIBILITIES, FederationSettings +from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES, FederationSettings from scrobbler.federation.protocol.schedule import is_valid_timezone from scrobbler.services import accounts @@ -17,6 +17,7 @@ EDITABLE = ( "timezone", "post_weekly_summary", "post_milestones", + "now_playing_mode", ) @@ -36,6 +37,7 @@ def settings_for(user_id: int) -> FederationSettings: timezone="UTC", post_weekly_summary=True, post_milestones=True, + now_playing_mode="off", ) return settings @@ -48,6 +50,8 @@ def update(user_id: int, changes: dict) -> tuple[FederationSettings, bool | None raise ValueError(f"not editable: {sorted(unknown)}") if changes.get("visibility", "followers") not in VISIBILITIES: raise ValueError("visibility must be one of " + ", ".join(VISIBILITIES)) + if changes.get("now_playing_mode", "off") not in NOW_PLAYING_MODES: + raise ValueError("now_playing_mode must be one of " + ", ".join(NOW_PLAYING_MODES)) if "timezone" in changes and not is_valid_timezone(changes["timezone"]): raise ValueError(f"not a known time zone: {changes['timezone']!r}") settings = settings_for(user_id) diff --git a/src/scrobbler/migrations/versions/2533b727da79_now_playing.py b/src/scrobbler/migrations/versions/2533b727da79_now_playing.py new file mode 100644 index 0000000..ef1f370 --- /dev/null +++ b/src/scrobbler/migrations/versions/2533b727da79_now_playing.py @@ -0,0 +1,42 @@ +"""now playing + +Revision ID: 2533b727da79 +Revises: 0b81b61c932a +Create Date: 2026-09-26 16:54:40.320486 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2533b727da79' +down_revision = '0b81b61c932a' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_now_playing', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('profile_key', sa.String(length=512), nullable=True), + sa.Column('profile_updated_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('post_key', sa.String(length=512), nullable=True), + sa.Column('post_posted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id') + ) + with op.batch_alter_table('federation_settings', schema=None) as batch_op: + batch_op.add_column(sa.Column('now_playing_mode', sa.String(length=16), nullable=False, server_default='off')) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('federation_settings', schema=None) as batch_op: + batch_op.drop_column('now_playing_mode') + + op.drop_table('federation_now_playing') + # ### end Alembic commands ### diff --git a/tests/test_federation_keys_sharing.py b/tests/test_federation_keys_sharing.py index eb23128..b9bab40 100644 --- a/tests/test_federation_keys_sharing.py +++ b/tests/test_federation_keys_sharing.py @@ -19,11 +19,12 @@ def test_unsaved_defaults_have_every_field_populated(fed_ctx, user): """settings_for() builds a transient object when a user has never saved settings; its column defaults apply only on INSERT, so every field has to be set by hand.""" settings = sharing.settings_for(user.id) - assert (settings.timezone, settings.post_weekly_summary, settings.post_milestones) == ( - "UTC", - True, - True, - ) + assert ( + settings.timezone, + settings.post_weekly_summary, + settings.post_milestones, + settings.now_playing_mode, + ) == ("UTC", True, True, "off") def test_enabling_creates_a_key_pair_that_signs(fed_ctx, user): @@ -83,6 +84,7 @@ def test_shared_user_is_case_insensitive_and_requires_sharing(fed_ctx, user, mak {"enabled": True, "handle": "x"}, {"timezone": "Mars/Phobos"}, {"timezone": ""}, + {"now_playing_mode": "always"}, ], ) def test_invalid_changes_are_rejected(fed_ctx, user, changes): @@ -93,3 +95,9 @@ def test_invalid_changes_are_rejected(fed_ctx, user, changes): def test_a_valid_timezone_can_be_set(fed_ctx, user): settings, _ = sharing.update(user.id, {"timezone": "Pacific/Auckland"}) assert settings.timezone == "Pacific/Auckland" + + +@pytest.mark.parametrize("mode", ["off", "profile", "posts"]) +def test_now_playing_mode_can_be_set(fed_ctx, user, mode): + settings, _ = sharing.update(user.id, {"now_playing_mode": mode}) + assert settings.now_playing_mode == mode