diff --git a/CHANGELOG.md b/CHANGELOG.md index c403c2a..f0c75ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.5.0] - 2026-11-01 + +### Added + +- **Likes and reposts** via Micropub `like-of` / `repost-of` (ADR-068); a comment is optional + - Likes are kept off the home page and feeds and listed on a new `/likes` page (linked in the header) + - Reposts appear in the stream and feeds with a "๐Ÿ” Reposted" line + - The liked/reposted post's title and author are fetched and shown; it is sent a webmention + - GoToSocial: likes/reposts of fediverse posts become native favourites/boosts; reposts of other pages (or with a comment) post "๐Ÿ” title url" + - Bluesky: likes/reposts of Bluesky posts become native likes/reposts; a repost with a comment is a quote post; reposts of other pages post with a link card + - Likes of ordinary web pages are not crossposted; deleting a like/repost undoes it everywhere +- Migration 013: `notes.like_of`, `notes.repost_of` + +### Fixed + +- Outgoing webmentions named posts `https://site//note/` (double slash) + +### Notes + +- The GoToSocial token needs the extra scopes `read:search` and `write:favourites` + ## [2.4.0] - 2026-10-31 ### Added diff --git a/docs/decisions/ADR-068-likes-and-reposts.md b/docs/decisions/ADR-068-likes-and-reposts.md new file mode 100644 index 0000000..e0d2c17 --- /dev/null +++ b/docs/decisions/ADR-068-likes-and-reposts.md @@ -0,0 +1,32 @@ +# ADR-068: Likes and reposts + +## Status + +Accepted (v2.5.0, 2026-11-01). Bookmarks were considered and declined. + +## Decision + +1. **Storage.** `notes.like_of` / `notes.repost_of` (migration 013). The note's + content is an optional comment and may be empty. +2. **Display.** Likes stay off the home page and feeds and are listed on + `/likes`. Reposts appear in the stream and feeds. Both show the target's + fetched title and author (the reply-context cache) and carry + `u-like-of` / `u-repost-of`. The target is sent a webmention. +3. **Crossposting, per target.** + + | | Target is a post on that network | Anything else | + |---|---|---| + | Like | native favourite / like | nothing | + | Repost, no comment | native boost / repost | "๐Ÿ” title url" post | + | Repost, with comment | Bluesky quote post; GoToSocial status | comment + "๐Ÿ” title url" post | + + GoToSocial finds fediverse posts with `/api/v2/search?resolve=true` + (needs `read:search`; favourites need `write:favourites`). Bluesky + recognises `bsky.app/profile//post/` URLs. Native actions + are stored as `favourite:` / `reblog:` or the like/repost record + URI, and deleting the note undoes them. + +## Consequences + +- Editing a like/repost doesn't change a native favourite/boost. +- A repost with a comment can't be a GoToSocial boost (no quote posts there). diff --git a/migrations/013_add_likes_reposts.sql b/migrations/013_add_likes_reposts.sql new file mode 100644 index 0000000..3f0871f --- /dev/null +++ b/migrations/013_add_likes_reposts.sql @@ -0,0 +1,8 @@ +-- Migration 013: Likes and reposts (v2.5.0, ADR-068) +-- A note with like_of is a like; with repost_of, a repost. Content is the +-- optional comment and may be empty. + +ALTER TABLE notes ADD COLUMN like_of TEXT; +ALTER TABLE notes ADD COLUMN repost_of TEXT; + +CREATE INDEX IF NOT EXISTS idx_notes_like_of ON notes(like_of); diff --git a/starpunk/__init__.py b/starpunk/__init__.py index b81f43a..5bee4bf 100644 --- a/starpunk/__init__.py +++ b/starpunk/__init__.py @@ -464,5 +464,5 @@ def create_app(config=None): # Package version (Semantic Versioning 2.0.0) # See docs/standards/versioning-strategy.md for details -__version__ = "2.4.0" +__version__ = "2.5.0" __version_info__ = (2, 1, 0) diff --git a/starpunk/feeds/atom.py b/starpunk/feeds/atom.py index 3935ef3..6891f70 100644 --- a/starpunk/feeds/atom.py +++ b/starpunk/feeds/atom.py @@ -198,7 +198,7 @@ def generate_atom_streaming( yield f' \n' # Content - include media as HTML (per Q24) - if note.html: + if note.feed_html: # Build HTML content with media at top html_content = "" @@ -212,7 +212,7 @@ def generate_atom_streaming( html_content += '' # Add text content below media - html_content += note.html + html_content += note.feed_html # HTML content - escaped yield ' ' diff --git a/starpunk/feeds/json_feed.py b/starpunk/feeds/json_feed.py index a58348d..8aea8e5 100644 --- a/starpunk/feeds/json_feed.py +++ b/starpunk/feeds/json_feed.py @@ -267,7 +267,7 @@ def _build_item_object(site_url: str, note: Note) -> Dict[str, Any]: # Add content (HTML or text) # Per Q24: Include media as HTML in content_html - if note.html: + if note.feed_html: content_html = "" # Add media at top if present (v1.2.0 Phase 3) @@ -280,7 +280,7 @@ def _build_item_object(site_url: str, note: Note) -> Dict[str, Any]: content_html += '' # Add text content below media - content_html += note.html + content_html += note.feed_html item["content_html"] = content_html else: item["content_text"] = note.content diff --git a/starpunk/feeds/rss.py b/starpunk/feeds/rss.py index 80d72e9..411b772 100644 --- a/starpunk/feeds/rss.py +++ b/starpunk/feeds/rss.py @@ -137,7 +137,7 @@ def generate_rss( html_content += '' # Add text content below media - html_content += clean_html_for_rss(note.html) + html_content += clean_html_for_rss(note.feed_html) # feedgen automatically wraps content in CDATA for RSS fe.description(html_content) @@ -278,7 +278,7 @@ def generate_rss_streaming( html_content += '' # Add text content below media - html_content += clean_html_for_rss(note.html) + html_content += clean_html_for_rss(note.feed_html) # Build item XML item_xml = f""" diff --git a/starpunk/micropub.py b/starpunk/micropub.py index bc62562..5f3339e 100644 --- a/starpunk/micropub.py +++ b/starpunk/micropub.py @@ -296,16 +296,21 @@ def extract_post_status(properties: dict) -> bool: raise MicropubValidationError(f"Unsupported post-status: {status}") -def extract_in_reply_to(properties: dict) -> Optional[str]: - value = _first(properties.get("in-reply-to")) +def extract_url_property(properties: dict, name: str) -> Optional[str]: + """A URL property (in-reply-to, like-of, repost-of): string or h-cite""" + value = _first(properties.get(name)) if isinstance(value, dict): # h-cite value = _first((value.get("properties") or {}).get("url")) or value.get("value") value = (value or "").strip() if isinstance(value, str) else "" if value and not value.startswith(("http://", "https://")): - raise MicropubValidationError("in-reply-to must be an http(s) URL") + raise MicropubValidationError(f"{name} must be an http(s) URL") return value or None +def extract_in_reply_to(properties: dict) -> Optional[str]: + return extract_url_property(properties, "in-reply-to") + + def extract_photos(properties: dict) -> list[dict[str, str]]: """ Extract photo URLs and alt text from Micropub properties @@ -516,7 +521,16 @@ def handle_create(data: dict, token_info: dict, files=None): try: properties = normalize_properties(data) - content = extract_content(properties) + like_of = extract_url_property(properties, "like-of") + repost_of = extract_url_property(properties, "repost-of") + if like_of and repost_of: + raise MicropubValidationError("A post can't be both a like and a repost") + # Likes and reposts may come without a comment (v2.5.0) + has_content = any( + (c.strip() if isinstance(c, str) else (c.get("text") or c.get("html") or "").strip()) + for c in properties.get("content", []) if c + ) + content = extract_content(properties) if has_content or not (like_of or repost_of) else "" title = extract_title(properties) tags = extract_tags(properties) published_date = extract_published_date(properties) @@ -537,6 +551,8 @@ def handle_create(data: dict, token_info: dict, files=None): custom_slug=custom_slug, tags=tags if tags else None, in_reply_to=in_reply_to, + like_of=like_of, + repost_of=repost_of, ) if photos: @@ -705,6 +721,10 @@ def note_to_mf2(note, wanted: Optional[list] = None) -> dict: props["category"] = [tag["display_name"] for tag in note.tags] if getattr(note, "in_reply_to", None): props["in-reply-to"] = [note.in_reply_to] + if getattr(note, "like_of", None): + props["like-of"] = [note.like_of] + if getattr(note, "repost_of", None): + props["repost-of"] = [note.repost_of] photos = _note_photos(note) if photos: props["photo"] = [{"value": p["url"], "alt": p["alt"]} for p in photos] @@ -768,6 +788,8 @@ def handle_query(args, token_info: dict): {"type": "article", "name": "Article", "properties": ["name", "content"]}, {"type": "photo", "name": "Photo", "properties": ["photo"]}, {"type": "reply", "name": "Reply", "properties": ["in-reply-to", "content"]}, + {"type": "like", "name": "Like", "properties": ["like-of"]}, + {"type": "repost", "name": "Repost", "properties": ["repost-of", "content"]}, ], }), 200 diff --git a/starpunk/models.py b/starpunk/models.py index 20a9ac7..1b6a74b 100644 --- a/starpunk/models.py +++ b/starpunk/models.py @@ -134,6 +134,8 @@ class Note: deleted_at: Optional[datetime] = None content_hash: Optional[str] = None in_reply_to: Optional[str] = None # v1.6.0: URL being replied to + like_of: Optional[str] = None # v2.5.0: URL liked (this note is a like) + repost_of: Optional[str] = None # v2.5.0: URL reposted (this note is a repost) _cached_content: Optional[str] = field( default=None, repr=False, compare=False, init=False ) @@ -192,6 +194,8 @@ class Note: _data_dir=data_dir, content_hash=data.get("content_hash"), in_reply_to=data.get("in_reply_to"), + like_of=data.get("like_of"), + repost_of=data.get("repost_of"), ) @property @@ -367,12 +371,43 @@ class Note: excerpt = excerpt[:last_space] excerpt += "..." + if not excerpt and self.reacts_to: + # A like or repost with no comment + verb = "Liked" if self.kind == "like" else "Reposted" + return f"{verb} {self.reacts_to}" + return excerpt except (FileNotFoundError, OSError): # If file doesn't exist, return slug return self.slug + @property + def kind(self) -> str: + """'like', 'repost' or 'note' (v2.5.0)""" + if self.like_of: + return "like" + if self.repost_of: + return "repost" + return "note" + + @property + def reacts_to(self) -> Optional[str]: + """The URL a like or repost points at""" + return self.like_of or self.repost_of + + @property + def feed_html(self) -> str: + """HTML for feeds: a repost/like line, then the note's own HTML""" + from html import escape + + if not self.reacts_to: + return self.html + verb = "Liked" if self.kind == "like" else "Reposted" + url = escape(self.reacts_to, quote=True) + line = f'

