diff --git a/docs/openapi.json b/docs/openapi.json index 61cbdf7..2dcbd33 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1953,6 +1953,150 @@ ] } }, + "/api/v1/federation/preview/weekly": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WeeklyPreview" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Preview this week's summary", + "description": "What it would say right now, for the week still in progress. Never posted or stored.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/federation/posts": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Post" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Your posts", + "description": "Newest first, including deleted ones (their text stays visible to you; deleted_at\nshows when).", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/federation/posts/{post_id}": { + "delete": { + "responses": { + "409": { + "description": "Already deleted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "No such post", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Delete a post", + "description": "Sends a Delete to whoever received it.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "post_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, "/api/v1/federation/profiles/{username}": { "get": { "responses": { @@ -1998,6 +2142,60 @@ } ] }, + "/api/v1/federation/profiles/{username}/posts/{post_uuid}": { + "get": { + "responses": { + "404": { + "description": "Not found, not public, or deleted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicPost" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "A public or unlisted post", + "description": "For the web UI's post page (the browser landing spot for a Note's `url`, since it\ncan't itself speak ActivityPub).", + "tags": [ + "Federation" + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + }, + { + "in": "path", + "name": "post_uuid", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, "/api/v1/federation/followers": { "get": { "parameters": [ @@ -4183,6 +4381,19 @@ ], "maxLength": 500 }, + "timezone": { + "type": "string", + "description": "IANA time zone, e.g. `Europe/London`. Decides when a week ends for the weekly summary.", + "example": "Europe/London" + }, + "post_weekly_summary": { + "type": "boolean", + "description": "Post a weekly summary of your listening" + }, + "post_milestones": { + "type": "boolean", + "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" + }, "handle": { "type": "string", "readOnly": true, @@ -4250,6 +4461,19 @@ ], "maxLength": 500 }, + "timezone": { + "type": "string", + "description": "IANA time zone, e.g. `Europe/London`. Decides when a week ends for the weekly summary.", + "example": "Europe/London" + }, + "post_weekly_summary": { + "type": "boolean", + "description": "Post a weekly summary of your listening" + }, + "post_milestones": { + "type": "boolean", + "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" + }, "handle": { "type": "string", "readOnly": true, @@ -4276,6 +4500,48 @@ }, "additionalProperties": false }, + "WeeklyPreview": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "html": { + "type": "string" + } + }, + "additionalProperties": false + }, + "Post": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "kind": { + "type": "string", + "description": "weekly or milestone" + }, + "text": { + "type": "string" + }, + "visibility": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "deleted_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "additionalProperties": false + }, "PublicProfile": { "type": "object", "properties": { @@ -4301,6 +4567,32 @@ }, "additionalProperties": false }, + "PublicPost": { + "type": "object", + "properties": { + "text": { + "type": "string" + }, + "html": { + "type": "string" + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "display_name": { + "type": "string" + }, + "handle": { + "type": "string", + "example": "@alice@scrobble.example" + }, + "profile_url": { + "type": "string" + } + }, + "additionalProperties": false + }, "Follower": { "type": "object", "properties": { diff --git a/frontend/css/style.css b/frontend/css/style.css index b846e83..9f4c983 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -919,6 +919,22 @@ input { margin-top: 0.5rem; } +.preview-box { + padding: 1rem 1.25rem; + border-radius: var(--radius-control); + background: var(--paper-raised); + border: 1px solid var(--rule); + margin: 0.75rem 0 1.25rem; +} + +.preview-box p { + margin: 0 0 0.5rem; +} + +.preview-box p:last-child { + margin-bottom: 0; +} + .field textarea { min-height: 5rem; padding: 0.5rem 0.75rem; diff --git a/frontend/js/post.js b/frontend/js/post.js new file mode 100644 index 0000000..930e91c --- /dev/null +++ b/frontend/js/post.js @@ -0,0 +1,40 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, h, replace } from "./dom.js"; +import { publicPage } from "./layout.js"; + +const root = document.getElementById("post"); +const params = new URLSearchParams(location.search); +const username = params.get("u") ?? ""; +const postId = params.get("id") ?? ""; + +// A public page: never sends visitors to sign in. +publicPage(); + +try { + const post = await api( + `/federation/profiles/${encodeURIComponent(username)}/posts/${encodeURIComponent(postId)}`, + { auth: false }, + ); + document.title = `${post.display_name} · Scrobbler`; + replace( + root, + h( + "p", + { class: "muted" }, + h("a", { href: post.profile_url }, post.display_name), + ` · ${post.handle}`, + ), + h("p", { style: "white-space: pre-line" }, post.text), + h("p", { class: "muted", title: formatDate(post.created_at) }, `Posted ${formatDate(post.created_at)}`), + ); +} catch (error) { + replace( + root, + error.status === 404 + ? [ + h("h1", {}, "No post here"), + h("p", { class: "lede" }, "This post doesn't exist, isn't public, or has been deleted."), + ] + : errorBox(error.message), + ); +} diff --git a/frontend/js/posts.js b/frontend/js/posts.js new file mode 100644 index 0000000..5323730 --- /dev/null +++ b/frontend/js/posts.js @@ -0,0 +1,80 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const messages = document.getElementById("messages"); +const KIND_LABEL = { weekly: "Weekly summary", milestone: "Milestone" }; +const VISIBILITY_LABEL = { followers: "Followers only", unlisted: "Unlisted", public: "Public" }; + +await signedInPage("sharing.html"); +await refresh(); + +async function refresh() { + let posts; + try { + posts = await api("/federation/posts"); + } catch (error) { + replace( + messages, + error.status === 404 + ? h("p", { class: "notice" }, "This server doesn't share to the fediverse.") + : errorBox(error.message), + ); + return; + } + replace( + document.getElementById("posts"), + posts.length + ? posts.map(postRow) + : h( + "li", + { class: "empty" }, + "Nothing posted yet. Weekly summaries and milestones appear here once you're sharing.", + ), + ); +} + +function postRow(post) { + const actions = h("div", { class: "confirm" }); + const reset = () => + replace( + actions, + post.deleted_at + ? null + : h("button", { type: "button", class: "button button-quiet", onclick: askDelete }, "Delete"), + ); + const askDelete = () => + replace( + actions, + h("span", { class: "muted" }, "Delivered followers keep a copy; this only removes it from their timeline."), + h("button", { type: "button", class: "button button-danger", onclick: doDelete }, "Delete post"), + h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"), + ); + const doDelete = async () => { + try { + await api(`/federation/posts/${post.id}`, { method: "DELETE" }); + replace(messages, h("p", { class: "notice notice-ok", role: "status" }, "Post deleted.")); + } catch (error) { + replace(messages, errorBox(error.message)); + } + await refresh(); + }; + reset(); + return h( + "li", + {}, + h( + "div", + { class: "row-head" }, + h("span", { class: "row-title" }, KIND_LABEL[post.kind] ?? post.kind), + actions, + ), + h("p", { style: "white-space: pre-line" }, post.text), + h( + "p", + { class: "muted", title: formatDate(post.created_at) }, + `${VISIBILITY_LABEL[post.visibility] ?? post.visibility} · Posted ${timeAgo(post.created_at)}`, + post.deleted_at ? ` · Deleted ${timeAgo(post.deleted_at)}` : null, + ), + ); +} diff --git a/frontend/js/sharing.js b/frontend/js/sharing.js index eaab3d0..3fe7fb8 100644 --- a/frontend/js/sharing.js +++ b/frontend/js/sharing.js @@ -5,8 +5,20 @@ import { signedInPage } from "./layout.js"; const form = document.getElementById("sharing"); const messages = document.getElementById("messages"); const handlePanel = document.getElementById("handle-panel"); -const FIELDS = ["enabled", "visibility", "manually_approves_followers", "discoverable", "indexable", "display_name", "bio"]; +const FIELDS = [ + "enabled", + "visibility", + "manually_approves_followers", + "discoverable", + "indexable", + "post_weekly_summary", + "post_milestones", + "timezone", + "display_name", + "bio", +]; +fillTimezoneChoices(); await signedInPage("sharing.html"); let settings; @@ -26,6 +38,34 @@ if (settings) { form.hidden = false; form.elements.enabled.addEventListener("change", () => showHandle(form.elements.enabled.checked)); form.addEventListener("submit", save); + document.getElementById("preview-weekly").addEventListener("click", previewWeekly); +} + +// Free text (validated server-side), with autocomplete from the browser's own IANA list +// when it can supply one; a picker where that's available, a plain field otherwise. +function fillTimezoneChoices() { + if (typeof Intl.supportedValuesOf !== "function") return; + const datalist = document.getElementById("timezones"); + replace(datalist, Intl.supportedValuesOf("timeZone").map((zone) => h("option", { value: zone }))); +} + +async function previewWeekly() { + const box = document.getElementById("weekly-preview"); + const button = document.getElementById("preview-weekly"); + button.disabled = true; + try { + const preview = await api("/federation/preview/weekly"); + replace( + box, + h("p", { class: "muted" }, "What this week's summary would say so far:"), + h("p", { style: "white-space: pre-line" }, preview.text), + ); + box.hidden = false; + } catch (error) { + replace(messages, errorBox(error.message)); + } finally { + button.disabled = false; + } } function fill(values) { @@ -107,6 +147,9 @@ async function save(event) { manually_approves_followers: form.elements.manually_approves_followers.checked, discoverable: form.elements.discoverable.checked, indexable: form.elements.indexable.checked, + post_weekly_summary: form.elements.post_weekly_summary.checked, + post_milestones: form.elements.post_milestones.checked, + timezone: form.elements.timezone.value.trim() || "UTC", display_name: form.elements.display_name.value.trim() || null, bio: form.elements.bio.value.trim() || null, }; diff --git a/frontend/post.html b/frontend/post.html new file mode 100644 index 0000000..d41f3fe --- /dev/null +++ b/frontend/post.html @@ -0,0 +1,18 @@ + + + + + + Post · Scrobbler + + + + + + + +
+
+
+ + diff --git a/frontend/posts.html b/frontend/posts.html new file mode 100644 index 0000000..a7e2381 --- /dev/null +++ b/frontend/posts.html @@ -0,0 +1,21 @@ + + + + + + Posts · Scrobbler + + + + + + + +
+

