diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index d4ab553..f7e26f5 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -38,8 +38,10 @@ def init_app(app: Flask) -> None: from scrobbler import worker from scrobbler.federation import delivery, inbox + from scrobbler.federation.publishing import weekly worker.register_task(app, "federation.inbox", inbox.work_once) worker.register_task(app, "federation.deliver", delivery.work_once) worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) worker.register_periodic(app, "federation.gauges", 30, delivery.maintenance) + worker.register_periodic(app, "federation.weekly", 900, weekly.check_all) diff --git a/src/scrobbler/federation/protocol/content.py b/src/scrobbler/federation/protocol/content.py new file mode 100644 index 0000000..ec27501 --- /dev/null +++ b/src/scrobbler/federation/protocol/content.py @@ -0,0 +1,31 @@ +"""Safe post content: plain text and matching HTML, shared by every post kind so +they're formatted consistently and every track/artist name is escaped the same way. + +Only the tags Mastodon keeps: p, strong, em, ol, li. No br is needed here since each +line of a post is its own paragraph. +""" + +import html + +HASHTAG = "Scrobbler" + + +def escape(text: str) -> str: + """HTML-escape a name (artist, track, ...) for embedding in generated markup.""" + return html.escape(text, quote=False) + + +def paragraph(inner_html: str) -> str: + return f"

{inner_html}

" + + +def numbered_list(items_html: list[str]) -> str: + return "
    " + "".join(f"
  1. {item}
  2. " for item in items_html) + "
