API and web UI for posts, previews and post settings (phase 3, step 8)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m0s
CI / test (push) Successful in 2m53s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m0s
CI / test (push) Successful in 2m53s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
/api/v1/federation gains:
- GET /posts, DELETE /posts/{id}: manage your own posts from the UI.
- GET /preview/weekly: what the weekly summary would say right now, for
the week still in progress - never posted or stored. Backed by a new
weekly.preview() and schedule.current_week_start().
- GET /profiles/{username}/posts/{post_uuid} (public, unauthenticated):
backs the UI's post page, which can't itself speak ActivityPub.
Settings gain timezone/post_weekly_summary/post_milestones, already
present in sharing.EDITABLE since phase 3 step 2 but never added to
SharingSettingsSchema, so the API was silently dropping them from
responses. timezone validates against the same is_valid_timezone() the
service layer uses, with a dedicated marshmallow validator.
Fixed a real gap found while wiring the post page: ids.post_page_url()
took a username but never put it in the URL, so post.html would have
had no way to know whose post to look up. It's now ?u=<username>&id=<uuid>.
Sharing page gets a "What to post" section (weekly summary and
milestones toggles, a timezone field with a browser-supplied IANA
datalist where Intl.supportedValuesOf exists, and a live preview).
New posts.html lists a user's posts with delete (mirroring followers.js's
confirm-before-destructive-action pattern); new post.html is the public
landing page for a post's `url`, reached by browsers redirected from the
raw ActivityPub endpoint.
Verified by hand against a local dev server and a real browser: sign in,
enable sharing, preview and publish, list and delete a post, and follow
the ActivityPub redirect through to the public post page and its 404
after deletion - fixed one bug found this way (the preview box was
collapsing the summary's line breaks).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
d4f3607eef
commit
0acce9b948
16 files changed
+865
-8
No files matched your search
@@ -5,17 +5,21 @@ from flask_smorest import Blueprint, abort
|
||||
|
||||
from scrobbler.api.decorators import authenticated
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.federation import activities, publishing, sharing
|
||||
from scrobbler.federation import activities, ids, publishing, sharing
|
||||
from scrobbler.federation import followers as follower_state
|
||||
from scrobbler.federation import metrics as fed_metrics
|
||||
from scrobbler.federation.models import FederationBlock, FederationFollower
|
||||
from scrobbler.federation.models import FederationBlock, FederationFollower, FederationPost
|
||||
from scrobbler.federation.publishing import weekly
|
||||
from scrobbler.federation.schemas import (
|
||||
BlockSchema,
|
||||
FollowerListArgsSchema,
|
||||
FollowerSchema,
|
||||
PostSchema,
|
||||
PublicPostSchema,
|
||||
PublicProfileSchema,
|
||||
SharingSettingsSchema,
|
||||
SharingSettingsUpdateSchema,
|
||||
WeeklyPreviewSchema,
|
||||
)
|
||||
from scrobbler.schemas import ErrorSchema
|
||||
|
||||
@@ -86,6 +90,73 @@ def update_settings(changes):
|
||||
return _settings_body(g.user, settings)
|
||||
|
||||
|
||||
@blp.route("/preview/weekly", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, WeeklyPreviewSchema)
|
||||
def preview_weekly():
|
||||
"""Preview this week's summary
|
||||
|
||||
What it would say right now, for the week still in progress. Never posted or stored.
|
||||
"""
|
||||
result = weekly.preview(g.user.id)
|
||||
if result is None: # pragma: no cover - g.user is always a real, current account
|
||||
abort(404, code="not_found", message="No such user")
|
||||
text, html = result
|
||||
return {"text": text, "html": html}
|
||||
|
||||
|
||||
def _post_body(post: FederationPost) -> dict:
|
||||
return {
|
||||
"id": post.id,
|
||||
"kind": post.kind,
|
||||
"text": post.content_text,
|
||||
"visibility": post.visibility,
|
||||
"created_at": post.created_at,
|
||||
"deleted_at": post.deleted_at,
|
||||
}
|
||||
|
||||
|
||||
@blp.route("/posts", methods=["GET"])
|
||||
@authenticated(blp)
|
||||
@blp.response(200, PostSchema(many=True))
|
||||
def list_posts():
|
||||
"""Your posts
|
||||
|
||||
Newest first, including deleted ones (their text stays visible to you; deleted_at
|
||||
shows when).
|
||||
"""
|
||||
posts = db.session.scalars(
|
||||
db.select(FederationPost)
|
||||
.filter_by(user_id=g.user.id)
|
||||
.order_by(FederationPost.created_at.desc())
|
||||
).all()
|
||||
return [_post_body(p) for p in posts]
|
||||
|
||||
|
||||
def _own_post(post_id: int) -> FederationPost:
|
||||
post = db.session.get(FederationPost, post_id)
|
||||
if post is None or post.user_id != g.user.id:
|
||||
abort(404, code="not_found", message="No such post")
|
||||
return post
|
||||
|
||||
|
||||
@blp.route("/posts/<int:post_id>", methods=["DELETE"])
|
||||
@authenticated(blp)
|
||||
@blp.response(204)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No such post")
|
||||
@blp.alt_response(409, schema=ErrorSchema, description="Already deleted")
|
||||
def delete_post(post_id):
|
||||
"""Delete a post
|
||||
|
||||
Sends a Delete to whoever received it.
|
||||
"""
|
||||
post = _own_post(post_id)
|
||||
activity = publishing.delete_post(g.user.id, g.user.username, post)
|
||||
if activity is None:
|
||||
abort(409, code="already_deleted", message="That post is already deleted.")
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@blp.route("/profiles/<string:username>", methods=["GET"])
|
||||
@blp.response(200, PublicProfileSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="No one sharing with that name")
|
||||
@@ -108,6 +179,38 @@ def public_profile(username):
|
||||
}
|
||||
|
||||
|
||||
@blp.route("/profiles/<string:username>/posts/<string:post_uuid>", methods=["GET"])
|
||||
@blp.response(200, PublicPostSchema)
|
||||
@blp.alt_response(404, schema=ErrorSchema, description="Not found, not public, or deleted")
|
||||
def public_post(username, post_uuid):
|
||||
"""A public or unlisted post
|
||||
|
||||
For the web UI's post page (the browser landing spot for a Note's `url`, since it
|
||||
can't itself speak ActivityPub).
|
||||
"""
|
||||
found = sharing.shared_user(username)
|
||||
if found is not None:
|
||||
user, settings = found
|
||||
post = publishing.find_by_note_id(user.id, ids.note_url(username, post_uuid))
|
||||
else:
|
||||
post = None
|
||||
if (
|
||||
post is None
|
||||
or post.deleted_at is not None
|
||||
or post.visibility not in publishing.LISTED_VISIBILITIES
|
||||
):
|
||||
fed_metrics.lookups_total.labels(kind="post", result="not_found").inc()
|
||||
abort(404, code="not_found", message="No such post.")
|
||||
fed_metrics.lookups_total.labels(kind="post", result="found").inc()
|
||||
return {
|
||||
"text": post.content_text,
|
||||
"html": post.content_html,
|
||||
"created_at": post.created_at,
|
||||
"display_name": settings.display_name or user.username,
|
||||
**{k: v for k, v in _identity(user.username).items() if k != "actor_url"},
|
||||
}
|
||||
|
||||
|
||||
# --- Followers ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -37,8 +37,9 @@ def note_url(username: str, post_uuid: str) -> str:
|
||||
|
||||
|
||||
def post_page_url(username: str, post_uuid: str) -> str:
|
||||
"""Where a browser following the Note's `url` lands, in the web UI."""
|
||||
return f"{current_app.config['UI_BASE_URL']}/post.html?id={post_uuid}"
|
||||
"""Where a browser following the Note's `url` lands, in the web UI. Carries the
|
||||
username too: the UI page has no other way to know whose post to look up."""
|
||||
return f"{current_app.config['UI_BASE_URL']}/post.html?u={username}&id={post_uuid}"
|
||||
|
||||
|
||||
def username_from_actor_id(uri: str | None) -> str | None:
|
||||
|
||||
@@ -30,6 +30,14 @@ def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, st
|
||||
return start_local.astimezone(UTC), end_local.astimezone(UTC), f"{year}-W{week:02d}"
|
||||
|
||||
|
||||
def current_week_start(now_utc: datetime, tz: ZoneInfo) -> datetime:
|
||||
"""The UTC instant of this week's Monday 00:00 local time - the week still in
|
||||
progress, not yet postable. For previewing what a summary would say so far."""
|
||||
local_now = now_utc.astimezone(tz)
|
||||
monday = local_now.date() - timedelta(days=local_now.weekday())
|
||||
return datetime(monday.year, monday.month, monday.day, tzinfo=tz).astimezone(UTC)
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -11,7 +11,7 @@ import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.federation import publishing
|
||||
from scrobbler.federation import publishing, sharing
|
||||
from scrobbler.federation.models import FederationSettings
|
||||
from scrobbler.federation.protocol import content, schedule
|
||||
from scrobbler.services import accounts, stats
|
||||
@@ -83,6 +83,22 @@ def check_and_post(settings: FederationSettings, now_utc: datetime) -> str:
|
||||
return "posted" if post is not None else "already_posted" # lost a race with another pass
|
||||
|
||||
|
||||
def preview(user_id: int, now_utc: datetime | None = None) -> tuple[str, str] | None:
|
||||
"""What a weekly summary would say right now, for the week still in progress. Never
|
||||
stored or posted: for the Sharing page's live preview. None if the account is gone."""
|
||||
user = accounts.get_user(user_id)
|
||||
if user is None:
|
||||
return None
|
||||
settings = sharing.settings_for(user_id)
|
||||
tz = schedule.resolve_timezone(settings.timezone)
|
||||
now_utc = now_utc or datetime.now(UTC)
|
||||
start = schedule.current_week_start(now_utc, tz)
|
||||
count = stats.scrobble_count_between(user, start, now_utc)
|
||||
top_artists = stats.top_artists_between(user, start, now_utc, limit=TOP_ARTISTS)
|
||||
top_tracks = stats.top_tracks_between(user, start, now_utc, limit=1)
|
||||
return build_content(count, top_artists, top_tracks)
|
||||
|
||||
|
||||
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."""
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
from marshmallow import Schema, fields, validate
|
||||
from marshmallow import Schema, ValidationError, fields, validate
|
||||
|
||||
from scrobbler.federation.models import VISIBILITIES
|
||||
from scrobbler.federation.protocol.schedule import is_valid_timezone
|
||||
|
||||
|
||||
def _valid_timezone(value: str) -> None:
|
||||
if not is_valid_timezone(value):
|
||||
raise ValidationError("Not a known time zone.")
|
||||
|
||||
|
||||
class SharingSettingsSchema(Schema):
|
||||
@@ -20,6 +26,24 @@ class SharingSettingsSchema(Schema):
|
||||
indexable = fields.Boolean(metadata={"description": "Posts may be indexed for search"})
|
||||
display_name = fields.String(allow_none=True, validate=validate.Length(max=100))
|
||||
bio = fields.String(allow_none=True, validate=validate.Length(max=500))
|
||||
timezone = fields.String(
|
||||
validate=_valid_timezone,
|
||||
metadata={
|
||||
"description": (
|
||||
"IANA time zone, e.g. `Europe/London`. Decides when a week ends for the "
|
||||
"weekly summary."
|
||||
),
|
||||
"example": "Europe/London",
|
||||
},
|
||||
)
|
||||
post_weekly_summary = fields.Boolean(
|
||||
metadata={"description": "Post a weekly summary of your listening"}
|
||||
)
|
||||
post_milestones = fields.Boolean(
|
||||
metadata={
|
||||
"description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them"
|
||||
}
|
||||
)
|
||||
handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"})
|
||||
actor_url = fields.String(dump_only=True)
|
||||
profile_url = fields.String(dump_only=True)
|
||||
@@ -61,3 +85,28 @@ class BlockSchema(Schema):
|
||||
display_name = fields.String(allow_none=True)
|
||||
actor_url = fields.String()
|
||||
since = fields.DateTime()
|
||||
|
||||
|
||||
class PostSchema(Schema):
|
||||
id = fields.Integer()
|
||||
kind = fields.String(metadata={"description": "weekly or milestone"})
|
||||
text = fields.String()
|
||||
visibility = fields.String()
|
||||
created_at = fields.DateTime()
|
||||
deleted_at = fields.DateTime(allow_none=True)
|
||||
|
||||
|
||||
class WeeklyPreviewSchema(Schema):
|
||||
text = fields.String()
|
||||
html = fields.String()
|
||||
|
||||
|
||||
class PublicPostSchema(Schema):
|
||||
"""A public or unlisted post, for the web UI's post page (post.html)."""
|
||||
|
||||
text = fields.String()
|
||||
html = fields.String()
|
||||
created_at = fields.DateTime()
|
||||
display_name = fields.String()
|
||||
handle = fields.String(metadata={"example": "@alice@scrobble.example"})
|
||||
profile_url = fields.String()
|
||||
Reference in new issue
Block a user