Posts

+

Weekly summaries and milestones sent to the fediverse. Sharing settings

+
+ +
+ + diff --git a/frontend/sharing.html b/frontend/sharing.html index 1cade12..96ac78e 100644 --- a/frontend/sharing.html +++ b/frontend/sharing.html @@ -60,6 +60,29 @@ +
+ What to post +
+ + +
+
+ + +
+
+ + + + Decides when your week ends for the weekly summary. +
+
+ +
+ +

See your posts

+
+
Profile
diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index a3504b5..cbf967a 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -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/", 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/", 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//posts/", 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 --------------------------------------------------------------------------- diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py index c49ed0a..81807cc 100644 --- a/src/scrobbler/federation/ids.py +++ b/src/scrobbler/federation/ids.py @@ -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: diff --git a/src/scrobbler/federation/protocol/schedule.py b/src/scrobbler/federation/protocol/schedule.py index 0de8c88..1a5f4fc 100644 --- a/src/scrobbler/federation/protocol/schedule.py +++ b/src/scrobbler/federation/protocol/schedule.py @@ -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 diff --git a/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py index 697ee17..7f1e273 100644 --- a/src/scrobbler/federation/publishing/weekly.py +++ b/src/scrobbler/federation/publishing/weekly.py @@ -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.""" diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index cb1b5d6..80a9218 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -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() diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py index d88dea6..007ab41 100644 --- a/tests/test_federation_api.py +++ b/tests/test_federation_api.py @@ -1,5 +1,12 @@ +from datetime import UTC, datetime, timedelta + import pytest +from scrobbler.extensions import db +from scrobbler.federation import publishing, sharing +from scrobbler.federation.models import FederationPost +from scrobbler.models import Scrobble + @pytest.fixture def fed_auth(fed_ctx, user): @@ -17,11 +24,38 @@ def test_settings_start_private(fed_client, fed_auth): False, False, ) + assert (body["timezone"], body["post_weekly_summary"], body["post_milestones"]) == ( + "UTC", + True, + True, + ) assert body["handle"] == "@alice@scrobble.test" assert body["actor_url"] == "https://scrobble.test/users/alice" assert body["profile_url"] == "http://localhost:8080/profile.html?u=alice" +def test_timezone_and_post_toggles_can_be_changed(fed_client, fed_auth): + response = fed_client.patch( + "/api/v1/federation/settings", + json={"timezone": "Europe/London", "post_weekly_summary": False}, + headers=fed_auth, + ) + assert response.status_code == 200 + body = response.get_json() + assert (body["timezone"], body["post_weekly_summary"], body["post_milestones"]) == ( + "Europe/London", + False, + True, + ) + + +def test_an_unknown_timezone_is_rejected(fed_client, fed_auth): + response = fed_client.patch( + "/api/v1/federation/settings", json={"timezone": "Mars/Phobos"}, headers=fed_auth + ) + assert response.status_code == 422 + + def test_enable_and_change_settings(fed_client, fed_auth, metric_delta): enabled = metric_delta("scrobbler_federation_sharing_changes_total", change="enabled") response = fed_client.patch( @@ -80,3 +114,115 @@ def test_public_profile(fed_client, sharing_user, make_user): def test_disabled_server_has_no_federation_api(client, auth): assert client.get("/api/v1/federation/settings", headers=auth).status_code == 404 + + +def test_public_post_serves_a_public_or_unlisted_note(fed_client, fed_ctx, sharing_user): + sharing.update(sharing_user.id, {"visibility": "unlisted"}) + post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="

