feat: backfeed of responses to crossposts (v2.13.0)
Likes, reposts, quotes and replies to a note's GoToSocial, Bluesky and Threads copies are read back from the silos and stored as webmentions (ADR-073): age-based schedule to 90 days, pruning of withdrawn responses, #nobridge/#nobot opt-outs, admin backfill and Check now, Threads counts, a Quotes group, local avatar copies, and delete tombstones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6aaac982d5
commit
55ce6a1fdd
27 files changed
+1763
-40
No files matched your search
+211
-5
@@ -67,8 +67,9 @@ class MastodonClient:
|
||||
|
||||
def _call(self, method: str, path: str, **kwargs) -> httpx.Response:
|
||||
headers = {**self.headers, **kwargs.pop("headers", {})}
|
||||
url = path if path.startswith(("http://", "https://")) else self.base_url + path
|
||||
try:
|
||||
response = self.http.request(method, self.base_url + path, headers=headers, **kwargs)
|
||||
response = self.http.request(method, url, headers=headers, **kwargs)
|
||||
except httpx.HTTPError as e:
|
||||
raise SyndicationError(f"{method} {path}: {e}")
|
||||
if response.status_code == 404:
|
||||
@@ -76,10 +77,12 @@ class MastodonClient:
|
||||
if response.status_code >= 400:
|
||||
# 4xx other than rate limiting won't fix itself
|
||||
permanent = 400 <= response.status_code < 500 and response.status_code != 429
|
||||
raise SyndicationError(
|
||||
exc = SyndicationError(
|
||||
f"{method} {path}: HTTP {response.status_code} {response.text[:200]}",
|
||||
permanent=permanent,
|
||||
)
|
||||
exc.status = response.status_code
|
||||
raise exc
|
||||
return response
|
||||
|
||||
def upload_media(self, path: Path, mime_type: str, description: str) -> str:
|
||||
@@ -166,6 +169,61 @@ class MastodonClient:
|
||||
text, media_ids = self._prepare(post)
|
||||
return self.update_status(remote_id, text, media_ids)
|
||||
|
||||
# --- Backfeed (v2.13.0, ADR-073) ---
|
||||
|
||||
def _account_id(self) -> str:
|
||||
"""Id of the account StarPunk posts as (its own responses are skipped)"""
|
||||
if not getattr(self, "account_id", None):
|
||||
self.account_id = self._call("GET", "/api/v1/accounts/verify_credentials").json()["id"]
|
||||
return self.account_id
|
||||
|
||||
def _list(self, path: str, cap: int) -> tuple:
|
||||
"""Items of a paginated list (Link: rel="next"). Returns (items, complete)."""
|
||||
items, url, params = [], path, {"limit": 80}
|
||||
while url:
|
||||
response = self._call("GET", url, params=params)
|
||||
items.extend(response.json() or [])
|
||||
if len(items) >= cap:
|
||||
return items[:cap], False
|
||||
url, params = (response.links.get("next") or {}).get("url"), None
|
||||
return items, True
|
||||
|
||||
@staticmethod
|
||||
def _author(account: dict) -> dict:
|
||||
return {
|
||||
"author_id": account.get("id") or "",
|
||||
"author_name": account.get("display_name") or account.get("username") or account.get("acct") or "",
|
||||
"author_url": account.get("url") or "",
|
||||
"author_photo": account.get("avatar_static") or account.get("avatar"),
|
||||
"author_bio": account.get("note") or "",
|
||||
}
|
||||
|
||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
||||
"""Likes, boosts and public direct replies of one of our statuses"""
|
||||
from starpunk.backfeed import Harvest, Response
|
||||
|
||||
me = self._account_id()
|
||||
found, complete = [], True
|
||||
for kind, path, fragment in (("like", "favourited_by", "liked-by"),
|
||||
("repost", "reblogged_by", "reposted-by")):
|
||||
accounts, done = self._list(f"/api/v1/statuses/{remote_id}/{path}", cap)
|
||||
complete = complete and done
|
||||
for account in accounts:
|
||||
if account.get("id") == me:
|
||||
continue
|
||||
found.append(Response(kind=kind, source_url=f"{remote_url}#{fragment}-{account['id']}",
|
||||
remote_id=account["id"], **self._author(account)))
|
||||
context = self._call("GET", f"/api/v1/statuses/{remote_id}/context").json() or {}
|
||||
for status in context.get("descendants") or []:
|
||||
account = status.get("account") or {}
|
||||
if (status.get("in_reply_to_id") != remote_id or status.get("visibility") != "public"
|
||||
or account.get("id") == me):
|
||||
continue
|
||||
found.append(Response(kind="reply", source_url=status.get("url") or status["uri"],
|
||||
remote_id=status["id"], content_html=status.get("content") or "",
|
||||
published=status.get("created_at"), **self._author(account)))
|
||||
return Harvest(found, complete)
|
||||
|
||||
def delete(self, remote_id: str) -> None:
|
||||
action, _, status_id = remote_id.partition(":")
|
||||
if action in self.NATIVE and status_id:
|
||||
@@ -227,9 +285,11 @@ class BlueskyClient:
|
||||
if response.status_code < 400:
|
||||
return
|
||||
permanent = 400 <= response.status_code < 500 and response.status_code != 429
|
||||
raise SyndicationError(
|
||||
exc = SyndicationError(
|
||||
f"{nsid}: HTTP {response.status_code} {response.text[:200]}", permanent=permanent
|
||||
)
|
||||
exc.status = response.status_code
|
||||
raise exc
|
||||
|
||||
def _login(self) -> None:
|
||||
response = None
|
||||
@@ -405,6 +465,94 @@ class BlueskyClient:
|
||||
def update(self, remote_id: str, post: "Post") -> dict:
|
||||
raise NotImplementedError("Bluesky posts can't be edited")
|
||||
|
||||
# --- Backfeed (v2.13.0, ADR-073) ---
|
||||
|
||||
def _paged(self, nsid: str, params: dict, key: str, cap: int) -> tuple:
|
||||
"""Items of a cursor-paginated XRPC list. Returns (items, complete)."""
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
query = {**params, "limit": 100}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
data = self._call("GET", nsid, params=query).json()
|
||||
page = data.get(key) or []
|
||||
items.extend(page)
|
||||
if len(items) >= cap:
|
||||
return items[:cap], False
|
||||
cursor = data.get("cursor")
|
||||
if not cursor or not page:
|
||||
return items, True
|
||||
|
||||
@staticmethod
|
||||
def _author(profile: dict) -> dict:
|
||||
handle = profile.get("handle") or profile.get("did") or ""
|
||||
return {
|
||||
"author_id": profile.get("did") or "",
|
||||
"author_name": profile.get("displayName") or handle,
|
||||
"author_url": f"https://bsky.app/profile/{handle}",
|
||||
"author_photo": profile.get("avatar"),
|
||||
"author_bio": profile.get("description") or "",
|
||||
# The author asked not to be shown to people who aren't logged in
|
||||
"opted_out": any(label.get("val") == "!no-unauthenticated"
|
||||
for label in profile.get("labels") or []),
|
||||
}
|
||||
|
||||
def _post_response(self, kind: str, view: dict):
|
||||
from starpunk.backfeed import Response, facets_html
|
||||
|
||||
author = view.get("author") or {}
|
||||
record = view.get("record") or {}
|
||||
rkey = view["uri"].rsplit("/", 1)[1]
|
||||
return Response(
|
||||
kind=kind,
|
||||
source_url=f"https://bsky.app/profile/{author.get('handle') or author.get('did')}/post/{rkey}",
|
||||
remote_id=view["uri"],
|
||||
content_html=facets_html(record.get("text") or "", record.get("facets") or []),
|
||||
published=record.get("createdAt") or view.get("indexedAt"),
|
||||
**self._author(author),
|
||||
)
|
||||
|
||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
||||
"""Likes, reposts, quotes and direct replies of one of our posts"""
|
||||
from starpunk.backfeed import Harvest, Response
|
||||
|
||||
if not self.did:
|
||||
with self._lock:
|
||||
self._login()
|
||||
found, complete = [], True
|
||||
likes, done = self._paged("app.bsky.feed.getLikes", {"uri": remote_id}, "likes", cap)
|
||||
complete = complete and done
|
||||
for like in likes:
|
||||
actor = like.get("actor") or {}
|
||||
found.append(Response(kind="like", source_url=f"{remote_url}#liked-by-{actor.get('did')}",
|
||||
remote_id=actor.get("did") or "", published=like.get("createdAt"),
|
||||
**self._author(actor)))
|
||||
reposters, done = self._paged("app.bsky.feed.getRepostedBy", {"uri": remote_id},
|
||||
"repostedBy", cap)
|
||||
complete = complete and done
|
||||
for actor in reposters:
|
||||
found.append(Response(kind="repost", source_url=f"{remote_url}#reposted-by-{actor.get('did')}",
|
||||
remote_id=actor.get("did") or "", **self._author(actor)))
|
||||
quotes, done = self._paged("app.bsky.feed.getQuotes", {"uri": remote_id}, "posts", cap)
|
||||
complete = complete and done
|
||||
posts = [self._post_response("quote", view) for view in quotes]
|
||||
thread = self._call("GET", "app.bsky.feed.getPostThread",
|
||||
params={"uri": remote_id, "depth": 1, "parentHeight": 0}).json()
|
||||
for item in (thread.get("thread") or {}).get("replies") or []:
|
||||
if item.get("post"): # skips blocked and deleted replies
|
||||
posts.append(self._post_response("reply", item["post"]))
|
||||
# Post views carry no bio; fetch them to honour #nobridge
|
||||
dids = list({p.author_id for p in posts if p.author_id})
|
||||
bios = {}
|
||||
for i in range(0, len(dids), 25):
|
||||
profiles = self._call("GET", "app.bsky.actor.getProfiles",
|
||||
params={"actors": dids[i:i + 25]}).json().get("profiles") or []
|
||||
bios.update({p["did"]: p.get("description") or "" for p in profiles})
|
||||
for post in posts:
|
||||
post.author_bio = bios.get(post.author_id, "")
|
||||
found.extend(posts)
|
||||
return Harvest([r for r in found if r.author_id != self.did], complete)
|
||||
|
||||
def delete(self, remote_id: str) -> None:
|
||||
# at://<did>/app.bsky.feed.post/<rkey>; deleting a missing record succeeds
|
||||
repo, collection, rkey = remote_id[len("at://"):].split("/", 2)
|
||||
@@ -513,7 +661,7 @@ def page_card(http: httpx.Client, url: str) -> dict:
|
||||
return card
|
||||
|
||||
|
||||
THREADS_API = "https://graph.threads.net/v1.0"
|
||||
THREADS_API = "https://graph.threads.com/v1.0" # Meta's current host (v2.13.0)
|
||||
THREADS_IMAGE_TYPES = {"image/jpeg", "image/png"}
|
||||
THREADS_IMAGE_LIMIT = 8_000_000
|
||||
THREADS_MAX_LINKS = 5
|
||||
@@ -775,6 +923,57 @@ class ThreadsClient:
|
||||
def update(self, remote_id: str, post: "Post") -> dict:
|
||||
raise NotImplementedError("Threads posts can't be edited through the API")
|
||||
|
||||
# --- Backfeed (v2.13.0, ADR-073) ---
|
||||
|
||||
REPLY_FIELDS = "id,text,username,permalink,timestamp,profile_picture_url,hide_status"
|
||||
SHOWN = (None, "NOT_HUSHED", "UNHUSHED") # hide_status values of replies nobody hid
|
||||
|
||||
def responses(self, remote_id: str, remote_url: str, cap: int = 1000):
|
||||
"""
|
||||
Direct replies to one of our posts, and its like/repost/quote counts.
|
||||
The API doesn't say who liked, reposted or quoted (ADR-073 Decision 7).
|
||||
"""
|
||||
from starpunk.backfeed import Harvest, Response, text_html
|
||||
|
||||
self._me()
|
||||
replies, after, complete = [], None, True
|
||||
while True:
|
||||
params = {"fields": self.REPLY_FIELDS}
|
||||
if after:
|
||||
params["after"] = after
|
||||
data = self._call("GET", f"{remote_id}/replies", **params)
|
||||
page = data.get("data") or []
|
||||
replies.extend(page)
|
||||
if len(replies) >= cap:
|
||||
replies, complete = replies[:cap], False
|
||||
break
|
||||
paging = data.get("paging") or {}
|
||||
after = (paging.get("cursors") or {}).get("after")
|
||||
if not page or not after or not paging.get("next"):
|
||||
break
|
||||
found = []
|
||||
for reply in replies:
|
||||
username = reply.get("username")
|
||||
# Private accounts have no username or permalink: nothing public to show
|
||||
if (not username or not reply.get("permalink") or username == self.username
|
||||
or reply.get("hide_status") not in self.SHOWN):
|
||||
continue
|
||||
found.append(Response(
|
||||
kind="reply", source_url=reply["permalink"], remote_id=reply["id"],
|
||||
author_id=username, author_name=username,
|
||||
author_url=f"https://www.threads.com/@{username}",
|
||||
author_photo=reply.get("profile_picture_url"),
|
||||
content_html=text_html(reply.get("text") or ""),
|
||||
published=reply.get("timestamp"),
|
||||
))
|
||||
insights = self._call("GET", f"{remote_id}/insights", metric="likes,reposts,quotes")
|
||||
counts = {}
|
||||
for metric in insights.get("data") or []:
|
||||
values = metric.get("values") or [{}]
|
||||
counts[metric.get("name")] = int((values[0] or {}).get("value") or 0)
|
||||
return Harvest(found, complete, counts={k: counts.get(k, 0)
|
||||
for k in ("likes", "reposts", "quotes")})
|
||||
|
||||
def delete(self, remote_id: str) -> None:
|
||||
try:
|
||||
self._call("DELETE", remote_id)
|
||||
@@ -1381,12 +1580,19 @@ class SyndicationWorker(threading.Thread):
|
||||
|
||||
def run(self):
|
||||
while not self._stop_event.is_set():
|
||||
handled = 0
|
||||
try:
|
||||
with self.app.app_context():
|
||||
handled = process_due()
|
||||
except Exception as e:
|
||||
self.app.logger.error(f"Syndication worker error: {e}", exc_info=True)
|
||||
handled = 0
|
||||
# Responses to the copies (v2.13.0, ADR-073), after any crossposts
|
||||
try:
|
||||
from starpunk import backfeed
|
||||
with self.app.app_context():
|
||||
handled += backfeed.process_due()
|
||||
except Exception as e:
|
||||
self.app.logger.error(f"Backfeed error: {e}", exc_info=True)
|
||||
if handled == 0:
|
||||
self._stop_event.wait(self.poll_interval)
|
||||
|
||||
|
||||
Reference in new issue
Block a user