feat: crossposted replies look like replies (v2.20.0)
- Native replies on the same network: GoToSocial in_reply_to_id (resolved by our instance) with the author's @mention; Bluesky reply root/parent - Replies to our own notes (permalink or any crosspost URL) thread under that note's crosspost on every network, Threads included - Otherwise "↩ Replying to <author>" and the link; on Bluesky the name is the link. compose_text keeps the line whole when shortening Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7a936562c
commit
67c0411fd8
5 files changed
+467
-20
No files matched your search
@@ -476,5 +476,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.19.0"
|
||||
__version_info__ = (2, 19, 0)
|
||||
__version__ = "2.20.0"
|
||||
__version_info__ = (2, 20, 0)
|
||||
+161
-18
@@ -25,6 +25,7 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from urllib.parse import urlparse
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
@@ -102,10 +103,14 @@ class MastodonClient:
|
||||
"content_type": "text/markdown",
|
||||
}
|
||||
|
||||
def create_status(self, text: str, media_ids: List[str], idempotency_key: str) -> dict:
|
||||
def create_status(self, text: str, media_ids: List[str], idempotency_key: str,
|
||||
in_reply_to_id: Optional[str] = None) -> dict:
|
||||
body = self._status_body(text, media_ids)
|
||||
if in_reply_to_id:
|
||||
body["in_reply_to_id"] = in_reply_to_id
|
||||
response = self._call(
|
||||
"POST", "/api/v1/statuses",
|
||||
json=self._status_body(text, media_ids),
|
||||
json=body,
|
||||
headers={"Idempotency-Key": idempotency_key},
|
||||
)
|
||||
data = response.json()
|
||||
@@ -143,14 +148,45 @@ class MastodonClient:
|
||||
status = self.resolve_status(url)
|
||||
return status["id"] if status else None
|
||||
|
||||
def _reply_parent(self, post: "Post") -> tuple:
|
||||
"""(status id, '@acct ' mention) a reply threads under; (None, '') if it can't (v2.20.0)
|
||||
|
||||
Our own crosspost of the replied-to note, else the replied-to post as
|
||||
this instance resolves it (any fediverse post). Replies to others
|
||||
start with their @mention, as Mastodon and GoToSocial clients do, so
|
||||
they are notified and their server gets the reply."""
|
||||
if not post.reply_to:
|
||||
return None, ""
|
||||
if post.reply_remote_id and post.reply_remote_id.split(":", 1)[0] not in self.NATIVE:
|
||||
return post.reply_remote_id, ""
|
||||
try:
|
||||
status = self.resolve_status(post.reply_to)
|
||||
except SyndicationError as e:
|
||||
current_app.logger.info(f"Could not resolve {post.reply_to}: {e}")
|
||||
return None, ""
|
||||
if not status:
|
||||
return None, ""
|
||||
account = status.get("account") or {}
|
||||
try:
|
||||
mine = account.get("id") == self._account_id()
|
||||
except SyndicationError:
|
||||
mine = False
|
||||
mention = "" if mine or not account.get("acct") else f"@{account['acct']} "
|
||||
return status["id"], mention
|
||||
|
||||
def _prepare(self, post: "Post") -> tuple:
|
||||
"""(text, media ids, id of the status it replies to)"""
|
||||
if post.kind == "repost":
|
||||
return compose_repost_text(post, post.note.content, post.max_chars), []
|
||||
return compose_repost_text(post, post.note.content, post.max_chars), [], None
|
||||
parent, mention = self._reply_parent(post)
|
||||
# Images in the text are sent as attachments instead (v2.6.6)
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars,
|
||||
body=strip_images(post.note.content))
|
||||
body = strip_images(post.note.content)
|
||||
if mention.strip() and mention.strip() not in body:
|
||||
body = mention + body.lstrip()
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars, body=body,
|
||||
lead="" if parent else reply_line(post))
|
||||
media_ids = [self.upload_media(f["path"], f["mime_type"], f["description"]) for f in post.media]
|
||||
return text, media_ids
|
||||
return text, media_ids, parent
|
||||
|
||||
def create(self, post: "Post", key: str, retrying: bool = False) -> dict:
|
||||
if post.kind in ("like", "repost") and post.target_url:
|
||||
@@ -165,13 +201,13 @@ class MastodonClient:
|
||||
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)
|
||||
text, media_ids, parent = self._prepare(post)
|
||||
return self.create_status(text, media_ids, idempotency_key=key, in_reply_to_id=parent)
|
||||
|
||||
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)
|
||||
text, media_ids, _ = self._prepare(post) # edits can't move a status in a thread
|
||||
return self.update_status(remote_id, text, media_ids)
|
||||
|
||||
# --- Backfeed (v2.13.0, ADR-073) ---
|
||||
@@ -359,14 +395,44 @@ class BlueskyClient:
|
||||
current_app.logger.info(f"No link card image for {url}: {e}")
|
||||
return {"$type": "app.bsky.embed.external", "external": external}
|
||||
|
||||
def _reply_ref(self, post: "Post") -> Optional[dict]:
|
||||
"""{'root', 'parent'} for a reply to a Bluesky post (ours or anyone's); None otherwise (v2.20.0)"""
|
||||
if not post.reply_to:
|
||||
return None
|
||||
uri = post.reply_remote_id if (post.reply_remote_id or "").startswith("at://") and \
|
||||
f"/{self.POST}/" in post.reply_remote_id else None
|
||||
try:
|
||||
if uri is None:
|
||||
found = self.resolve_post(post.reply_to)
|
||||
if not found:
|
||||
return None
|
||||
uri = found["uri"]
|
||||
views = self._call("GET", "app.bsky.feed.getPosts", params={"uris": uri}).json().get("posts") or []
|
||||
except SyndicationError as e:
|
||||
current_app.logger.info(f"Could not resolve {post.reply_to} on Bluesky: {e}")
|
||||
return None
|
||||
if not views:
|
||||
return None
|
||||
parent = {"uri": views[0]["uri"], "cid": views[0]["cid"]}
|
||||
root = ((views[0].get("record") or {}).get("reply") or {}).get("root") or parent
|
||||
return {"root": {"uri": root["uri"], "cid": root["cid"]}, "parent": parent}
|
||||
|
||||
def _record(self, post: "Post", text: Optional[str] = None, embed: Optional[dict] = None,
|
||||
anchors: List[tuple] = ()) -> dict:
|
||||
anchors: List[tuple] = (), reply: Optional[dict] = None) -> dict:
|
||||
if text is None:
|
||||
# An article is posted as a teaser (compose_text), so its links aren't in the text
|
||||
body, anchors = (None, []) if post.note.title else \
|
||||
plain_text_links(post.note.content, links="anchor")
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars, body=body)
|
||||
lead = ""
|
||||
if post.reply_to and not reply:
|
||||
# "↩ Replying to <name>", the name linking to the post (v2.20.0)
|
||||
lead = reply_line(post, with_url=False)
|
||||
anchors = [(reply_label(post), post.reply_to), *anchors]
|
||||
text = compose_text(post.note, post.permalink, post.tags, post.max_chars, body=body,
|
||||
lead=lead)
|
||||
record = {"$type": self.POST, "text": text, "createdAt": self._now()}
|
||||
if reply:
|
||||
record["reply"] = reply
|
||||
facets = bluesky_facets(text, anchors)
|
||||
if facets:
|
||||
record["facets"] = facets
|
||||
@@ -464,7 +530,7 @@ class BlueskyClient:
|
||||
existing = self._find_existing(post.permalink)
|
||||
if existing:
|
||||
return existing
|
||||
record = self._record(post)
|
||||
record = self._record(post, reply=self._reply_ref(post))
|
||||
response = self._call("POST", "com.atproto.repo.createRecord",
|
||||
json={"repo": self.did or self.identifier, "collection": self.POST,
|
||||
"record": record})
|
||||
@@ -843,15 +909,26 @@ class ThreadsClient:
|
||||
def _text(self, post: "Post") -> str:
|
||||
# Links written "text (url)"; the first one gets Threads' preview card.
|
||||
# Meta allows 5 different links per post and the permalink is one.
|
||||
body = plain_text(post.note.content, links="inline", max_urls=THREADS_MAX_LINKS - 1)
|
||||
# A reply to someone else's post says so, with its link (v2.20.0);
|
||||
# one to our own Threads post is a native reply instead
|
||||
lead = "" if self._reply_to_id(post) else reply_line(post)
|
||||
links = THREADS_MAX_LINKS - 1 - (1 if lead else 0)
|
||||
body = plain_text(post.note.content, links="inline", max_urls=links)
|
||||
limit = post.max_chars
|
||||
while True:
|
||||
text = compose_text(post.note, post.permalink, [], limit, body=body)
|
||||
text = compose_text(post.note, post.permalink, [], limit, body=body, lead=lead)
|
||||
over = threads_length(text) - post.max_chars
|
||||
if over <= 0:
|
||||
return text
|
||||
limit -= over
|
||||
|
||||
@staticmethod
|
||||
def _reply_to_id(post: "Post") -> Optional[str]:
|
||||
"""Media id of our own Threads post this replies to. The API can't look
|
||||
up other people's posts by URL, so only those thread natively."""
|
||||
remote = post.reply_remote_id or ""
|
||||
return remote if post.reply_to and remote.isdigit() else None
|
||||
|
||||
def _image_container(self, uid: str, media: dict, **extra) -> str:
|
||||
params = {"media_type": "IMAGE", "image_url": media["url"], **extra}
|
||||
if media["description"]:
|
||||
@@ -874,6 +951,8 @@ class ThreadsClient:
|
||||
return self._call("POST", f"{uid}/threads", media_type="TEXT",
|
||||
text=self._repost_text(post))["id"]
|
||||
common = {"text": self._text(post)}
|
||||
if self._reply_to_id(post):
|
||||
common["reply_to_id"] = self._reply_to_id(post)
|
||||
topic = threads_topic(post.tags)
|
||||
if topic:
|
||||
common["topic_tag"] = topic
|
||||
@@ -1011,6 +1090,22 @@ class Post:
|
||||
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
|
||||
reply_to: Optional[str] = None # what a reply answers (v2.20.0)
|
||||
reply_name: Optional[str] = None # its author (or title), from the reply context
|
||||
reply_remote_id: Optional[str] = None # its crosspost on this target, if it's one of ours
|
||||
|
||||
|
||||
def reply_line(post: "Post", with_url: bool = True) -> str:
|
||||
"""'↩ Replying to <who>' (and the URL) for replies that can't thread natively (v2.20.0)"""
|
||||
if not post.reply_to:
|
||||
return ""
|
||||
who = post.reply_name or urlparse(post.reply_to).hostname or post.reply_to
|
||||
return f"↩ Replying to {who}" + (f"\n{post.reply_to}" if with_url else "")
|
||||
|
||||
|
||||
def reply_label(post: "Post") -> str:
|
||||
"""The linked part of a Bluesky reply line"""
|
||||
return post.reply_name or urlparse(post.reply_to).hostname or post.reply_to
|
||||
|
||||
|
||||
def compose_repost_text(post: "Post", comment: str, max_chars: int) -> str:
|
||||
@@ -1200,7 +1295,7 @@ def article_teaser(note) -> str:
|
||||
|
||||
|
||||
def compose_text(note, permalink: str, tags: List[str], max_chars: int,
|
||||
body: Optional[str] = None) -> str:
|
||||
body: Optional[str] = None, lead: str = "") -> str:
|
||||
"""
|
||||
Full note (Markdown unless `body` is given), then the permalink and
|
||||
hashtags; shortened at a word boundary if too long. On short targets the
|
||||
@@ -1221,9 +1316,14 @@ def compose_text(note, permalink: str, tags: List[str], max_chars: int,
|
||||
if getattr(note, "bookmark_of", None):
|
||||
# A bookmark leads with what it bookmarks (v2.9.0)
|
||||
body = f"🔖 {note.bookmark_of}\n\n{body}".strip()
|
||||
if len(body) + len(tail) > max_chars:
|
||||
room = max_chars - len(tail) - 1
|
||||
body = body[:room].rsplit(" ", 1)[0].rstrip() + "…"
|
||||
# A reply that can't thread says what it replies to (v2.20.0); the lead
|
||||
# is kept whole and the body shortened instead
|
||||
lead = lead.strip()
|
||||
head = f"{lead}\n\n" if lead and body else lead
|
||||
if len(head) + len(body) + len(tail) > max_chars:
|
||||
room = max_chars - len(tail) - len(head) - 1
|
||||
body = body[:max(room, 0)].rsplit(" ", 1)[0].rstrip() + "…"
|
||||
body = head + body
|
||||
# A photo post may have no text: start with the link (v2.6.5)
|
||||
return (body + tail).lstrip()
|
||||
|
||||
@@ -1510,6 +1610,48 @@ def _target_title(url: Optional[str]) -> Optional[str]:
|
||||
return " ".join(title.split())[:200] or None
|
||||
|
||||
|
||||
def _own_note_id(url: str) -> Optional[int]:
|
||||
"""The note a URL is, if it's one of ours: its page on this site, or one
|
||||
of its crossposts on any network (v2.20.0)"""
|
||||
db = get_db(current_app)
|
||||
row = db.execute("SELECT note_id FROM syndications WHERE remote_url = ? AND state = 'synced'",
|
||||
(url,)).fetchone()
|
||||
if row:
|
||||
return row["note_id"]
|
||||
site = urlparse(current_app.config.get("SITE_URL", ""))
|
||||
parsed = urlparse(url)
|
||||
parts = [p for p in parsed.path.split("/") if p]
|
||||
if parsed.netloc != site.netloc or len(parts) != 2 or \
|
||||
parts[0] not in ("note", "notes", "article", "articles"):
|
||||
return None
|
||||
row = db.execute("SELECT id FROM notes WHERE slug = ? AND deleted_at IS NULL",
|
||||
(parts[1],)).fetchone()
|
||||
return row["id"] if row else None
|
||||
|
||||
|
||||
def _reply_fields(url: Optional[str], target_id: str) -> dict:
|
||||
"""Post fields for a reply: who it answers, and its crosspost on this target if it's ours"""
|
||||
if not url:
|
||||
return {}
|
||||
fields = {"reply_to": url}
|
||||
try:
|
||||
from starpunk.webmention_queries import get_reply_context
|
||||
context = get_reply_context(url) or {}
|
||||
if context.get("fetch_status") == "fetched":
|
||||
name = context.get("author_name") or context.get("title")
|
||||
fields["reply_name"] = " ".join(name.split())[:100] if name else None
|
||||
note_id = _own_note_id(url)
|
||||
if note_id is not None:
|
||||
row = get_db(current_app).execute(
|
||||
"SELECT remote_id FROM syndications WHERE note_id = ? AND target = ? "
|
||||
"AND state = 'synced' AND remote_id IS NOT NULL", (note_id, target_id)).fetchone()
|
||||
if row:
|
||||
fields["reply_remote_id"] = row["remote_id"]
|
||||
except Exception as e:
|
||||
current_app.logger.info(f"Reply details for {url}: {e}")
|
||||
return fields
|
||||
|
||||
|
||||
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
|
||||
@@ -1538,6 +1680,7 @@ def _reconcile(row, target: Target) -> tuple:
|
||||
kind=note.kind,
|
||||
target_url=note.reacts_to,
|
||||
target_title=_target_title(note.reacts_to),
|
||||
**(_reply_fields(note.in_reply_to, target.id) if note.kind == "note" else {}),
|
||||
)
|
||||
|
||||
if row["remote_id"]:
|
||||
|
||||
Reference in new issue
Block a user