t

") + note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] + + body = fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").get_json() + assert body == { + "text": "t", + "html": "

t

", + "created_at": body["created_at"], + "display_name": "Alice", + "handle": "@alice@scrobble.test", + "profile_url": "http://localhost:8080/profile.html?u=alice", + } + + +def test_public_post_404s_for_followers_only_deleted_or_unknown(fed_client, fed_ctx, sharing_user): + post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="

t

") + note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] + # followers-only (the default) + assert fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").status_code == 404 + + sharing.update(post.user_id, {"visibility": "public"}) + publishing.delete_post(post.user_id, "alice", post) + db.session.commit() + assert fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").status_code == 404 + + assert fed_client.get("/api/v1/federation/profiles/alice/posts/not-a-uuid").status_code == 404 + assert fed_client.get("/api/v1/federation/profiles/nobody/posts/not-a-uuid").status_code == 404 + + +# --- Posts and preview ------------------------------------------------------------------ + + +def test_preview_weekly_reflects_the_week_in_progress(fed_client, fed_auth, fed_ctx, user): + now = datetime.now(UTC) + monday = now.date() - timedelta(days=now.weekday()) + db.session.add( + Scrobble( + user_id=user.id, + artist="Radiohead", + track="Reckoner", + played_at=datetime(monday.year, monday.month, monday.day, 12, tzinfo=UTC), + ) + ) + db.session.commit() + + response = fed_client.get("/api/v1/federation/preview/weekly", headers=fed_auth) + assert response.status_code == 200 + body = response.get_json() + assert "1 play" in body["text"] + assert "