" + + +def hashtag_line() -> str: + return f"#{HASHTAG}" + + +def plural(count: int, word: str) -> str: + return word if count == 1 else f"{word}s" diff --git a/src/scrobbler/federation/protocol/schedule.py b/src/scrobbler/federation/protocol/schedule.py new file mode 100644 index 0000000..0de8c88 --- /dev/null +++ b/src/scrobbler/federation/protocol/schedule.py @@ -0,0 +1,51 @@ +"""Pure date/time math for scheduled posts: which week is due, in a user's own zone. + +Weeks run Monday 00:00 to Sunday 24:00 *local time*, computed in the zone itself (not as +a fixed UTC offset), so the window is correct across a daylight-saving change. +""" + +from datetime import UTC, datetime, timedelta +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +POST_HOUR = 9 # local time a week's summary becomes postable, on the following Monday + + +def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, str]: + """The [start, end) UTC window, and ISO year-week key (e.g. "2026-W02"), of the most + recent Monday-Sunday week whose Monday-POST_HOUR-local posting gate has passed. + + Always resolves to exactly one week, so a worker that was down for a while catches up + with a single post (the latest eligible week), not one per week it missed. + """ + local_now = now_utc.astimezone(tz) + gate_monday = local_now.date() - timedelta(days=local_now.weekday()) + gate = datetime(gate_monday.year, gate_monday.month, gate_monday.day, POST_HOUR, tzinfo=tz) + if local_now < gate: + gate_monday -= timedelta(days=7) + week_start = gate_monday - timedelta(days=7) + + start_local = datetime(week_start.year, week_start.month, week_start.day, tzinfo=tz) + end_local = start_local + timedelta(days=7) # wall-clock +7 days: DST-correct on conversion + year, week, _ = week_start.isocalendar() + return start_local.astimezone(UTC), end_local.astimezone(UTC), f"{year}-W{week:02d}" + + +def resolve_timezone(name: str) -> ZoneInfo: + """A user's timezone setting, or UTC for anything that isn't a valid IANA name (a + bad or since-removed name in one user's settings must never crash the task for + everyone else).""" + try: + return ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError): + return ZoneInfo("UTC") + + +def is_valid_timezone(name: str) -> bool: + """For validating user input (reject a bad name with an error), as opposed to + resolve_timezone's silent fallback (never crash the periodic task over one user's + stale setting).""" + try: + ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError): + return False + return True diff --git a/src/scrobbler/federation/publishing/__init__.py b/src/scrobbler/federation/publishing/__init__.py index 61f04d5..0326dae 100644 --- a/src/scrobbler/federation/publishing/__init__.py +++ b/src/scrobbler/federation/publishing/__init__.py @@ -3,6 +3,6 @@ later now-playing. Shared machinery — idempotent publishing, addressing, fan-o deletion — lives in base.py. """ -from scrobbler.federation.publishing.base import delete_all_for, delete_post, publish +from scrobbler.federation.publishing.base import delete_all_for, delete_post, has_post, publish -__all__ = ["delete_all_for", "delete_post", "publish"] +__all__ = ["delete_all_for", "delete_post", "has_post", "publish"] diff --git a/src/scrobbler/federation/publishing/base.py b/src/scrobbler/federation/publishing/base.py index 9bd1118..ae28573 100644 --- a/src/scrobbler/federation/publishing/base.py +++ b/src/scrobbler/federation/publishing/base.py @@ -24,6 +24,17 @@ def _now() -> datetime: return datetime.now(UTC) +def has_post(user_id: int, kind: str, key: str) -> bool: + """Whether a post with this (user, kind, key) already exists (posted or since + deleted). Lets a caller skip expensive work — computing stats, say — before deciding + whether to call publish() at all.""" + full_key = f"{kind}:{key}" + return ( + db.session.scalar(db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key)) + is not None + ) + + def publish( user_id: int, username: str, diff --git a/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py new file mode 100644 index 0000000..697ee17 --- /dev/null +++ b/src/scrobbler/federation/publishing/weekly.py @@ -0,0 +1,100 @@ +"""Weekly summaries: for each sharing user with them on, once the Monday-09:00-local +posting gate has passed (see protocol/schedule.target_week), post about the Monday- +Sunday week that just ended. + +Empty weeks aren't posted. Since the target week only ever moves forward — once its own +gate has passed, it never becomes the target again — an empty week is never reconsidered +either, without needing a separate "skipped" marker. +""" + +import logging +from datetime import UTC, datetime + +from scrobbler.extensions import db +from scrobbler.federation import publishing +from scrobbler.federation.models import FederationSettings +from scrobbler.federation.protocol import content, schedule +from scrobbler.services import accounts, stats + +KIND = "weekly" +TOP_ARTISTS = 3 + +log = logging.getLogger(__name__) + + +def build_content(count: int, top_artists: list, top_tracks: list) -> tuple[str, str]: + headline = f"My week in music: {count} {content.plural(count, 'play')}" + text_lines = [headline] + html_parts = [content.paragraph(f"{content.escape(headline)}")] + + if top_artists: + text_lines.append( + "Top artists: " + + " ".join(f"{i}. {a.name} ({a.playcount})" for i, a in enumerate(top_artists, 1)) + ) + html_parts.append( + content.numbered_list( + [ + f"{content.escape(a.name)} — {a.playcount} " + f"{content.plural(a.playcount, 'play')}" + for a in top_artists + ] + ) + ) + + if top_tracks: + top = top_tracks[0] + words = content.plural(top.playcount, "play") + text_lines.append(f"Most played: {top.name} by {top.artist} ({top.playcount} {words})") + html_parts.append( + content.paragraph( + f"Most played: {content.escape(top.name)} by " + f"{content.escape(top.artist)} ({top.playcount} {words})" + ) + ) + + text_lines.append(content.hashtag_line()) + html_parts.append(content.paragraph(content.hashtag_line())) + return "\n".join(text_lines), "".join(html_parts) + + +def check_and_post(settings: FederationSettings, now_utc: datetime) -> str: + """For one user's settings, post their most recent eligible week if it's due and not + already posted. Returns a result: disabled, already_posted, skipped_empty or posted.""" + if not settings.post_weekly_summary: + return "disabled" + user = accounts.get_user(settings.user_id) + if user is None: # the account was deleted; federation_settings should follow, but be safe + return "disabled" + + tz = schedule.resolve_timezone(settings.timezone) + start, end, key = schedule.target_week(now_utc, tz) + if publishing.has_post(user.id, KIND, key): + return "already_posted" # the common case: checked before, nothing new to do + + count = stats.scrobble_count_between(user, start, end) + if count == 0: + return "skipped_empty" + + top_artists = stats.top_artists_between(user, start, end, limit=TOP_ARTISTS) + top_tracks = stats.top_tracks_between(user, start, end, limit=1) + text, html = build_content(count, top_artists, top_tracks) + post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html) + return "posted" if post is not None else "already_posted" # lost a race with another pass + + +def check_all(now_utc: datetime | None = None) -> None: + """Worker task (periodic): check every sharing user with weekly summaries on. One + user's failure is logged and doesn't stop the rest from being checked.""" + now_utc = now_utc or datetime.now(UTC) + settings_rows = db.session.scalars( + db.select(FederationSettings).filter_by(enabled=True, post_weekly_summary=True) + ).all() + for settings in settings_rows: + try: + check_and_post(settings, now_utc) + except Exception: + log.exception("weekly summary check failed for user %s", settings.user_id) + db.session.rollback() + else: + db.session.commit() diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index 2e274f5..70f6603 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -3,6 +3,7 @@ from scrobbler.extensions import db from scrobbler.federation import keys from scrobbler.federation.models import VISIBILITIES, FederationSettings +from scrobbler.federation.protocol.schedule import is_valid_timezone from scrobbler.services import accounts EDITABLE = ( @@ -13,6 +14,9 @@ EDITABLE = ( "indexable", "display_name", "bio", + "timezone", + "post_weekly_summary", + "post_milestones", ) @@ -44,6 +48,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 "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) was_enabled = bool(settings.enabled) for field, value in changes.items(): diff --git a/src/scrobbler/services/accounts.py b/src/scrobbler/services/accounts.py index c5e3bc2..66e65e2 100644 --- a/src/scrobbler/services/accounts.py +++ b/src/scrobbler/services/accounts.py @@ -40,6 +40,10 @@ def find_user(username: str) -> User | None: return db.session.scalar(db.select(User).where(func.lower(User.username) == username.lower())) +def get_user(user_id: int) -> User | None: + return db.session.get(User, user_id) + + def register(username: str, email: str, password: str) -> User: if not USERNAME_RE.match(username): raise AccountError( diff --git a/tests/test_federation_content.py b/tests/test_federation_content.py new file mode 100644 index 0000000..13af7dc --- /dev/null +++ b/tests/test_federation_content.py @@ -0,0 +1,101 @@ +"""Safe post content (protocol/content.py): escaping, and the weekly summary template +built on top of it (publishing/weekly.py's build_content).""" + +import pytest + +from scrobbler.federation.protocol import content +from scrobbler.federation.publishing.weekly import build_content +from scrobbler.services.stats import TopItem + + +def test_escape_neutralises_markup(): + assert content.escape("") == "<script>alert(1)</script>" + + +def test_escape_handles_ampersands_without_double_escaping(): + assert content.escape("Earth, Wind & Fire") == "Earth, Wind & Fire" + + +def test_escape_passes_through_emoji_and_non_latin_text(): + # Emoji and non-Latin scripts aren't HTML-significant, so they pass through untouched. + assert content.escape("Björk 🎵 坂本龍一") == "Björk 🎵 坂本龍一" + + +def test_escape_does_not_break_right_to_left_text(): + name = "محمد <عبده>" # Arabic text with embedded angle brackets + escaped = content.escape(name) + assert "<" not in escaped and ">" not in escaped + assert "محمد" in escaped # the Arabic letters are untouched + + +def test_paragraph_and_numbered_list_only_use_tags_mastodon_keeps(): + assert content.paragraph("hi") == "

hi

" + assert content.numbered_list(["a", "b"]) == "
  1. a
  2. b
" + + +@pytest.mark.parametrize( + ("count", "word"), [(0, "plays"), (1, "play"), (2, "plays"), (312, "plays")] +) +def test_plural(count, word): + assert content.plural(count, "play") == word + + +def test_hashtag_line_matches_the_vocab_hashtag_name(): + from scrobbler.federation.protocol import vocab + + assert content.hashtag_line() == vocab.hashtag(content.HASHTAG)["name"] + + +# --- The weekly summary template (uses the primitives above) -------------------------- + + +def test_build_content_escapes_hostile_names_in_both_text_and_html(): + artists = [TopItem(1, "", 5)] + tracks = [TopItem(1, 'Earth, Wind & Fire\'s "Anthem"', 3, artist="A & B", duration=200)] + text, html = build_content(8, artists, tracks) + + assert "