Weekly summary task (phase 3, step 5)
CI / validate-monitoring (push) Successful in 10s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m2s
CI / test (push) Successful in 2m40s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

protocol/schedule.py (pure): target_week(now_utc, tz) resolves to
exactly one Monday-Sunday week — the most recent one whose Monday
09:00-local posting gate has passed — computed via wall-clock
arithmetic in the user's own zone so it's correct across a DST change
(a week can be 6h23/7h01 of real time, never silently 7 flat days).
Because it's a pure function of "now", a worker that was down for
weeks naturally catches up with one post, not a backlog. Also
resolve_timezone()/is_valid_timezone() for a settings field that can
otherwise crash a task or silently do nothing forever.

protocol/content.py (pure): the small HTML subset shared by every post
kind (p, strong, em, ol, li), with escaping split from formatting so a
hostile artist/track name can't inject markup.

publishing/weekly.py: build_content() (the template) and
check_and_post()/check_all() (the federation.weekly periodic task,
every 15 minutes). An empty week is simply never posted, and — since
the target week only ever advances — never reconsidered either, with
no separate marker needed. has_post() lets the common "already posted
this week" pass skip the stats queries entirely.

Core: accounts.get_user(id) (federation needs it and can't import the
User model directly); sharing.EDITABLE and update() gain
timezone/post_weekly_summary/post_milestones, with the same
now-not-later validation visibility already had.

Tested: the DST week and gate boundaries against real computed
reference dates (not guessed ones — one guess was wrong and the test
caught it before it shipped), hostile/emoji/RTL names in the template,
and the full task against a real database (empty vs non-empty weeks,
posting twice, disabled settings, a worker down for weeks, a bad
stored timezone not stopping other users).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Sonnet 5 committed 2026-09-26 12:02:02 +01:00
1 parent b16ba116c4
commit 0766c09fb3
13 files changed
+576 -3

No files matched your search

@@ -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"<strong>{content.escape(headline)}</strong>")]
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: <em>{content.escape(top.name)}</em> 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()