" in body["html"] + # Never stored or posted + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 0 + + +def test_preview_weekly_needs_auth(fed_client): + assert fed_client.get("/api/v1/federation/preview/weekly").status_code == 401 + + +def test_list_posts_newest_first_including_deleted(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + first = publishing.publish(user.id, "alice", "weekly", "a", text="first", html="

1

") + second = publishing.publish(user.id, "alice", "weekly", "b", text="second", html="

2

") + publishing.delete_post(user.id, "alice", second) + db.session.commit() + + body = fed_client.get("/api/v1/federation/posts", headers=fed_auth).get_json() + assert [p["id"] for p in body] == [second.id, first.id] + assert body[0]["text"] == "second" + assert body[0]["deleted_at"] is not None + assert body[1]["deleted_at"] is None + + +def test_list_posts_needs_auth(fed_client): + assert fed_client.get("/api/v1/federation/posts").status_code == 401 + + +def test_delete_post(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "a", text="t", html="

t

") + db.session.commit() + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 204 + assert db.session.get(FederationPost, post.id).deleted_at is not None + + +def test_deleting_an_already_deleted_post_conflicts(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "a", text="t", html="

t

") + db.session.commit() + fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 409 + + +def test_deleting_someone_elses_post_is_not_found(fed_client, fed_auth, fed_ctx, user, make_user): + other = make_user(username="bob") + sharing.update(other.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(other.id, "bob", "weekly", "a", text="t", html="

t

") + db.session.commit() + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 404 + + +def test_deleting_an_unknown_post_is_not_found(fed_client, fed_auth): + assert fed_client.delete("/api/v1/federation/posts/999999", headers=fed_auth).status_code == 404 diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index fc0b0e7..71b596c 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -170,7 +170,7 @@ def test_post_note_browser_is_redirected_to_the_ui_page(fed_client, fed_ctx, sha note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] response = fed_client.get(f"/users/alice/posts/{note_uuid}", headers={"Accept": "text/html"}) assert response.status_code == 302 - assert response.headers["Location"] == f"http://localhost:8080/post.html?id={note_uuid}" + assert response.headers["Location"] == f"http://localhost:8080/post.html?u=alice&id={note_uuid}" def test_nodeinfo(fed_client, sharing_user): diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 25c11e6..a71b154 100644 --- a/tests/test_openapi.py +++ b/tests/test_openapi.py @@ -77,6 +77,7 @@ def test_ui_routes_declare_bearer_auth(fed_spec): ("/api/v1/auth/login", "post"), ("/api/v1/auth/register", "post"), ("/api/v1/federation/profiles/{username}", "get"), + ("/api/v1/federation/profiles/{username}/posts/{post_uuid}", "get"), } for path, operations in spec["paths"].items(): if not path.startswith("/api/v1/"):