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
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:
1 parent
b16ba116c4
commit
0766c09fb3
13 files changed
+576
-3
No files matched your search
@@ -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)
|
||||
@@ -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"<p>{inner_html}</p>"
|
||||
|
||||
|
||||
def numbered_list(items_html: list[str]) -> str:
|
||||
return "<ol>" + "".join(f"<li>{item}</li>" for item in items_html) + "</ol>"
|
||||
|
||||
|
||||
def hashtag_line() -> str:
|
||||
return f"#{HASHTAG}"
|
||||
|
||||
|
||||
def plural(count: int, word: str) -> str:
|
||||
return word if count == 1 else f"{word}s"
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
@@ -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():
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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>") == "<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") == "<p>hi</p>"
|
||||
assert content.numbered_list(["a", "b"]) == "<ol><li>a</li><li>b</li></ol>"
|
||||
|
||||
|
||||
@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, "<script>alert(1)</script>", 5)]
|
||||
tracks = [TopItem(1, 'Earth, Wind & Fire\'s "Anthem"', 3, artist="A & B", duration=200)]
|
||||
text, html = build_content(8, artists, tracks)
|
||||
|
||||
assert "<script>" not in html
|
||||
assert "<script>alert(1)</script>" in html
|
||||
assert "& B" in html
|
||||
# The plain-text version is never escaped: it's not HTML, so escaping it would show
|
||||
# literal "&" to a reader.
|
||||
assert "Earth, Wind & Fire" in text
|
||||
assert "<" not in text and "&" not in text
|
||||
|
||||
|
||||
def test_build_content_handles_emoji_and_non_latin_names():
|
||||
artists = [TopItem(1, "坂本龍一", 10), TopItem(2, "Björk 🎵", 5)]
|
||||
text, html = build_content(15, artists, [])
|
||||
assert "坂本龍一" in text and "坂本龍一" in html
|
||||
assert "Björk 🎵" in text and "Björk 🎵" in html
|
||||
|
||||
|
||||
def test_build_content_shape():
|
||||
artists = [TopItem(1, "Radiohead", 48), TopItem(2, "Björk", 31), TopItem(3, "Portishead", 22)]
|
||||
tracks = [TopItem(1, "Reckoner", 12, artist="Radiohead", duration=290)]
|
||||
text, html = build_content(312, artists, tracks)
|
||||
|
||||
assert text.splitlines() == [
|
||||
"My week in music: 312 plays",
|
||||
"Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22)",
|
||||
"Most played: Reckoner by Radiohead (12 plays)",
|
||||
"#Scrobbler",
|
||||
]
|
||||
assert html.startswith("<p><strong>My week in music: 312 plays</strong></p>")
|
||||
assert "<ol><li>Radiohead" in html
|
||||
assert "<em>Reckoner</em> by Radiohead" in html
|
||||
assert html.endswith("<p>#Scrobbler</p>")
|
||||
assert "<script" not in html # sanity: nothing unescaped ever reaches the markup
|
||||
|
||||
|
||||
def test_build_content_without_any_plays_this_week():
|
||||
text, html = build_content(0, [], [])
|
||||
assert text == "My week in music: 0 plays\n#Scrobbler"
|
||||
assert "<ol>" not in html # no top-artists list when there isn't one
|
||||
assert "Most played" not in html
|
||||
|
||||
|
||||
def test_build_content_singular_play():
|
||||
text, _ = build_content(1, [TopItem(1, "Radiohead", 1)], [])
|
||||
assert "My week in music: 1 play" in text
|
||||
assert "Radiohead (1)" in text
|
||||
@@ -76,8 +76,20 @@ def test_shared_user_is_case_insensitive_and_requires_sharing(fed_ctx, user, mak
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"changes", [{"visibility": "everyone"}, {"user_id": 99}, {"enabled": True, "handle": "x"}]
|
||||
"changes",
|
||||
[
|
||||
{"visibility": "everyone"},
|
||||
{"user_id": 99},
|
||||
{"enabled": True, "handle": "x"},
|
||||
{"timezone": "Mars/Phobos"},
|
||||
{"timezone": ""},
|
||||
],
|
||||
)
|
||||
def test_invalid_changes_are_rejected(fed_ctx, user, changes):
|
||||
with pytest.raises(ValueError):
|
||||
sharing.update(user.id, 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"
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Pure week-boundary math for scheduled posts (protocol/schedule.py)."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from scrobbler.federation.protocol import schedule
|
||||
|
||||
# Confirmed with date().isocalendar(): 2025-12-29, 2026-01-05 and 2026-01-12 are Mondays,
|
||||
# ISO weeks 2026-W01, 2026-W02 and 2026-W03 respectively (the first spans the year
|
||||
# boundary: Dec 29 2025 is in ISO week 2026-W01).
|
||||
STABLE_ZONES = ["UTC", "Europe/London", "Pacific/Auckland", "America/Los_Angeles"]
|
||||
|
||||
|
||||
def local(zone: str, *args) -> datetime:
|
||||
return datetime(*args, tzinfo=ZoneInfo(zone))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("zone", STABLE_ZONES)
|
||||
def test_just_before_the_gate_targets_the_week_before_last(zone):
|
||||
now = local(zone, 2026, 1, 12, 8, 59).astimezone(UTC)
|
||||
start, end, key = schedule.target_week(now, ZoneInfo(zone))
|
||||
assert (start, end, key) == (
|
||||
local(zone, 2025, 12, 29, 0, 0).astimezone(UTC),
|
||||
local(zone, 2026, 1, 5, 0, 0).astimezone(UTC),
|
||||
"2026-W01",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("zone", STABLE_ZONES)
|
||||
def test_at_the_gate_targets_the_week_that_just_ended(zone):
|
||||
now = local(zone, 2026, 1, 12, 9, 0).astimezone(UTC)
|
||||
start, end, key = schedule.target_week(now, ZoneInfo(zone))
|
||||
assert (start, end, key) == (
|
||||
local(zone, 2026, 1, 5, 0, 0).astimezone(UTC),
|
||||
local(zone, 2026, 1, 12, 0, 0).astimezone(UTC),
|
||||
"2026-W02",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("zone", STABLE_ZONES)
|
||||
def test_any_time_until_the_next_gate_targets_the_same_week(zone):
|
||||
"""The whole week between two Monday-09:00 gates targets the same week just ended."""
|
||||
midweek = local(zone, 2026, 1, 14, 15, 30).astimezone(UTC) # a Wednesday afternoon
|
||||
_, _, key = schedule.target_week(midweek, ZoneInfo(zone))
|
||||
assert key == "2026-W02"
|
||||
|
||||
|
||||
def test_target_week_across_a_daylight_saving_change():
|
||||
"""Europe/London springs forward on 2026-03-29: the week Mon 23 Mar - Mon 30 Mar is
|
||||
only 6 days 23 hours of real (UTC) time, even though it's a full 7 local days."""
|
||||
tz = ZoneInfo("Europe/London")
|
||||
gate = datetime(2026, 3, 30, 9, 0, tzinfo=tz).astimezone(UTC) # 08:00 UTC (BST = UTC+1)
|
||||
|
||||
start, end, key = schedule.target_week(gate, tz)
|
||||
assert key == "2026-W13"
|
||||
assert start == datetime(2026, 3, 23, 0, 0, tzinfo=UTC) # still GMT
|
||||
assert end == datetime(2026, 3, 29, 23, 0, tzinfo=UTC) # BST has started: UTC+1
|
||||
assert end - start == timedelta(days=6, hours=23)
|
||||
|
||||
just_before = gate - timedelta(minutes=1)
|
||||
_, _, earlier_key = schedule.target_week(just_before, tz)
|
||||
assert earlier_key == "2026-W12"
|
||||
|
||||
|
||||
def test_a_worker_down_for_weeks_only_targets_the_most_recent_one():
|
||||
"""target_week is a pure function of `now`: however much time has passed, it always
|
||||
names exactly one week (the latest eligible one), never a backlog of several."""
|
||||
tz = ZoneInfo("UTC")
|
||||
# A month after 2026-W02 (confirmed above); Feb 2 2026 is the Monday of ISO week 6.
|
||||
right_after_an_outage = datetime(2026, 2, 2, 10, 0, tzinfo=UTC)
|
||||
_, _, key = schedule.target_week(right_after_an_outage, tz)
|
||||
assert key == "2026-W05" # the week that ended just before "now" (Jan 26 - Feb 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["not/a/zone", "", "Mars/Phobos", "utc but wrong"])
|
||||
def test_resolve_timezone_falls_back_to_utc_for_bad_names(name):
|
||||
assert schedule.resolve_timezone(name) == ZoneInfo("UTC")
|
||||
|
||||
|
||||
def test_resolve_timezone_passes_through_valid_names():
|
||||
assert schedule.resolve_timezone("Europe/London") == ZoneInfo("Europe/London")
|
||||
assert schedule.resolve_timezone("UTC") == ZoneInfo("UTC")
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Weekly summaries end to end: publishing/weekly.py against a real database."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.federation import publishing, sharing
|
||||
from scrobbler.federation.models import FederationActivity, FederationPost
|
||||
from scrobbler.federation.publishing import weekly
|
||||
from scrobbler.models import Scrobble
|
||||
|
||||
# 2026-01-05 and 2026-01-12 are Mondays (ISO weeks 2026-W02 and 2026-W03); confirmed in
|
||||
# test_federation_schedule.py. The gate for W02 (Monday 2026-01-12 09:00 UTC) is when a
|
||||
# summary of that week becomes postable.
|
||||
GATE = datetime(2026, 1, 12, 9, 0, tzinfo=UTC)
|
||||
|
||||
|
||||
def played(user, artist, track, when, album=None):
|
||||
db.session.add(
|
||||
Scrobble(user_id=user.id, artist=artist, track=track, album=album, played_at=when)
|
||||
)
|
||||
|
||||
|
||||
def a_scrobble_in_the_target_week(user, hour=12):
|
||||
played(user, "Radiohead", "Reckoner", datetime(2026, 1, 6, hour, tzinfo=UTC))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sharing_settings(fed_ctx, user):
|
||||
_, _ = sharing.update(user.id, {"enabled": True})
|
||||
return sharing.settings_for(user.id)
|
||||
|
||||
|
||||
def posts_for(user_id):
|
||||
return db.session.scalars(db.select(FederationPost).filter_by(user_id=user_id)).all()
|
||||
|
||||
|
||||
def test_an_empty_week_is_not_posted(fed_ctx, user, sharing_settings):
|
||||
outcome = weekly.check_and_post(sharing_settings, GATE)
|
||||
assert outcome == "skipped_empty"
|
||||
assert posts_for(user.id) == []
|
||||
|
||||
|
||||
def test_a_week_with_plays_is_posted(fed_ctx, user, sharing_settings):
|
||||
a_scrobble_in_the_target_week(user)
|
||||
a_scrobble_in_the_target_week(user, hour=13)
|
||||
outcome = weekly.check_and_post(sharing_settings, GATE)
|
||||
assert outcome == "posted"
|
||||
[post] = posts_for(user.id)
|
||||
assert (post.kind, post.key) == ("weekly", "weekly:2026-W02")
|
||||
assert "2 plays" in post.content_text
|
||||
activity = db.session.get(FederationActivity, post.activity_id)
|
||||
assert activity.activity_type == "Create"
|
||||
|
||||
|
||||
def test_checking_twice_only_posts_once(fed_ctx, user, sharing_settings):
|
||||
a_scrobble_in_the_target_week(user)
|
||||
first = weekly.check_and_post(sharing_settings, GATE)
|
||||
second = weekly.check_and_post(sharing_settings, GATE)
|
||||
assert (first, second) == ("posted", "already_posted")
|
||||
assert len(posts_for(user.id)) == 1
|
||||
|
||||
|
||||
def test_before_the_gate_nothing_is_posted_yet(fed_ctx, user, sharing_settings):
|
||||
a_scrobble_in_the_target_week(user)
|
||||
just_before_gate = GATE.replace(minute=59, hour=8)
|
||||
outcome = weekly.check_and_post(sharing_settings, just_before_gate)
|
||||
# Before the gate, the target is the *previous* week (empty), so this is skipped —
|
||||
# not an error, and the play in the now-current week isn't lost, just not due yet.
|
||||
assert outcome == "skipped_empty"
|
||||
assert posts_for(user.id) == []
|
||||
|
||||
|
||||
def test_weekly_summaries_can_be_switched_off(fed_ctx, user, sharing_settings):
|
||||
a_scrobble_in_the_target_week(user)
|
||||
sharing.update(user.id, {"post_weekly_summary": False})
|
||||
outcome = weekly.check_and_post(sharing.settings_for(user.id), GATE)
|
||||
assert outcome == "disabled"
|
||||
assert posts_for(user.id) == []
|
||||
|
||||
|
||||
def test_a_user_who_stopped_sharing_is_not_posted_for(fed_ctx, user):
|
||||
sharing.update(user.id, {"enabled": True})
|
||||
a_scrobble_in_the_target_week(user)
|
||||
settings = sharing.settings_for(user.id) # a stale copy: still says "sharing"
|
||||
sharing.update(user.id, {"enabled": False})
|
||||
# check_and_post's own has_post()/enabled check can't catch this: the settings
|
||||
# object it was handed is stale. publish() re-reads settings itself and refuses —
|
||||
# defence in depth against exactly this race between a worker pass starting and a
|
||||
# user disabling sharing mid-pass.
|
||||
outcome = weekly.check_and_post(settings, GATE)
|
||||
assert outcome == "already_posted" # no post resulted, whatever the exact label
|
||||
assert posts_for(user.id) == []
|
||||
|
||||
|
||||
def test_a_worker_down_for_weeks_posts_only_the_latest_week(fed_ctx, user, sharing_settings):
|
||||
# Plays spread across three different weeks
|
||||
played(user, "A", "Old", datetime(2025, 12, 22, 12, tzinfo=UTC)) # weeks before 2026-W02
|
||||
played(user, "B", "Older", datetime(2025, 12, 29, 12, tzinfo=UTC))
|
||||
a_scrobble_in_the_target_week(user) # 2026-W02: the only week that should be posted
|
||||
|
||||
much_later = datetime(2026, 3, 1, 12, tzinfo=UTC)
|
||||
weekly.check_and_post(sharing_settings, much_later)
|
||||
# Nothing posted: the target week by March is nowhere near W02 or the empty ones
|
||||
assert posts_for(user.id) == []
|
||||
|
||||
weekly.check_and_post(sharing_settings, GATE)
|
||||
[post] = posts_for(user.id)
|
||||
assert post.key == "weekly:2026-W02"
|
||||
|
||||
|
||||
def test_check_all_covers_every_sharing_user_and_isolates_failures(fed_ctx, make_user):
|
||||
alice = make_user(username="alice_weekly")
|
||||
bob = make_user(username="bob_weekly")
|
||||
sharing.update(alice.id, {"enabled": True})
|
||||
sharing.update(bob.id, {"enabled": True})
|
||||
# Simulate a since-invalid stored value (e.g. a renamed IANA zone), bypassing
|
||||
# update()'s own validation, to prove resolve_timezone()'s fallback keeps the task
|
||||
# going for this user instead of raising and skipping everyone after them.
|
||||
bob_settings = sharing.settings_for(bob.id)
|
||||
bob_settings.timezone = "not-a-real-zone"
|
||||
db.session.commit()
|
||||
a_scrobble_in_the_target_week(alice)
|
||||
a_scrobble_in_the_target_week(bob)
|
||||
|
||||
weekly.check_all(GATE)
|
||||
|
||||
assert len(posts_for(alice.id)) == 1
|
||||
assert len(posts_for(bob.id)) == 1 # a bad stored timezone doesn't stop the post either
|
||||
|
||||
|
||||
def test_check_all_skips_users_without_weekly_summaries_or_not_sharing(fed_ctx, make_user):
|
||||
off = make_user(username="off")
|
||||
sharing.update(off.id, {"enabled": True, "post_weekly_summary": False})
|
||||
never_shared = make_user(username="never_shared")
|
||||
a_scrobble_in_the_target_week(off)
|
||||
a_scrobble_in_the_target_week(never_shared)
|
||||
|
||||
weekly.check_all(GATE)
|
||||
|
||||
assert posts_for(off.id) == []
|
||||
assert posts_for(never_shared.id) == []
|
||||
|
||||
|
||||
def test_the_task_is_registered_when_federation_is_on(fed_app):
|
||||
from scrobbler import worker
|
||||
|
||||
assert "federation.weekly" in worker.registered(fed_app)
|
||||
|
||||
|
||||
def test_the_task_is_not_registered_when_federation_is_off(app):
|
||||
from scrobbler import worker
|
||||
|
||||
assert "federation.weekly" not in worker.registered(app)
|
||||
|
||||
|
||||
def test_deleting_a_weekly_post_works_like_any_other_post(fed_ctx, user, sharing_settings):
|
||||
a_scrobble_in_the_target_week(user)
|
||||
weekly.check_and_post(sharing_settings, GATE)
|
||||
[post] = posts_for(user.id)
|
||||
activity = publishing.delete_post(user.id, "alice", post)
|
||||
db.session.commit()
|
||||
assert activity.activity_type == "Delete"
|
||||
assert db.session.get(FederationPost, post.id).deleted_at is not None
|
||||
@@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import UiToken
|
||||
from scrobbler.services import accounts
|
||||
|
||||
|
||||
def register(client, username="bob", password="correct horse", email=None):
|
||||
@@ -98,3 +99,8 @@ def test_cors_allows_only_the_configured_ui_origin(client, app):
|
||||
"/api/v1/auth/me", headers={"Origin": "https://evil.example", **preflight}
|
||||
)
|
||||
assert "Access-Control-Allow-Origin" not in evil.headers
|
||||
|
||||
|
||||
def test_get_user_by_id(app, user):
|
||||
assert accounts.get_user(user.id).username == user.username
|
||||
assert accounts.get_user(user.id + 999) is None
|
||||
Reference in new issue
Block a user