{"โ˜…" if self.kind == "like" else "๐Ÿ”"} {verb} {url}

' + return line + (self.html or "") + @property def permalink(self) -> str: """ diff --git a/starpunk/notes.py b/starpunk/notes.py index 14e9bab..282ff8d 100644 --- a/starpunk/notes.py +++ b/starpunk/notes.py @@ -139,7 +139,9 @@ def create_note( created_at: Optional[datetime] = None, custom_slug: Optional[str] = None, tags: Optional[list[str]] = None, - in_reply_to: Optional[str] = None + in_reply_to: Optional[str] = None, + like_of: Optional[str] = None, + repost_of: Optional[str] = None, ) -> Note: """ Create a new note @@ -203,7 +205,11 @@ def create_note( - created_at and updated_at set to same value initially """ # 1. VALIDATION (before any changes) - if not content or not content.strip(): + # Likes and reposts may have no comment (v2.5.0) + if like_of and repost_of: + raise InvalidNoteDataError("like_of", like_of, "A note can't be both a like and a repost") + content = content or "" + if not content.strip() and not (like_of or repost_of): raise InvalidNoteDataError( "content", content, "Content cannot be empty or whitespace-only" ) @@ -264,10 +270,10 @@ def create_note( try: db.execute( """ - INSERT INTO notes (slug, file_path, published, created_at, updated_at, content_hash, in_reply_to) - VALUES (?, ?, ?, ?, ?, ?, ?) + INSERT INTO notes (slug, file_path, published, created_at, updated_at, content_hash, in_reply_to, like_of, repost_of) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """, - (slug, file_path_rel, published, created_at, updated_at, content_hash, in_reply_to), + (slug, file_path_rel, published, created_at, updated_at, content_hash, in_reply_to, like_of, repost_of), ) db.commit() except Exception as e: @@ -322,33 +328,36 @@ def create_note( from starpunk.webmention_sender import queue_webmentions_for_note db_path = Path(current_app.config["DATABASE_PATH"]) site_url = current_app.config["SITE_URL"] - note_url = f"{site_url}/note/{slug}" + from starpunk.utils import absolute_url_for + note_url = absolute_url_for("public.note", slug=slug) # Get rendered HTML from note html_content = note.html # Queue webmentions (best-effort, failures logged but don't fail note creation) + # The reply/like/repost target is notified first (v2.5.0) queue_webmentions_for_note( db_path=db_path, note_id=note_id, note_url=note_url, content_html=html_content, - in_reply_to=in_reply_to + in_reply_to=in_reply_to or like_of or repost_of ) except Exception as e: # Webmention queueing failure should not prevent note creation current_app.logger.warning(f"Failed to queue webmentions for note {slug}: {e}") # 12. FETCH REPLY CONTEXT (v1.6.0 Phase 3) - # Fetch context if this is a reply - if in_reply_to: + # Fetch context for the post being replied to, liked or reposted + context_url = in_reply_to or like_of or repost_of + if context_url: try: from starpunk.reply_context import fetch_reply_context db_path = Path(current_app.config["DATABASE_PATH"]) site_url = current_app.config["SITE_URL"] # Fetch context (best-effort, failures logged but don't fail note creation) - fetch_reply_context(db_path, in_reply_to, site_url) + fetch_reply_context(db_path, context_url, site_url) except Exception as e: # Reply context fetch failure should not prevent note creation current_app.logger.warning(f"Failed to fetch reply context for {in_reply_to}: {e}") @@ -472,6 +481,7 @@ def list_notes( offset: int = 0, order_by: str = "created_at", order_dir: str = "DESC", + likes: Optional[bool] = None, ) -> list[Note]: """ List notes with filtering and pagination @@ -564,6 +574,11 @@ def list_notes( params = [] if published_only: query += " AND published = 1" + # likes: None = all notes, False = leave likes out, True = only likes (v2.5.0) + if likes is True: + query += " AND like_of IS NOT NULL" + elif likes is False: + query += " AND like_of IS NULL" # Add ordering (safe because order_by validated above) query += f" ORDER BY {order_by} {order_dir}" @@ -663,12 +678,9 @@ def update_note( if content is None and published is None and tags is None and in_reply_to is None: raise ValueError("Must provide at least one of content, published, tags, or in_reply_to to update") - # Validate content if provided - if content is not None: - if not content or not content.strip(): - raise InvalidNoteDataError( - "content", content, "Content cannot be empty or whitespace-only" - ) + # Validate content if provided (checked against the note below for + # likes/reposts, whose comment may be empty) + empty_content = content is not None and not content.strip() # 2. GET EXISTING NOTE # Phase 6: Load content to get old HTML for webmention URL diffing @@ -678,6 +690,11 @@ def update_note( identifier = slug if slug is not None else id raise NoteNotFoundError(identifier) + if empty_content and not (existing_note.like_of or existing_note.repost_of): + raise InvalidNoteDataError( + "content", content, "Content cannot be empty or whitespace-only" + ) + # 3. SETUP updated_at = datetime.utcnow() data_dir = Path(current_app.config["DATA_PATH"]) @@ -815,13 +832,14 @@ def update_note( from starpunk.webmention_sender import queue_webmentions_for_note db_path = Path(current_app.config["DATABASE_PATH"]) site_url = current_app.config["SITE_URL"] - note_url = f"{site_url}/note/{updated_note.slug}" + from starpunk.utils import absolute_url_for + note_url = absolute_url_for("public.note", slug=updated_note.slug) # Get rendered HTML from updated note (if published) html_content = updated_note.html if updated_note.published else None # Determine in_reply_to (use new value if provided, otherwise existing) - reply_to = in_reply_to if in_reply_to is not None else updated_note.in_reply_to + reply_to = (in_reply_to if in_reply_to is not None else updated_note.in_reply_to) or updated_note.like_of or updated_note.repost_of # Queue webmentions (best-effort) # Pass old_html for URL diffing (Phase 6) @@ -838,8 +856,8 @@ def update_note( current_app.logger.warning(f"Failed to queue webmentions for note {updated_note.slug}: {e}") # 9. FETCH REPLY CONTEXT (v1.6.0 Phase 3) - # Fetch context if in_reply_to changed and is not None - if in_reply_to is not None: + # Fetch context if in_reply_to changed and is set ("" clears it) + if in_reply_to: try: from starpunk.reply_context import fetch_reply_context db_path = Path(current_app.config["DATABASE_PATH"]) diff --git a/starpunk/routes/admin.py b/starpunk/routes/admin.py index f1f0422..6d3e59f 100644 --- a/starpunk/routes/admin.py +++ b/starpunk/routes/admin.py @@ -277,7 +277,7 @@ def update_note_submit(note_id: int): published = "published" in request.form tags_input = request.form.get("tags", "") - if not content: + if not content and not existing_note.reacts_to: # likes/reposts may have no comment flash("Content cannot be empty", "error") return redirect(url_for("admin.edit_note_form", note_id=note_id)) diff --git a/starpunk/routes/public.py b/starpunk/routes/public.py index 683039b..d1c3474 100644 --- a/starpunk/routes/public.py +++ b/starpunk/routes/public.py @@ -64,7 +64,7 @@ def _get_cached_notes(): # Cache expired or empty, fetch fresh notes max_items = current_app.config.get("FEED_MAX_ITEMS", 50) - notes = list_notes(published_only=True, limit=max_items) + notes = list_notes(published_only=True, limit=max_items, likes=False) # Batch load media and tags for all notes (v1.5.0 Phase 3) # Reduces query count from O(n) to O(1) for both media and tags @@ -249,8 +249,8 @@ def index(): from starpunk.media import get_note_media from starpunk.tags import get_note_tags - # Get recent published notes (limit 20) - notes = list_notes(published_only=True, limit=20) + # Get recent published notes (limit 20); likes have their own page (v2.5.0) + notes = list_notes(published_only=True, limit=20, likes=False) # Attach media and tags to each note for display for note in notes: @@ -262,9 +262,38 @@ def index(): tags = get_note_tags(note.id) object.__setattr__(note, '_cached_tags', tags) + attach_contexts(notes) return render_template("index.html", notes=notes) +def attach_contexts(notes) -> None: + """Give likes and reposts the fetched context of the post they point at""" + from starpunk.webmention_queries import get_reply_context + + for note in notes: + context = None + if note.reacts_to: + try: + context = get_reply_context(note.reacts_to) + except Exception: + context = None + object.__setattr__(note, 'context', context) + + +@bp.route("/likes") +def likes(): + """Likes, kept off the home page and feeds (v2.5.0)""" + from starpunk.media import get_note_media + from starpunk.tags import get_note_tags + + notes = list_notes(published_only=True, limit=50, likes=True) + for note in notes: + object.__setattr__(note, 'media', get_note_media(note.id)) + object.__setattr__(note, '_cached_tags', get_note_tags(note.id)) + attach_contexts(notes) + return render_template("likes.html", notes=notes) + + @bp.route("/note/") def note(slug: str): """ @@ -334,6 +363,7 @@ def note(slug: str): from starpunk.syndication import get_note_syndications syndications = [s for s in get_note_syndications(note_obj.id) if s["state"] == "synced"] + attach_contexts([note_obj]) return render_template( "note.html", @@ -384,6 +414,7 @@ def tag(tag: str): for note in notes: media = get_note_media(note.id) object.__setattr__(note, 'media', media) + attach_contexts(notes) return render_template( "tag.html", diff --git a/starpunk/syndication.py b/starpunk/syndication.py index b30aeab..337db59 100644 --- a/starpunk/syndication.py +++ b/starpunk/syndication.py @@ -113,21 +113,56 @@ class MastodonClient: # Interface used by the reconcile loop can_edit = True + NATIVE = ("favourite", "reblog") # remote_id prefixes for likes/boosts (v2.5.0) + + def find_status(self, url: str) -> Optional[str]: + """Local id of a fediverse post, fetching it if needed; None if the URL isn't one""" + try: + response = self._call("GET", "/api/v2/search", params={ + "q": url, "resolve": "true", "type": "statuses", "limit": 1, + }) + except RemoteGone: + return None + statuses = response.json().get("statuses") or [] + return statuses[0]["id"] if statuses else None def _prepare(self, post: "Post") -> tuple: + if post.kind == "repost": + return compose_repost_text(post, post.note.content, post.max_chars), [] text = compose_text(post.note, post.permalink, post.tags, post.max_chars) media_ids = [self.upload_media(f["path"], f["mime_type"], f["description"]) for f in post.media] return text, media_ids def create(self, post: "Post", key: str, retrying: bool = False) -> dict: + if post.kind in ("like", "repost") and post.target_url: + # Native favourite/boost when the target is a fediverse post; a + # repost with a comment is posted as a status so the comment stays + commented = bool(post.note.content.strip()) + if post.kind == "like" or not commented: + status_id = self.find_status(post.target_url) + if status_id: + action = "favourite" if post.kind == "like" else "reblog" + self._call("POST", f"/api/v1/statuses/{status_id}/{action}") + return {"id": f"{action}:{status_id}", "url": None} + if post.kind == "like": + return {"id": None, "url": None} # nothing to like here text, media_ids = self._prepare(post) return self.create_status(text, media_ids, idempotency_key=key) def update(self, remote_id: str, post: "Post") -> dict: + if remote_id.split(":", 1)[0] in self.NATIVE: + return {"id": remote_id, "url": None} # a favourite/boost has nothing to edit text, media_ids = self._prepare(post) return self.update_status(remote_id, text, media_ids) def delete(self, remote_id: str) -> None: + action, _, status_id = remote_id.partition(":") + if action in self.NATIVE and status_id: + try: + self._call("POST", f"/api/v1/statuses/{status_id}/un{action}") + except RemoteGone: + pass + return self.delete_status(remote_id) @@ -229,18 +264,21 @@ class BlueskyClient: image["aspectRatio"] = {"width": width, "height": height} return image - def _record(self, post: "Post") -> dict: - text = compose_text(post.note, post.permalink, post.tags, post.max_chars, - body=plain_text(post.note.content)) - record = { - "$type": self.POST, - "text": text, - "createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z", - } + @staticmethod + def _now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" + + def _record(self, post: "Post", text: Optional[str] = None, embed: Optional[dict] = None) -> dict: + if text is None: + text = compose_text(post.note, post.permalink, post.tags, post.max_chars, + body=plain_text(post.note.content)) + record = {"$type": self.POST, "text": text, "createdAt": self._now()} facets = bluesky_facets(text) if facets: record["facets"] = facets - if post.media: + if embed is not None: + record["embed"] = embed + elif post.media: record["embed"] = {"$type": "app.bsky.embed.images", "images": [self._image(m) for m in post.media]} else: @@ -251,6 +289,54 @@ class BlueskyClient: }} return record + _POST_URL = re.compile(r"^https://bsky\.app/profile/([^/]+)/post/([^/?#]+)") + + def resolve_post(self, url: str) -> Optional[dict]: + """{'uri', 'cid'} of a Bluesky post URL; None if the URL isn't one""" + m = self._POST_URL.match(url or "") + if not m: + return None + actor, rkey = m.groups() + if not actor.startswith("did:"): + actor = self._call("GET", "com.atproto.identity.resolveHandle", + params={"handle": actor}).json()["did"] + uri = f"at://{actor}/{self.POST}/{rkey}" + posts = self._call("GET", "app.bsky.feed.getPosts", params={"uris": uri}).json().get("posts") or [] + return {"uri": uri, "cid": posts[0]["cid"]} if posts else None + + def _create(self, collection: str, record: dict) -> str: + response = self._call("POST", "com.atproto.repo.createRecord", + json={"repo": self.did or self.identifier, "collection": collection, + "record": record}) + return response.json()["uri"] + + def _react(self, post: "Post") -> dict: + """Like, repost or quote a Bluesky post; fall back to a link post for reposts""" + comment = plain_text(post.note.content) if post.note.content.strip() else "" + subject = self.resolve_post(post.target_url) + if subject and post.kind == "like": + uri = self._create("app.bsky.feed.like", { + "$type": "app.bsky.feed.like", "subject": subject, "createdAt": self._now()}) + return {"id": uri, "url": None} + if subject and not comment: + uri = self._create("app.bsky.feed.repost", { + "$type": "app.bsky.feed.repost", "subject": subject, "createdAt": self._now()}) + return {"id": uri, "url": None} + if subject: # repost with a comment -> quote post + text = comment if len(comment) <= post.max_chars else \ + comment[:post.max_chars - 1].rsplit(" ", 1)[0].rstrip() + "โ€ฆ" + uri = self._create(self.POST, self._record( + post, text=text, embed={"$type": "app.bsky.embed.record", "record": subject})) + return {"id": uri, "url": self._web_url(uri)} + if post.kind == "like": + return {"id": None, "url": None} # not a Bluesky post: nothing to like + text = compose_repost_text(post, comment, post.max_chars) + embed = {"$type": "app.bsky.embed.external", "external": { + "uri": post.target_url, "title": (post.target_title or post.target_url)[:300], + "description": ""}} + uri = self._create(self.POST, self._record(post, text=text, embed=embed)) + return {"id": uri, "url": self._web_url(uri)} + def _web_url(self, uri: str) -> str: rkey = uri.rsplit("/", 1)[1] return f"https://bsky.app/profile/{self.handle or self.did}/post/{rkey}" @@ -265,6 +351,11 @@ class BlueskyClient: return None def create(self, post: "Post", key: str, retrying: bool = False) -> dict: + if post.kind in ("like", "repost") and post.target_url: + if not self.did: + with self._lock: + self._login() + return self._react(post) if retrying: if not self.did: with self._lock: @@ -327,6 +418,24 @@ class Post: tags: List[str] max_chars: int media: List[dict] = field(default_factory=list) + kind: str = "note" # note, like or repost (v2.5.0) + target_url: Optional[str] = None # what a like/repost points at + target_title: Optional[str] = None # its fetched title, if any + + +def compose_repost_text(post: "Post", comment: str, max_chars: int) -> str: + """'comment' then '๐Ÿ” title' and the URL; the comment is shortened to fit""" + title = post.target_title or "Reposted" + tail = f"๐Ÿ” {title}\n{post.target_url}" + if len(tail) > max_chars: + tail = f"๐Ÿ” {post.target_url}" + comment = (comment or "").strip() + if not comment: + return tail + room = max_chars - len(tail) - 2 + if len(comment) > room: + comment = comment[:max(room - 1, 0)].rsplit(" ", 1)[0].rstrip() + "โ€ฆ" + return f"{comment}\n\n{tail}" if room > 1 else tail _client_cache: Dict[str, object] = {} @@ -615,6 +724,21 @@ def _fail(db, row, error: SyndicationError) -> None: ) +def _target_title(url: Optional[str]) -> Optional[str]: + """Fetched title of a liked/reposted post, if we have one""" + if not url: + return None + try: + from starpunk.webmention_queries import get_reply_context + context = get_reply_context(url) or {} + except Exception: + return None + title = context.get("title") or "" + if not title and context.get("author_name"): + title = f"Post by {context['author_name']}" + return " ".join(title.split())[:200] or None + + def _reconcile(row, target: Target) -> tuple: """Bring the remote post in line with the note. Returns (remote_id, remote_url).""" from starpunk.notes import get_note @@ -637,7 +761,10 @@ def _reconcile(row, target: Target) -> tuple: permalink=f"{site}/note/{note.slug}", tags=[t["display_name"] for t in get_note_tags(note.id)], max_chars=target.max_chars, - media=_media_files(note.id, target.max_media), + media=_media_files(note.id, target.max_media) if note.kind == "note" else [], + kind=note.kind, + target_url=note.reacts_to, + target_title=_target_title(note.reacts_to), ) if row["remote_id"]: diff --git a/static/css/style.css b/static/css/style.css index 6d89d21..a0aa74b 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -92,6 +92,17 @@ main { flex: 1; margin-bottom: var(--spacing-xl); } .e-content ul, .e-content ol { margin: 0 0 var(--spacing-md) 1.25rem; } .e-content img { max-width: 100%; height: auto; } .e-content h1, .e-content h2, .e-content h3 { font-family: var(--font-body); } +.reaction { margin-bottom: var(--spacing-sm); font-size: 0.9375rem; color: var(--color-text-light); overflow-wrap: anywhere; } +.reaction-verb { font-weight: 600; margin-right: 0.25rem; } +.reaction-like .reaction-verb { color: #c2410c; } +.reaction-repost .reaction-verb { color: #15803d; } +.reaction a { color: var(--color-text); font-weight: 500; } +.reaction a:hover { color: var(--color-link); } +.reaction-by { margin-left: 0.25rem; } +@media (prefers-color-scheme: dark) { + .reaction-like .reaction-verb { color: #fb923c; } + .reaction-repost .reaction-verb { color: #4ade80; } +} .read-more { margin: var(--spacing-sm) 0 0; font-size: 0.9375rem; } .note-meta { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0 0.4rem; margin-top: var(--spacing-sm); color: var(--color-text-light); font-size: 0.8125rem; } diff --git a/templates/admin/edit.html b/templates/admin/edit.html index e22bd03..6bd5901 100644 --- a/templates/admin/edit.html +++ b/templates/admin/edit.html @@ -12,12 +12,15 @@
- + {% if note.reacts_to %} +

{{ 'โ˜… Like of' if note.kind == 'like' else '๐Ÿ” Repost of' }} {{ note.reacts_to }}

+ {% endif %} + Use Markdown syntax for formatting diff --git a/templates/base.html b/templates/base.html index 8688a39..ee29581 100644 --- a/templates/base.html +++ b/templates/base.html @@ -38,6 +38,7 @@ {{ config.SITE_NAME }}
{% endif %} + {{ reaction(note) }} + {# u-photo placement: Per draft spec, u-photo must be direct child of h-entry, #} {# NOT inside e-content. Media is rendered ABOVE e-content to meet this requirement. #} {{ display_media(note.media) }} diff --git a/templates/partials/note_preview.html b/templates/partials/note_preview.html index 3b6b1f7..b8e11d5 100644 --- a/templates/partials/note_preview.html +++ b/templates/partials/note_preview.html @@ -1,5 +1,6 @@ {# One note in a list (home, tag pages). v2.3.0 #} {% from "partials/media.html" import display_media %} +{% from "partials/reaction.html" import reaction %} {% macro note_preview(note, author) %}
{# Notes starting with a # heading have a title (Q22) #} @@ -8,6 +9,8 @@

{{ note.title }}

{% endif %} + {{ reaction(note) }} + {{ display_media(note.media) }} {% if has_explicit_title %} @@ -16,7 +19,7 @@

{{ note.excerpt }}

Read more โ†’

- {% else %} + {% elif note.html %}
{{ note.html|safe }}
diff --git a/templates/partials/reaction.html b/templates/partials/reaction.html new file mode 100644 index 0000000..13798c4 --- /dev/null +++ b/templates/partials/reaction.html @@ -0,0 +1,12 @@ +{# "Liked" / "Reposted" line for likes and reposts (v2.5.0) #} +{% macro reaction(note) %} +{% if note.reacts_to %} +{% set ctx = note.context if note.context is defined else None %} +{% if ctx and ctx.title %}{% set label = ctx.title %}{% elif ctx and ctx.content_snippet %}{% set label = ctx.content_snippet|striptags|truncate(90) %}{% elif ctx and (ctx.author_name or ctx.site_name) %}{% set label = 'a post' %}{% else %}{% set label = note.reacts_to %}{% endif %} +

+ {% if note.kind == 'like' %}โ˜… Liked{% else %}๐Ÿ” Reposted{% endif %} + {{ label }} + {% if ctx and (ctx.author_name or ctx.site_name) %}by {{ ctx.author_name or ctx.site_name }}{% endif %} +

+{% endif %} +{% endmacro %} diff --git a/tests/test_likes_reposts.py b/tests/test_likes_reposts.py new file mode 100644 index 0000000..7e79d05 --- /dev/null +++ b/tests/test_likes_reposts.py @@ -0,0 +1,223 @@ +""" +Likes and reposts (v2.5.0, ADR-068) + +Fake GoToSocial and Bluesky servers check that likes/reposts of their own +posts become native favourites/boosts/likes/reposts, and everything else +falls back (reposts) or is skipped (likes). +""" + +import json + +import httpx +import pytest + +from starpunk import create_app, syndication +from starpunk.indieauth import create_access_token +from starpunk.notes import delete_note, get_note +from starpunk.syndication import BlueskyClient, MastodonClient, get_note_syndications, process_due + +SITE = "https://blog.example.com" +GTS = "https://social.example.com" +FEDI_POST = "https://mastodon.example/@alice/111" +BSKY_POST = "https://bsky.app/profile/alice.example/post/3abc" +WEB_PAGE = "https://someblog.example/2026/a-post" + + +class FakeGTS: + def __init__(self): + self.calls = [] + self.statuses = {} + + def __call__(self, request): + path = request.url.path + self.calls.append((request.method, path)) + if path == "/api/v2/search": + q = request.url.params["q"] + return httpx.Response(200, json={"statuses": [{"id": "s1"}] if q == FEDI_POST else []}) + if path in ("/api/v1/statuses/s1/favourite", "/api/v1/statuses/s1/unfavourite", + "/api/v1/statuses/s1/reblog", "/api/v1/statuses/s1/unreblog"): + return httpx.Response(200, json={"id": "s1"}) + if path == "/api/v1/statuses" and request.method == "POST": + sid = f"p{len(self.statuses) + 1}" + self.statuses[sid] = json.loads(request.content) + return httpx.Response(200, json={"id": sid, "url": f"{GTS}/@phil/statuses/{sid}"}) + if path.startswith("/api/v1/statuses/") and request.method == "DELETE": + self.statuses.pop(path.rsplit("/", 1)[1], None) + return httpx.Response(200, json={}) + return httpx.Response(500) + + +class FakePDS: + def __init__(self): + self.records = {} + self.calls = [] + + def __call__(self, request): + nsid = request.url.path.removeprefix("/xrpc/") + self.calls.append(nsid) + if nsid == "com.atproto.server.createSession": + return httpx.Response(200, json={"did": "did:plc:me", "handle": "me.example", + "accessJwt": "a", "refreshJwt": "r"}) + if nsid == "com.atproto.identity.resolveHandle": + return httpx.Response(200, json={"did": "did:plc:alice"}) + if nsid == "app.bsky.feed.getPosts": + return httpx.Response(200, json={"posts": [{"uri": request.url.params["uris"], "cid": "cid1"}]}) + if nsid == "com.atproto.repo.createRecord": + body = json.loads(request.content) + uri = f"at://did:plc:me/{body['collection']}/r{len(self.records) + 1}" + self.records[uri] = body["record"] + return httpx.Response(200, json={"uri": uri, "cid": "c"}) + if nsid == "com.atproto.repo.deleteRecord": + body = json.loads(request.content) + self.records.pop(f"at://{body['repo']}/{body['collection']}/{body['rkey']}", None) + return httpx.Response(200, json={}) + return httpx.Response(500, json={"error": nsid}) + + +@pytest.fixture +def gts(): + return FakeGTS() + + +@pytest.fixture +def pds(): + return FakePDS() + + +@pytest.fixture +def app(tmp_path, gts, pds): + data = tmp_path / "data" + app = create_app({ + "TESTING": True, "SITE_URL": SITE, "ADMIN_ME": "https://example.com", "SESSION_SECRET": "x", + "DATA_PATH": data, "NOTES_PATH": data / "notes", "DATABASE_PATH": data / "starpunk.db", + "GOTOSOCIAL_URL": GTS, "GOTOSOCIAL_ACCESS_TOKEN": "t", + "BLUESKY_HANDLE": "me.example", "BLUESKY_APP_PASSWORD": "p", "BLUESKY_SERVICE": "https://pds.example", + "FEED_CACHE_ENABLED": False, + }) + # The feed's note list is cached at module level across apps + from starpunk.routes import public + public._feed_cache["notes"] = None + public._feed_cache["timestamp"] = None + syndication._client_cache[GTS] = MastodonClient(GTS, "t", http=httpx.Client(transport=httpx.MockTransport(gts))) + syndication._client_cache["bluesky:https://pds.example:me.example"] = BlueskyClient( + "https://pds.example", "me.example", "p", http=httpx.Client(transport=httpx.MockTransport(pds))) + yield app + syndication._client_cache.clear() + + +@pytest.fixture +def post(app, monkeypatch): + # Don't fetch contexts from the network + monkeypatch.setattr("starpunk.reply_context.fetch_reply_context", lambda *a, **k: None) + with app.test_request_context(): + token = create_access_token("https://quill.example/", "create update delete")["access_token"] + client = app.test_client() + + def _post(**props): + response = client.post("/micropub", json={"type": ["h-entry"], "properties": props}, + headers={"Authorization": f"Bearer {token}"}) + assert response.status_code == 201, response.get_json() + location = response.headers["Location"] + with app.app_context(): + note = get_note(slug=location.rsplit("/", 1)[1]) + process_due(limit=10) + rows = {r["target"]: r for r in get_note_syndications(note.id)} + return note, rows + return _post + + +def page(app, path): + return app.test_client().get(path).data.decode() + + +class TestSite: + def test_like_without_comment(self, app, post): + note, _ = post(**{"like-of": [WEB_PAGE]}) + assert note.kind == "like" and note.content == "" + assert note.slug not in page(app, "/") + likes = page(app, "/likes") + assert f'class="u-like-of" href="{WEB_PAGE}"' in likes and "โ˜… Liked" in likes + assert note.slug not in page(app, "/feed.json") + + def test_repost_in_stream_and_feed(self, app, post): + note, _ = post(**{"repost-of": [WEB_PAGE], "content": ["Worth a read"]}) + home = page(app, "/") + assert f'class="u-repost-of" href="{WEB_PAGE}"' in home and "Worth a read" in home + feed = json.loads(page(app, "/feed.json")) + item = next(i for i in feed["items"] if note.slug in i["url"]) + assert "Reposted" in item["content_html"] and WEB_PAGE in item["content_html"] + + def test_webmention_goes_to_target_with_clean_url(self, app, post, monkeypatch): + sent = {} + monkeypatch.setattr("starpunk.webmention_sender.queue_webmentions_for_note", + lambda **kw: sent.update(kw) or 0) + app.config["WEBMENTION_ENABLED"] = True + note, _ = post(**{"like-of": [WEB_PAGE]}) + assert sent["in_reply_to"] == WEB_PAGE + assert sent["note_url"] == f"{SITE}/note/{note.slug}" # no double slash + + def test_both_kinds_rejected(self, app, post): + with pytest.raises(AssertionError): + post(**{"like-of": [WEB_PAGE], "repost-of": [WEB_PAGE]}) + + +class TestGoToSocial: + def test_like_of_fediverse_post_favourites(self, app, post, gts): + note, rows = post(**{"like-of": [FEDI_POST]}) + assert rows["gotosocial"]["remote_id"] == "favourite:s1" + assert rows["gotosocial"]["remote_url"] is None + with app.test_request_context(): + delete_note(id=note.id) + process_due(limit=10) + assert ("POST", "/api/v1/statuses/s1/unfavourite") in gts.calls + + def test_like_of_web_page_is_not_crossposted(self, app, post, gts): + _, rows = post(**{"like-of": [WEB_PAGE]}) + assert rows["gotosocial"]["state"] == "synced" and rows["gotosocial"]["remote_id"] is None + assert gts.statuses == {} + + def test_repost_boosts(self, app, post, gts): + _, rows = post(**{"repost-of": [FEDI_POST]}) + assert rows["gotosocial"]["remote_id"] == "reblog:s1" + + def test_repost_with_comment_posts_status(self, app, post, gts): + _, rows = post(**{"repost-of": [FEDI_POST], "content": ["So true"]}) + (status,) = gts.statuses.values() + assert status["status"].startswith("So true") and FEDI_POST in status["status"] + assert ("POST", "/api/v1/statuses/s1/reblog") not in gts.calls + + def test_repost_of_web_page_posts_link(self, app, post, gts): + post(**{"repost-of": [WEB_PAGE]}) + (status,) = gts.statuses.values() + assert status["status"].startswith("๐Ÿ”") and WEB_PAGE in status["status"] + + +class TestBluesky: + def test_like_of_bluesky_post(self, app, post, pds): + note, rows = post(**{"like-of": [BSKY_POST]}) + uri = rows["bluesky"]["remote_id"] + assert "/app.bsky.feed.like/" in uri + assert pds.records[uri]["subject"] == {"uri": "at://did:plc:alice/app.bsky.feed.post/3abc", "cid": "cid1"} + with app.test_request_context(): + delete_note(id=note.id) + process_due(limit=10) + assert uri not in pds.records + + def test_like_of_web_page_skipped(self, app, post, pds): + _, rows = post(**{"like-of": [WEB_PAGE]}) + assert rows["bluesky"]["remote_id"] is None and pds.records == {} + + def test_repost_and_quote(self, app, post, pds): + _, rows = post(**{"repost-of": [BSKY_POST]}) + assert "/app.bsky.feed.repost/" in rows["bluesky"]["remote_id"] + _, rows = post(**{"repost-of": [BSKY_POST], "content": ["Great thread"]}) + record = pds.records[rows["bluesky"]["remote_id"]] + assert record["text"] == "Great thread" + assert record["embed"] == {"$type": "app.bsky.embed.record", + "record": {"uri": "at://did:plc:alice/app.bsky.feed.post/3abc", "cid": "cid1"}} + + def test_repost_of_web_page_posts_link_card(self, app, post, pds): + _, rows = post(**{"repost-of": [WEB_PAGE]}) + record = pds.records[rows["bluesky"]["remote_id"]] + assert record["embed"]["external"]["uri"] == WEB_PAGE + assert record["text"].startswith("๐Ÿ”")